feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
||||
|
||||
执行过程由 action 决定(UI 的两个开关派生):
|
||||
action='download' → 只下载:登录经营宝,按勾选下载打款记录 / 团购收益明细 / 预订收益明细;
|
||||
action='reconcile' → 只核对:**不开浏览器**,直接用本机最新的台账与收益明细并入台账、
|
||||
更新核对统计(适合数据已下载、只想重算的场景);
|
||||
action='all' → 下载后再核对(默认)。
|
||||
|
||||
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
||||
不涉及任何签名算法。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, meituan_login, payment_download, profit_download
|
||||
from .logic import merge_ledger, stat_links
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(str(s).strip(), fmt).date()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pair(raw_from, raw_to):
|
||||
"""解析一组日期:都空=昨天~今天;只给一端=单日;起止颠倒自动换序。"""
|
||||
d1 = _parse_day(raw_from) if raw_from else None
|
||||
d2 = _parse_day(raw_to) if raw_to else None
|
||||
if d1 is None and d2 is None:
|
||||
return ((date.today() - timedelta(days=1)).isoformat(), date.today().isoformat())
|
||||
if d1 is None:
|
||||
d1 = d2
|
||||
if d2 is None:
|
||||
d2 = d1
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
return d1.isoformat(), d2.isoformat()
|
||||
|
||||
|
||||
def _resolve_action(fields):
|
||||
"""决定本次做什么:download / reconcile / all。
|
||||
|
||||
UI 会直接给 action;老配置(无 action)按开关推导,缺省视为全流程。
|
||||
"""
|
||||
action = str(fields.get('action') or '').strip().lower()
|
||||
if action in ('download', 'reconcile', 'all'):
|
||||
return action
|
||||
do_download = fields.get('do_download')
|
||||
do_reconcile = fields.get('do_reconcile')
|
||||
do_download = True if do_download is None else bool(do_download)
|
||||
do_reconcile = True if do_reconcile is None else bool(do_reconcile)
|
||||
if do_download and do_reconcile:
|
||||
return 'all'
|
||||
if do_download:
|
||||
return 'download'
|
||||
if do_reconcile:
|
||||
return 'reconcile'
|
||||
return ''
|
||||
|
||||
|
||||
class Xq0041Plugin(ScenePlugin):
|
||||
id = 'xq0041'
|
||||
name = '新美大平台核对'
|
||||
version = '1.1.2'
|
||||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
||||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
||||
'并给核对统计表补当天的团购统计表链接')
|
||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0041']
|
||||
permissions = {'platforms': []}
|
||||
# 与 plugin.json.fields 一致(ui=true,前端按此渲染表单)
|
||||
fields = {
|
||||
'action': {'type': 'string', 'title': '执行过程', 'default': 'all',
|
||||
'enum': ['all', 'download', 'reconcile']},
|
||||
'do_download': {'type': 'boolean', 'title': '下载数据', 'default': True},
|
||||
'do_reconcile': {'type': 'boolean', 'title': '更新核对', 'default': True},
|
||||
'pay_enabled': {'type': 'boolean', 'title': '下载打款记录', 'default': True},
|
||||
'pay_date_from': {'type': 'string', 'title': '打款记录-开始日期', 'default': ''},
|
||||
'pay_date_to': {'type': 'string', 'title': '打款记录-结束日期', 'default': ''},
|
||||
'profit_group': {'type': 'boolean', 'title': '下载团购收益明细', 'default': True},
|
||||
'profit_booking': {'type': 'boolean', 'title': '下载预订收益明细', 'default': True},
|
||||
'profit_date_from': {'type': 'string', 'title': '收益明细-开始日期', 'default': ''},
|
||||
'profit_date_to': {'type': 'string', 'title': '收益明细-结束日期', 'default': ''},
|
||||
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
||||
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
||||
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx):
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(fields.get('debug_mode'))
|
||||
|
||||
# ---------- 参数 ----------
|
||||
action = _resolve_action(fields)
|
||||
if not action:
|
||||
raise RuntimeError('请至少选择一个执行过程(下载数据 / 更新核对)')
|
||||
do_download = action in ('all', 'download')
|
||||
do_reconcile = action in ('all', 'reconcile')
|
||||
|
||||
codes = []
|
||||
if fields.get('profit_group', True):
|
||||
codes.append(1)
|
||||
if fields.get('profit_booking', True):
|
||||
codes.append(11)
|
||||
pay_on = bool(fields.get('pay_enabled', True))
|
||||
|
||||
dry_run = bool(fields.get('dry_run'))
|
||||
run_merge = bool(fields.get('run_merge', True))
|
||||
run_links = bool(fields.get('run_links', True))
|
||||
save_dir = str(fields.get('save_dir') or config.WORK_DIR).strip().strip('"') or config.WORK_DIR
|
||||
|
||||
if do_download and not pay_on and not codes:
|
||||
raise RuntimeError('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||
|
||||
# 并入台账依赖团购收益明细(台账只收团购口径)
|
||||
if do_reconcile and run_merge and not codes and do_download:
|
||||
config.log('未勾选团购收益明细,本次跳过「并入台账」', 'WARN')
|
||||
run_merge = False
|
||||
|
||||
pay_from, pay_to = _resolve_pair(fields.get('pay_date_from'), fields.get('pay_date_to'))
|
||||
profit_from, profit_to = _resolve_pair(fields.get('profit_date_from'),
|
||||
fields.get('profit_date_to'))
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
plan = []
|
||||
if do_download:
|
||||
if pay_on:
|
||||
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
||||
if codes:
|
||||
name = '/'.join(n for c, n in ((1, '团购'), (11, '预订')) if c in codes)
|
||||
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
||||
if do_reconcile:
|
||||
plan.append('并入台账' if run_merge else '')
|
||||
plan.append('更新核对统计' if run_links else '')
|
||||
plan = [p for p in plan if p]
|
||||
config.log(('本次执行:' + ';'.join(plan) if plan else '本次没有可执行的动作')
|
||||
+ (f';目录 {save_dir}' if do_download else '')
|
||||
+ ('(只核对不写入)' if dry_run else ''))
|
||||
|
||||
detail = {'action': action, 'pay': None, 'profit': None, 'merge': None, 'links': None}
|
||||
files = []
|
||||
|
||||
# ---------- 1~3:登录 + 下载 ----------
|
||||
if do_download:
|
||||
ctx.progress(2)
|
||||
page = browser.open_page()
|
||||
try:
|
||||
ok, msg = meituan_login.ensure_login(page)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
ctx.progress(20 if do_reconcile else 30)
|
||||
|
||||
if pay_on:
|
||||
r1 = payment_download.download(page, pay_from, pay_to, save_dir, dry_run)
|
||||
if not r1.get('ok'):
|
||||
raise RuntimeError(f'打款记录下载失败:{r1.get("message")}')
|
||||
config.log(r1.get('message') or '')
|
||||
if r1.get('path'):
|
||||
files.append(r1['path'])
|
||||
detail['pay'] = r1
|
||||
ctx.progress(45 if do_reconcile else 65)
|
||||
|
||||
if codes:
|
||||
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
||||
codes, dry_run)
|
||||
if not r2.get('ok'):
|
||||
raise RuntimeError(f'收益明细下载失败:{r2.get("message")}')
|
||||
config.log(r2.get('message') or '')
|
||||
files.extend(r2.get('paths') or [])
|
||||
detail['profit'] = r2
|
||||
ctx.progress(60 if do_reconcile else 95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
# ---------- 4~5:并入台账 + 更新核对(不依赖浏览器) ----------
|
||||
if do_reconcile:
|
||||
ctx.progress(65 if do_download else 10)
|
||||
if run_merge:
|
||||
m = merge_ledger.run(dry_run=dry_run)
|
||||
config.log(m.get('message') or '')
|
||||
detail['merge'] = m
|
||||
if not m.get('ok'):
|
||||
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
||||
ctx.progress(85 if do_download else 60)
|
||||
|
||||
if run_links:
|
||||
# 纯核对时让后端按本机最新明细文件的日期推断(跟随实际数据);
|
||||
# 有下载则用本次的收益明细区间。
|
||||
link_from, link_to = (profit_from, profit_to) if do_download else (None, None)
|
||||
s = stat_links.run(link_from, link_to, dry_run=dry_run)
|
||||
config.log(s.get('message') or '')
|
||||
detail['links'] = s
|
||||
if not s.get('ok'):
|
||||
config.log(f'更新核对统计失败:{s.get("message")}', 'WARN')
|
||||
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
parts = []
|
||||
if files:
|
||||
parts.append(f'下载 {len(files)} 个文件')
|
||||
if detail['merge'] and detail['merge'].get('appended'):
|
||||
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
||||
if detail['links'] and detail['links'].get('rows'):
|
||||
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
||||
if not parts:
|
||||
parts.append('执行完成')
|
||||
if dry_run:
|
||||
parts.insert(0, '[只核对不写入]')
|
||||
return {
|
||||
'summary': ';'.join(parts),
|
||||
'detail': detail,
|
||||
'path': files[0] if files else '',
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0041Plugin())
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0041 新美大平台核对 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
各业务模块统一经 config.log() / config.progress() 输出,由 run() 启动时注入 ctx。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
# ==================== 平台:美团经营宝 ====================
|
||||
HOME_URL = 'https://ecom.meituan.com/'
|
||||
|
||||
# 登录成功的落地页:经营宝按商家类型分流(kdb → ecom.meituan.com/meishi,
|
||||
# dp → e.dianping.com/app/...)。命中任一即已登录。
|
||||
BACKEND_HINTS = (
|
||||
'ecom.meituan.com/meishi',
|
||||
'e.dianping.com/app/',
|
||||
'e.dianping.com/meishi/',
|
||||
)
|
||||
LOGIN_PAGE_HINT = 'bizaccount/login.html'
|
||||
BIZ_CHOICE_HINT = 'bizaccount/biz-choice.html'
|
||||
PASSPORT_HINTS = (
|
||||
'passport.meituan.com', 'epassport.meituan.com', 'unifiedlogin', 'ssologin',
|
||||
'passport.dianping.com', 'account.dianping.com/login', 'e.dianping.com/login',
|
||||
)
|
||||
|
||||
# ==================== 打款记录(h5 账单页,iframe 内 smartBill 接口) ====================
|
||||
PAYMENT_PAGE_URL = (
|
||||
'https://e.dianping.com/app/merchant-platform/02a5e2f40d5d4b0'
|
||||
'?iUrl=Ly9oNS5kaWFucGluZy5jb20vL2FwcC9tZXJjaGFudC1iaWxsLXN0YXRpYy9pbmRleC5odG1sIy9wYXltZW50cmVjb3Jk')
|
||||
PAYMENT_LIST_API = 'https://e.dianping.com/gw/smartBill/paymentlist'
|
||||
PAYMENT_DOWNLOAD_API = 'https://e.dianping.com/gw/smartBill/paymentdownload'
|
||||
PAYMENT_HISTORY_API = 'https://e.dianping.com/gw/smartBill/paymenthistory'
|
||||
PAYMENT_FILE_TYPE = 6 # 6 = 打款记录
|
||||
PAYMENT_NAME_KEY = '打款记录'
|
||||
|
||||
# ==================== 收益明细(PC 商户中心 downloadManagement 接口) ====================
|
||||
PROFIT_PAGE_URL = 'https://e.dianping.com/finance/web/payment/download/list'
|
||||
SHOP_API = 'https://e.dianping.com/smartBill/queryAllShopIds'
|
||||
PRODUCT_API = 'https://e.dianping.com/finance/ajax/downloadManagement/productCodeList'
|
||||
PROFIT_REQUEST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/request'
|
||||
PROFIT_LIST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/list'
|
||||
PROFIT_LINK_API = 'https://e.dianping.com/finance/ajax/downloadManagement/downloadLink'
|
||||
PROFIT_FILE_TYPE = 201 # 201 = 收益明细
|
||||
|
||||
# ==================== 台账 ====================
|
||||
WORK_DIR = r'D:\资料\财务\新美大平台核对' # 账单 + 台账统一目录
|
||||
LEDGER_GLOB = '新美大到账统计*.xlsx'
|
||||
LEDGER_SHEET = '金色印象--新美大导出(收)'
|
||||
STAT_SHEET = '新美大核对统计'
|
||||
TIME_COL = '验券/退款/调整时间'
|
||||
DETAIL_GLOB = '团购收益明细_*.xlsx'
|
||||
HEADER_ROW = 2
|
||||
DATA_START_ROW = 3
|
||||
|
||||
# 「新美大核对统计」V/W 列的外部工作簿(与台账历史 62 条链接一致)
|
||||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
||||
LINK_BOOK = '马敏团购总表'
|
||||
LINK_SHEET = '资金组取数'
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含选商家)超时
|
||||
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
|
||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
||||
POLL_SECONDS = 2
|
||||
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
||||
REUSE_MAX_AGE_MIN = 10 # 账单复用时效:记录生成时间距今 ≤ N 分钟才复用
|
||||
RETRY_MAX = 3
|
||||
HEADLESS = False # 人工登录必须可见浏览器
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'meituan_tokens.json')
|
||||
META_FILE = os.path.join(SESSIONS_DIR, 'meituan_session_meta.json')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0041')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶。
|
||||
|
||||
登录需要人工操作(账号密码 / 短信 / 扫码 / 选商家),窗口被其它窗口遮挡或最小化时
|
||||
用户容易漏看;置顶保证它一直在最前面。失败仅告警,不影响流程。
|
||||
"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as e:
|
||||
log(f'设置窗口全屏失败(忽略):{e}', 'WARN')
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
_set_topmost(page.process_id)
|
||||
except Exception as e:
|
||||
log(f'设置窗口置顶失败(忽略):{e}', 'WARN')
|
||||
|
||||
|
||||
def _set_topmost(pid):
|
||||
"""把指定进程的主窗口设为 HWND_TOPMOST(Win32 SetWindowPos,仅 Windows)。"""
|
||||
if not pid:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
|
||||
hwnds = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def _collect(hwnd, _lparam):
|
||||
if user32.IsWindowVisible(hwnd) and user32.GetWindowTextLengthW(hwnd) > 0:
|
||||
proc = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(proc))
|
||||
if proc.value == pid:
|
||||
hwnds.append(hwnd)
|
||||
return True
|
||||
|
||||
user32.EnumWindows.argtypes = [ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),
|
||||
wintypes.LPARAM]
|
||||
user32.EnumWindows(_collect, 0)
|
||||
|
||||
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint]
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(hwnd, wintypes.HWND(-1), 0, 0, 0, 0, 0x0001 | 0x0002) # NOSIZE | NOMOVE
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_debug(on):
|
||||
global _debug
|
||||
_debug = bool(on)
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _debug
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
text = f'[{time.strftime("%H:%M:%S")}] {msg}'
|
||||
if level == 'DEBUG' and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f'[{level}] {text}')
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:登录态、打款记录与收益明细的下载。"""
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0041,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
import os
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。
|
||||
|
||||
返回 (status:int, text:str)。
|
||||
"""
|
||||
import json as _json
|
||||
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):
|
||||
import json as _json
|
||||
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 download_file(link, save_path):
|
||||
"""S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。"""
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
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(link, 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')
|
||||
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 read_xlsx_summary(path):
|
||||
"""读 sheet 名/行列数,确认文件有效。"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(path, read_only=True, data_only=True)
|
||||
ws = wb.worksheets[0]
|
||||
info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column}
|
||||
wb.close()
|
||||
return info
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""美团经营宝登录态:打开官方页面 → 人工登录(含选商家)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
为什么不用 requests 校验:经营宝所有业务接口带 mtgsig 动态签名(页面 H5guard 秒级生成),
|
||||
requests 复刻必然 403。登录态有效性只由浏览器判定,取数也一律在页面上下文发请求。
|
||||
|
||||
实测登录链路(2026-10):
|
||||
ecom.meituan.com → 外壳,未登录也先进这里
|
||||
ecom.meituan.com/meishi → 前端异步鉴权,约 20s 后才跳走,不可当已登录
|
||||
.../bizaccount/login.html → 真·未登录
|
||||
.../bizaccount/biz-choice.html → 账号已登录、待选商家
|
||||
e.dianping.com/app/... → 选完商家进后台(登录完成,dp 商家)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login / biz_choice / backend / other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if config.LOGIN_PAGE_HINT in low or any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
if config.BIZ_CHOICE_HINT in low:
|
||||
return 'biz_choice'
|
||||
if any(h in low for h in config.BACKEND_HINTS):
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _platform_cookie_header(cookies):
|
||||
skip = ('passport', 'certificates', 'report', 'lx', 'dreport')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and any(d in (c.get('domain') or '') for d in ('meituan.com', 'dianping.com'))
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _platform_cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 选商家」。返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = biz_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
|
||||
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
|
||||
biz_hint_at = time.time()
|
||||
config.log('账号已登录,请在页面上选择要进入的商家(脚本不自动选,避免进错店)')
|
||||
|
||||
if state == 'backend':
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进入商家后台,等待 {config.BACKEND_STABLE}s 确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('又回到登录/选商家页,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page):
|
||||
"""确保 page 已进入商家后台;必要时停在前台等人工登录。"""
|
||||
config.log(f'打开经营宝:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用一个短窗口:profile 里残留会话能直接进后台就不用打扰
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend':
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state in ('login', 'biz_choice'):
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
config.log(f'需要人工登录,最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' + ', '.join(sorted({c.get('name') for c in cookies if c.get('name')})),
|
||||
'WARN')
|
||||
return False, '登录超时(未进入商家后台)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""打款记录下载(h5 账单页,iframe 内 smartBill 三个接口)。
|
||||
|
||||
链路(实测):
|
||||
① 查询 POST /gw/smartBill/paymentlist body{payTime,productCodeList,payStatusList,shopList,pageIndex,pageSize}
|
||||
② 生成 POST /gw/smartBill/paymentdownload body 同上 + downloadFileType=6
|
||||
③ 记录 GET /gw/smartBill/paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6
|
||||
(必须带 downloadFileType + 分页参数,缺了返回 code=500)
|
||||
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
|
||||
|
||||
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
def _find_frame(page, timeout=30):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for f in page.get_frames():
|
||||
try:
|
||||
if 'merchant-bill' in (f.url or ''):
|
||||
return f
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _history_items(frame):
|
||||
url = (f'{config.PAYMENT_HISTORY_API}?pageIndex=0&pageSize=20'
|
||||
f'&downloadFileType={config.PAYMENT_FILE_TYPE}')
|
||||
data = browser.api_json(frame, 'GET', url) or {}
|
||||
return (data.get('data') or {}).get('details') or []
|
||||
|
||||
|
||||
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 download(page, d_from, d_to, save_dir, dry_run=False):
|
||||
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
match_key = d_from
|
||||
|
||||
config.log(f'打开打款记录页:{config.PAYMENT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PAYMENT_PAGE_URL)
|
||||
frame = _find_frame(page)
|
||||
if not frame:
|
||||
return {'ok': False, 'message': '未找到账单 iframe(登录态可能已失效)'}
|
||||
config.log(f'账单 iframe:{frame.url}', 'DEBUG')
|
||||
|
||||
# ① 先查询(页面同款顺序:查询出数据后下载按钮才可用)
|
||||
query = {
|
||||
'payTime': f'{d_from},{d_to}',
|
||||
'productCodeList': [], 'payStatusList': [], 'shopList': [],
|
||||
'pageIndex': 0, 'pageSize': 10,
|
||||
}
|
||||
q = browser.api_json(frame, 'POST', config.PAYMENT_LIST_API, query)
|
||||
if q is None:
|
||||
return {'ok': False, 'message': '打款记录查询失败'}
|
||||
qdata = q.get('data') or {}
|
||||
total = qdata.get('totalCount')
|
||||
details = qdata.get('details') or []
|
||||
config.log(f'查询 {d_from}~{d_to}:totalCount={total}')
|
||||
if details:
|
||||
s = details[0]
|
||||
config.log(f' 首条 {s.get("payTime")} | {s.get("productCodeName")} | '
|
||||
f'{s.get("amount")} | {s.get("payStatusName")}')
|
||||
if not total:
|
||||
return {'ok': False, '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 = fresh[0]
|
||||
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
|
||||
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
|
||||
elif cands:
|
||||
config.log('同区间记录已过期,重新生成以取最新数据')
|
||||
|
||||
# ③ 生成 + 轮询
|
||||
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}'}
|
||||
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history_items(frame)
|
||||
for it in items:
|
||||
if it.get('id') in before_ids:
|
||||
continue
|
||||
if match_key not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
target = it
|
||||
break
|
||||
if target:
|
||||
break
|
||||
config.log(' 等待账单生成…')
|
||||
|
||||
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 内未拿到可下载记录'}
|
||||
|
||||
link = target.get('downloadLink')
|
||||
if not link:
|
||||
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
|
||||
|
||||
path = os.path.join(save_dir, f'{config.PAYMENT_NAME_KEY}_{tag}.xlsx')
|
||||
config.log(f'下载 → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': '打款记录下载失败'}
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
|
||||
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|
||||
@@ -0,0 +1,189 @@
|
||||
# -*- 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 直下)
|
||||
|
||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
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):
|
||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||
|
||||
返回 {ok, paths, 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)
|
||||
|
||||
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 "无"}),重新生成以取最新数据')
|
||||
|
||||
# ③ 生成
|
||||
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}'}
|
||||
|
||||
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]
|
||||
if ready:
|
||||
targets = ready
|
||||
if not pending:
|
||||
break
|
||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
||||
len(ready), len(pending),
|
||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
||||
else:
|
||||
config.log(' 等待生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||
|
||||
if not targets:
|
||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
||||
|
||||
# ④ 逐个下载(同类型去重取最新)
|
||||
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
|
||||
path = os.path.join(save_dir, f'{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:
|
||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""逻辑层:台账增量合并、核对统计 V/W 外部链接。"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账增量合并:把收益明细里比台账更新的行追加到「金色印象--新美大导出(收)」。
|
||||
|
||||
规则(业务口径):
|
||||
1. 找最新月份的台账(新美大到账统计YYYY.M月新.xlsx,排除备份文件);
|
||||
2. 取该 sheet「验券/退款/调整时间」列的最大时间;
|
||||
3. 明细里该列 < 最大时间的行剔除,其余按表头对齐追加;
|
||||
4. 从**真实数据末行**的下一行开始写(max_row 被尾部公式空行撑大,不能直接用);
|
||||
5. 台账第 32 列之后(AF~AP)全是公式 —— 几十万行不可能人工下拉,必须由脚本生成:
|
||||
模板行里内联公式直接按行号平移;共享公式(<f t="shared" si="N"/>)先按 si
|
||||
找到同列主定义,再从定义行平移到新行。效果与手工下拉完全一致。
|
||||
|
||||
写入方式:只改目标 sheet 的 XML(清掉尾部空行、在 </sheetData> 前插入新行、更新 dimension),
|
||||
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 62 个外部链接,openpyxl 全量保存会丢透视表,
|
||||
且 645MB 的 sheet 也吃不下内存。
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
|
||||
_CELL_RE = re.compile(rb'<c r="([A-Z]+)(\d+)"([^>]*?)>(.*?)</c>', re.S)
|
||||
_F_RE = re.compile(rb'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
|
||||
|
||||
# ==================== 通用小工具 ====================
|
||||
def _to_dt(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, date):
|
||||
return datetime(v.year, v.month, v.day)
|
||||
s = str(v).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
|
||||
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(s, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _month_key(path):
|
||||
m = _MONTH_RE.search(os.path.basename(path))
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
|
||||
|
||||
|
||||
def _pick_latest(pattern, by_month=True):
|
||||
"""排除备份文件(`_备份20261027_155650.xlsx` 同样匹配 glob,曾误当成台账)。"""
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
if by_month:
|
||||
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
|
||||
else:
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _header_index(header):
|
||||
out = {}
|
||||
for i, v in enumerate(header):
|
||||
if v is None:
|
||||
continue
|
||||
name = str(v).strip()
|
||||
if name and name not in out:
|
||||
out[name] = i
|
||||
return out
|
||||
|
||||
|
||||
def _col_letter(n):
|
||||
s = ''
|
||||
while n > 0:
|
||||
n, r = divmod(n - 1, 26)
|
||||
s = chr(65 + r) + s
|
||||
return s
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _xml_text(v):
|
||||
return (str(v).replace('&', '&').replace('<', '<')
|
||||
.replace('>', '>').replace('"', '"'))
|
||||
|
||||
|
||||
def _cell_xml(col, row, value, style=None):
|
||||
letter = _col_letter(col) if isinstance(col, int) else col
|
||||
ref = f'{letter}{row}'
|
||||
s_attr = f' s="{style}"' if style else ''
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, bool):
|
||||
return f'<c r="{ref}"{s_attr} t="b"><v>{1 if value else 0}</v></c>'
|
||||
if isinstance(value, (int, float)):
|
||||
num = repr(round(float(value), 12)) if isinstance(value, float) else str(value)
|
||||
return f'<c r="{ref}"{s_attr}><v>{num}</v></c>'
|
||||
text = str(value)
|
||||
if text == '':
|
||||
return ''
|
||||
return f'<c r="{ref}"{s_attr} t="inlineStr"><is><t xml:space="preserve">{_xml_text(text)}</t></is></c>'
|
||||
|
||||
|
||||
# ==================== 公式:模板行 + 共享公式 ====================
|
||||
def _parse_shared_defs(chunk):
|
||||
"""共享公式主定义 {si: (定义行, 公式原文)}。
|
||||
|
||||
Excel 把连续行的同款公式存成一组共享公式:只有主定义带公式文本,
|
||||
其余单元格是自闭合的 <f t="shared" si="N"/>。要下拉必须先按 si 找到定义。
|
||||
"""
|
||||
out = {}
|
||||
for m in _CELL_RE.finditer(chunk):
|
||||
row, inner = int(m.group(2)), m.group(4)
|
||||
fm = _F_RE.search(inner)
|
||||
if not fm or b't="shared"' not in fm.group(1):
|
||||
continue
|
||||
text = (fm.group(2) or b'').decode('utf-8', 'replace')
|
||||
if not text.strip():
|
||||
continue
|
||||
sm = re.search(rb'si="(\d+)"', fm.group(1))
|
||||
if sm:
|
||||
out[sm.group(1).decode()] = (row, text)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_template_row(xml_bytes, row_no):
|
||||
"""模板行 {列字母: {'s': 样式, 'f': 内联公式, 'si': 共享公式组号}}。"""
|
||||
text = xml_bytes.decode('utf-8', 'replace')
|
||||
out = {}
|
||||
for m in re.finditer(r'<c r="([A-Z]+)' + str(row_no) + r'"([^>]*?)(/>|>(.*?)</c>)', text, re.S):
|
||||
col, attrs, inner = m.group(1), m.group(2), m.group(4) or ''
|
||||
sm = re.search(r'\bs="(\d+)"', attrs)
|
||||
fm = re.search(r'<f([^>]*?)(?:/>|>(.*?)</f>)', inner, re.S)
|
||||
f_text = si = None
|
||||
if fm:
|
||||
f_text = (fm.group(2) or None)
|
||||
if 't="shared"' in fm.group(1):
|
||||
sim = re.search(r'si="(\d+)"', fm.group(1))
|
||||
si = sim.group(1) if sim else None
|
||||
out[col] = {'s': sm.group(1) if sm else None, 'f': f_text, 'si': si}
|
||||
return out
|
||||
|
||||
|
||||
def _shift_formula(formula, from_row, to_row):
|
||||
"""把公式里的相对行号从 from_row 平移到 to_row($ 锁定的行号不动)。"""
|
||||
if not formula or from_row == to_row:
|
||||
return formula
|
||||
delta = to_row - from_row
|
||||
|
||||
def repl(m):
|
||||
col, lock, row = m.group(1), m.group(2), m.group(3)
|
||||
if lock == '$':
|
||||
return m.group(0)
|
||||
return f'{col}{int(row) + delta}'
|
||||
|
||||
return re.sub(r'(?<![A-Za-z0-9_])([A-Z]{1,3})(\$?)(\d+)', repl, formula)
|
||||
|
||||
|
||||
def _rows_xml(rows, start_row, col_map, tpl=None, tpl_row=None, shared=None):
|
||||
"""构造新行 XML:A~AE 填值,AF~AP 逐行下拉公式(内联公式 + 共享公式)。"""
|
||||
tpl = tpl or {}
|
||||
shared = shared or {}
|
||||
parts = []
|
||||
for i, row in enumerate(rows):
|
||||
r = start_row + i
|
||||
cells = []
|
||||
for didx, lcol in col_map:
|
||||
if didx < len(row):
|
||||
letter = _col_letter(lcol)
|
||||
c = _cell_xml(letter, r, row[didx], (tpl.get(letter) or {}).get('s'))
|
||||
if c:
|
||||
cells.append((lcol, c))
|
||||
for letter, info in tpl.items():
|
||||
cnum = _col_num(letter)
|
||||
if cnum <= 31:
|
||||
continue
|
||||
formula = None
|
||||
if info.get('f'):
|
||||
formula = _shift_formula(info['f'], tpl_row or start_row, r)
|
||||
elif info.get('si') and info['si'] in shared:
|
||||
def_row, text = shared[info['si']]
|
||||
formula = _shift_formula(text, def_row, r)
|
||||
if not formula:
|
||||
continue
|
||||
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
|
||||
cells.append((cnum, f'<c r="{letter}{r}"{s_attr}><f>{formula}</f></c>'))
|
||||
if not cells:
|
||||
continue
|
||||
cells.sort(key=lambda x: x[0])
|
||||
parts.append(f'<row r="{r}">{"".join(c for _, c in cells)}</row>')
|
||||
return ''.join(parts).encode('utf-8')
|
||||
|
||||
|
||||
# ==================== 原生 XML 写入 ====================
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{_NS_MAIN}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{_NS_REL}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
|
||||
if rel.get('Id') == rid:
|
||||
t = (rel.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _append_rows_native(path, sheet_name, rows, start_row, col_map, new_max_row,
|
||||
skip_from_row=None, tpl_row=None):
|
||||
"""流式重写目标 sheet:先丢弃尾部空公式行,再在 </sheetData> 前插入带公式的新行。"""
|
||||
tmp = path + '.rebuild.tmp'
|
||||
marker = b'</sheetData>'
|
||||
skip_tag = f'<row r="{skip_from_row}"'.encode() if skip_from_row else None
|
||||
tpl_tag = f'<row r="{tpl_row}"'.encode() if tpl_row else None
|
||||
tpl = None
|
||||
shared_defs = {}
|
||||
cache = {'payload': None}
|
||||
|
||||
def _payload():
|
||||
if cache['payload'] is None:
|
||||
cache['payload'] = _rows_xml(rows, start_row, col_map,
|
||||
tpl=tpl, tpl_row=tpl_row, shared=shared_defs)
|
||||
return cache['payload']
|
||||
|
||||
inserted = False
|
||||
dim_done = False
|
||||
|
||||
with zipfile.ZipFile(path, 'r') as src:
|
||||
sheet_path = _sheet_xml_path(src, sheet_name)
|
||||
if not sheet_path:
|
||||
raise RuntimeError(f'workbook 里找不到 sheet「{sheet_name}」')
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in src.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
with src.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
if info.filename != sheet_path:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
continue
|
||||
|
||||
mode = 'skip' if skip_tag else 'plain'
|
||||
buf = b''
|
||||
while True:
|
||||
chunk = fin.read(4 << 20)
|
||||
if not chunk:
|
||||
if buf:
|
||||
fout.write(buf)
|
||||
break
|
||||
buf += chunk
|
||||
if not dim_done:
|
||||
buf = re.sub(
|
||||
rb'(<dimension ref="[A-Z]+\d+:[A-Z]+)\d+(")',
|
||||
lambda m: m.group(1) + str(new_max_row).encode() + m.group(2),
|
||||
buf, count=1)
|
||||
dim_done = True
|
||||
|
||||
# 模板行在尾部空行之前,只出现一次;就近拿共享公式主定义
|
||||
if tpl is None and tpl_tag:
|
||||
i = buf.find(tpl_tag)
|
||||
if i >= 0:
|
||||
j = buf.find(b'</row>', i)
|
||||
if j >= 0:
|
||||
shared_defs.update(_parse_shared_defs(buf[:i]))
|
||||
tpl = _parse_template_row(buf[i:j + 6], tpl_row)
|
||||
fcols = [c for c, v in tpl.items()
|
||||
if v.get('f') or v.get('si')]
|
||||
config.log(f'模板行 {tpl_row}:{len(tpl)} 个单元格,'
|
||||
f'计算列 {fcols or "无"},'
|
||||
f'计算规则 {len(shared_defs)} 组', 'DEBUG')
|
||||
|
||||
if mode == 'plain':
|
||||
idx = buf.find(marker)
|
||||
if idx == -1:
|
||||
keep = 64
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:idx])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
|
||||
if mode == 'skip':
|
||||
i_skip = buf.find(skip_tag)
|
||||
i_mark = buf.find(marker)
|
||||
if i_mark >= 0 and (i_skip < 0 or i_mark < i_skip):
|
||||
fout.write(buf[:i_mark])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[i_mark:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if i_skip < 0:
|
||||
keep = max(len(skip_tag), len(marker), 512 * 1024)
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:i_skip])
|
||||
buf = buf[i_skip:]
|
||||
mode = 'drop'
|
||||
|
||||
idx = buf.find(marker)
|
||||
if idx < 0:
|
||||
buf = buf[-len(marker):]
|
||||
continue
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if not inserted:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError('sheet xml 里没找到 </sheetData>,未做任何修改')
|
||||
os.replace(tmp, path)
|
||||
return len(_payload())
|
||||
|
||||
|
||||
def run(dry_run=False):
|
||||
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。"""
|
||||
if not os.path.isdir(config.WORK_DIR):
|
||||
return {'ok': False, 'message': f'目录不存在:{config.WORK_DIR}'}
|
||||
|
||||
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)})')
|
||||
|
||||
detail = _pick_latest(config.DETAIL_GLOB, by_month=False)
|
||||
if not detail:
|
||||
return {'ok': False, 'message': f'未找到收益明细:{config.DETAIL_GLOB}'}
|
||||
config.log(f'明细:{os.path.basename(detail)}')
|
||||
|
||||
t0 = time.time()
|
||||
wb = load_workbook(ledger, read_only=True, data_only=True)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.LEDGER_SHEET}」'}
|
||||
ws = wb[config.LEDGER_SHEET]
|
||||
total_row = ws.max_row
|
||||
it = ws.iter_rows(values_only=True)
|
||||
next(it)
|
||||
lhead = _header_index(next(it))
|
||||
if config.TIME_COL not in lhead:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
|
||||
li = lhead[config.TIME_COL]
|
||||
|
||||
ledger_max = None
|
||||
ledger_rows = 0
|
||||
key_cols = [lhead[c] for c in ('账户名称', '订单号', '券号', config.TIME_COL) if c in lhead]
|
||||
last_data_row = config.HEADER_ROW
|
||||
for i, row in enumerate(it, start=config.DATA_START_ROW):
|
||||
if row is None:
|
||||
continue
|
||||
if key_cols and any(c < len(row) and row[c] not in (None, '') for c in key_cols):
|
||||
last_data_row = i
|
||||
if len(row) <= li:
|
||||
continue
|
||||
dt = _to_dt(row[li])
|
||||
if dt is None:
|
||||
continue
|
||||
ledger_rows += 1
|
||||
if ledger_max is None or dt > ledger_max:
|
||||
ledger_max = dt
|
||||
wb.close()
|
||||
if ledger_max is None:
|
||||
return {'ok': False, 'message': '台账该列没有有效时间'}
|
||||
config.log(f'台账有效行 {ledger_rows},最大时间 {ledger_max},真实末行 {last_data_row}'
|
||||
f'(max_row={total_row},尾部 {total_row - last_data_row} 行是公式撑出的空行)')
|
||||
|
||||
wb2 = load_workbook(detail, read_only=True, data_only=True)
|
||||
ws2 = wb2.worksheets[0]
|
||||
it2 = ws2.iter_rows(values_only=True)
|
||||
next(it2)
|
||||
dhead = _header_index(next(it2))
|
||||
if config.TIME_COL not in dhead:
|
||||
wb2.close()
|
||||
return {'ok': False, 'message': f'明细表头缺少「{config.TIME_COL}」'}
|
||||
di = dhead[config.TIME_COL]
|
||||
|
||||
keep, total, skip_old = [], 0, 0
|
||||
for row in it2:
|
||||
if row is None:
|
||||
continue
|
||||
total += 1
|
||||
dt = _to_dt(row[di]) if len(row) > di else None
|
||||
if dt is None or dt < ledger_max:
|
||||
skip_old += 1
|
||||
continue
|
||||
keep.append(row)
|
||||
wb2.close()
|
||||
config.log(f'明细 {total} 行:保留 {len(keep)},剔除 {skip_old}(耗时 {time.time() - t0:.1f}s)')
|
||||
|
||||
if not keep:
|
||||
return {'ok': True, 'appended': 0, 'message': '明细里没有比台账更新的记录'}
|
||||
|
||||
start_row = last_data_row + 1
|
||||
new_max_row = start_row + len(keep) - 1
|
||||
col_map = [(didx, lhead[name] + 1) for name, didx in dhead.items() if name in lhead]
|
||||
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'[演练] 将追加 {len(keep)} 行'}
|
||||
|
||||
bak = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, bak)
|
||||
config.log(f'已备份 → {os.path.basename(bak)}')
|
||||
|
||||
t1 = time.time()
|
||||
size = _append_rows_native(ledger, config.LEDGER_SHEET, keep, start_row, col_map,
|
||||
new_max_row, skip_from_row=start_row, tpl_row=last_data_row)
|
||||
config.log(f'并入完成:{len(keep)} 行,耗时 {time.time() - t1:.1f}s(数据量 {size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'appended': len(keep), 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'已并入 {len(keep)} 行到台账'}
|
||||
@@ -0,0 +1,282 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「新美大核对统计」按日期补 V/W 列外部链接公式。
|
||||
|
||||
业务口径(从台账既有 62 条链接反推):
|
||||
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留)
|
||||
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留)
|
||||
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||||
|
||||
实现:能复用的链接按 target 匹配复用,缺的新增 externalLinkNN.xml + rels +
|
||||
workbook.xml 的 externalReferences + workbook.xml.rels + Content_Types 声明;
|
||||
目标 sheet 只改对应行的 V/W 单元格,其余部件原样拷贝。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_EXTLINK_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
|
||||
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
|
||||
)
|
||||
_EXTLINK_RELS_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
|
||||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||||
)
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
|
||||
|
||||
def _pick_latest(pattern):
|
||||
import glob
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p)]
|
||||
if not files:
|
||||
return None
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _target_path(d):
|
||||
return os.path.join(config.SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
|
||||
f'{config.LINK_BOOK}{d.month}.{d.day}.xlsx')
|
||||
|
||||
|
||||
def _file_uri(path):
|
||||
"""与既有 rels 一致:file:///\\\\caiwu01\\共享文件夹\\...(XML 属性里反斜杠不转义)。"""
|
||||
return 'file:///' + path
|
||||
|
||||
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{main}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{rel}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for r in rels.iter(f'{pkg}Relationship'):
|
||||
if r.get('Id') == rid:
|
||||
t = (r.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
keep = []
|
||||
style_default = None
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if style_default is None and sm:
|
||||
style_default = sm.group(1)
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, (formula, style) in cells.items():
|
||||
s = style or style_default
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:`file:///\\\\caiwu01\\共享...` → `\\\\caiwu01\\共享...`(小写)。
|
||||
|
||||
比对方是本地路径,不带 file:/// 前缀;不归一会永远匹配不上,
|
||||
导致每次运行都新增一条重复的外部链接。
|
||||
"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _parse_links(zf):
|
||||
mapping, max_n = {}, 0
|
||||
for name in zf.namelist():
|
||||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||||
if not m:
|
||||
continue
|
||||
n = int(m.group(1))
|
||||
max_n = max(max_n, n)
|
||||
txt = zf.read(name).decode('utf-8', 'replace')
|
||||
tm = re.search(r'Target="([^"]+)"', txt)
|
||||
if tm:
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n) # 同路径多条时保留最早那条
|
||||
return mapping, max_n
|
||||
|
||||
|
||||
def run(d_from=None, d_to=None, dry_run=False):
|
||||
"""按日期区间补 V/W。d_from/d_to 为空则取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的日期。"""
|
||||
ledger = _pick_latest(config.LEDGER_GLOB)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}')
|
||||
|
||||
if not d_from:
|
||||
detail = _pick_latest(config.DETAIL_GLOB)
|
||||
if detail:
|
||||
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(detail)) or \
|
||||
re.search(r'(\d{8})', os.path.basename(detail))
|
||||
if m:
|
||||
d_from = m.group(1)
|
||||
d_to = m.group(2) if m.lastindex and m.lastindex >= 2 else m.group(1)
|
||||
if not d_from:
|
||||
today = date.today()
|
||||
d_from = (today - timedelta(days=1)).isoformat()
|
||||
d_to = today.isoformat()
|
||||
|
||||
d1 = datetime.strptime(d_from.replace('-', '')[:8], '%Y%m%d').date()
|
||||
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date()
|
||||
config.log(f'日期区间:{d1} ~ {d2}')
|
||||
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.STAT_SHEET}」'}
|
||||
ws = wb[config.STAT_SHEET]
|
||||
date_rows = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
date_rows[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
date_rows[v] = i
|
||||
wb.close()
|
||||
|
||||
days, day = [], d1
|
||||
while day <= d2:
|
||||
days.append(day)
|
||||
day += timedelta(days=1)
|
||||
skipped = [d for d in days if d not in date_rows]
|
||||
if skipped:
|
||||
config.log(f'核对统计表里没有这些日期行,跳过:{[str(d) for d in skipped]}', 'WARN')
|
||||
days = [d for d in days if d in date_rows]
|
||||
if not days:
|
||||
return {'ok': False, 'message': '没有可处理的日期行'}
|
||||
|
||||
zf = zipfile.ZipFile(ledger)
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
|
||||
plan, need_new = [], []
|
||||
for d in days:
|
||||
path = _target_path(d)
|
||||
if _norm_uri(path) in link_map:
|
||||
plan.append((d, date_rows[d], link_map[_norm_uri(path)], path, '复用'))
|
||||
else:
|
||||
idx = max_link + len(need_new) + 1
|
||||
need_new.append((idx, path, _file_uri(path)))
|
||||
plan.append((d, date_rows[d], idx, path, '新增'))
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
config.log(f' {d} → 第{row_no}行 [{idx}]({mode}){path}')
|
||||
|
||||
if dry_run:
|
||||
zf.close()
|
||||
return {'ok': True, 'rows': [p[1] for p in plan],
|
||||
'message': f'[演练] {len(plan)} 行将更新 V/W,需新增 {len(need_new)} 条外部链接'}
|
||||
|
||||
if not os.path.isdir(config.SHARE_ROOT):
|
||||
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
|
||||
f'恢复后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
zf.close()
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', sheet_xml, re.S)
|
||||
if not m:
|
||||
config.log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
# 注意:XML 的 <f> 里放公式正文,不带 Excel 界面上的前导 '='
|
||||
new_row = _set_row_cells(m.group(0), row_no, {
|
||||
'V': (f'[{idx}]{config.LINK_SHEET}!$B$5', None),
|
||||
'W': (f'[{idx}]{config.LINK_SHEET}!$B$6', None),
|
||||
})
|
||||
sheet_xml = sheet_xml[:m.start()] + new_row + sheet_xml[m.end():]
|
||||
config.log(f'{d} 行已补上团购统计表取数链接')
|
||||
|
||||
for idx, path, uri in need_new:
|
||||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||||
rid = f'rId{rid_num}'
|
||||
wb_rels = wb_rels.replace(
|
||||
'</Relationships>',
|
||||
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
|
||||
f'officeDocument/2006/relationships/externalLink" '
|
||||
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
|
||||
wb_xml = wb_xml.replace('</externalReferences>',
|
||||
f'<externalReference r:id="{rid}"/></externalReferences>')
|
||||
ct_xml = ct_xml.replace(
|
||||
'</Types>',
|
||||
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
|
||||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||||
|
||||
tmp = ledger + '.rebuild.tmp'
|
||||
replace = {
|
||||
sheet_path: sheet_xml.encode('utf-8'),
|
||||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||||
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
|
||||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||||
}
|
||||
new_files = {}
|
||||
for idx, path, uri in need_new:
|
||||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||||
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
|
||||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||||
(_EXTLINK_RELS_TPL % uri).encode('utf-8')
|
||||
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
zf.close()
|
||||
os.replace(tmp, ledger)
|
||||
|
||||
config.log(f'完成:{len(plan)} 行更新 V/W,新增外部链接 {len(need_new)} 条')
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'message': f'核对统计 V/W 已更新 {len(plan)} 行'}
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0041",
|
||||
"name": "新美大平台核对",
|
||||
"version": "1.1.3",
|
||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并给核对统计表补当天的团购统计表链接。登录一次后可长期复用。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"runTimeoutSeconds": 0,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0041"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"title": "执行过程",
|
||||
"default": "all",
|
||||
"enum": ["all", "download", "reconcile"],
|
||||
"description": "all=下载后核对;download=只下载;reconcile=只核对(不下载)"
|
||||
},
|
||||
"do_download": {
|
||||
"type": "boolean",
|
||||
"title": "下载数据",
|
||||
"default": true,
|
||||
"description": "登录经营宝,把账单下载到本机目录"
|
||||
},
|
||||
"do_reconcile": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对",
|
||||
"default": true,
|
||||
"description": "读本机最新的台账与收益明细,并入台账并更新核对统计,不重新下载"
|
||||
},
|
||||
"pay_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "下载打款记录",
|
||||
"default": true,
|
||||
"description": "平台打款到门店的明细(打款金额、到账银行卡、打款状态、账单周期)"
|
||||
},
|
||||
"pay_date_from": {
|
||||
"type": "string",
|
||||
"title": "打款记录-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"pay_date_to": {
|
||||
"type": "string",
|
||||
"title": "打款记录-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"profit_group": {
|
||||
"type": "boolean",
|
||||
"title": "下载团购收益明细",
|
||||
"default": true,
|
||||
"description": "团购业务的收益明细(券号/订单号、结算价、总收入、技术服务费、渠道佣金)"
|
||||
},
|
||||
"profit_booking": {
|
||||
"type": "boolean",
|
||||
"title": "下载预订收益明细",
|
||||
"default": true,
|
||||
"description": "预订业务的收益明细(无预订业务时为空表)"
|
||||
},
|
||||
"profit_date_from": {
|
||||
"type": "string",
|
||||
"title": "收益明细-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"profit_date_to": {
|
||||
"type": "string",
|
||||
"title": "收益明细-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"run_merge": {
|
||||
"type": "boolean",
|
||||
"title": "并入台账",
|
||||
"default": true,
|
||||
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
||||
},
|
||||
"run_links": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对统计",
|
||||
"default": true,
|
||||
"description": "给核对统计表对应日期的行补上当天团购统计表的取数链接"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"title": "只核对不写入",
|
||||
"default": false,
|
||||
"description": "只输出将要并入的行数与将更新的日期,不改动台账"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
openpyxl>=3.1
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>新美大平台核对</title>
|
||||
<script type="module" crossorigin src="/pui/xq0041/assets/index-Bfw7DCy5.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-D14JpOBT.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user