- 登录改为自动填账号密码并勾选用户协议,页面右上角浮层提示人工点「登录」(按钮、滑块/短信、选门店仍人工),登录一次长期复用 - 金色印象 / 金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b,9222 / 9333),避免同浏览器反复切号触发风控 - 执行模式拆 full(只导金色印象 + 并台账 + 更新核对统计)/ export_only(按范围勾选各导一份,不写表),湖畔报表文件名带「金色湖畔_」前缀;UI 同步重建
314 lines
17 KiB
Python
314 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
||
|
||
执行过程由 action 决定(UI 的两个开关派生):
|
||
action='download' → 只下载:登录经营宝(界面配了账号密码则自动填写提交,验证码/选商家仍需人工),
|
||
按勾选下载打款记录 / 团购收益明细 / 预订收益明细;
|
||
action='reconcile' → 只核对:**不开浏览器**,直接用本机最新的台账与收益明细并入台账、
|
||
更新核对统计(适合数据已下载、只想重算的场景);
|
||
action='all' → 下载后再核对(默认)。
|
||
|
||
多公司(对齐 xq0042 抖音平台核对):金色印象(台账那家)与金色湖畔在平台上是两套登录,
|
||
各自用独立的浏览器档案与调试端口(browser_sessions/xq0041 与 xq0041_b,端口 9222 / 9333),
|
||
登录态互不干扰,避免同浏览器反复切号触发风控。
|
||
run_mode='full' → 只导金色印象 + 并入台账 + 更新核对统计(默认,历史行为)
|
||
run_mode='export_only' → 按 export_companies 勾选的公司各导一份(可只导一家),不写任何表
|
||
(湖畔文件名带「金色湖畔_」前缀)
|
||
并入台账 / 更新核对统计只认金色印象那份明细(湖畔文件天然落在台账 glob 之外)。
|
||
|
||
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
||
不涉及任何签名算法。
|
||
"""
|
||
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.3.8'
|
||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
||
'并按日期把核对统计表整行同源取数公式(资金组取数)换成当天共享总表的链接;'
|
||
'界面可配账号密码自动填好并勾选用户协议、浏览器内浮层提示你点登录'
|
||
'(登录按钮/验证码/选门店仍人工),并自动选「非餐饮商家版」;'
|
||
'执行模式分「含写表」(只导金色印象 + 并台账 + 更新核对统计)与'
|
||
'「仅导出」(金色印象 / 金色湖畔按需勾选,可只导一家,不写表),'
|
||
'两家各自独立浏览器档案与调试端口,登录态互不干扰')
|
||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||
uses_month = False
|
||
capabilities = ['xq0041']
|
||
permissions = {'platforms': []}
|
||
# 与 plugin.json.fields 一致(ui=true,前端按此渲染表单)
|
||
fields = {
|
||
'mt_username': {'type': 'string', 'title': '金色印象-经营宝账号', 'default': ''},
|
||
'mt_password': {'type': 'string', 'title': '金色印象-登录密码', 'default': '',
|
||
'format': 'password'},
|
||
'mt2_username': {'type': 'string', 'title': '金色湖畔-经营宝账号', 'default': ''},
|
||
'mt2_password': {'type': 'string', 'title': '金色湖畔-登录密码', 'default': '',
|
||
'format': 'password'},
|
||
'run_mode': {'type': 'string', 'title': '执行模式', 'default': config.RUN_MODE_FULL,
|
||
'enum': [config.RUN_MODE_FULL, config.RUN_MODE_EXPORT_ONLY]},
|
||
'export_companies': {'type': 'array', 'title': '导出范围(仅导出模式生效)',
|
||
'default': ['a', 'b'], 'items': {'type': 'string'}},
|
||
'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': ''},
|
||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||
'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)
|
||
run_mode = config.normalize_run_mode(fields.get('run_mode'))
|
||
if run_mode == config.RUN_MODE_EXPORT_ONLY:
|
||
# 仅导出:两家公司各导一份,不写任何表(对齐 xq0042 的语义)
|
||
if action == 'reconcile':
|
||
raise RuntimeError('「仅导出」模式不做核对;要并台账请把执行模式切成「含写表」')
|
||
action = 'download'
|
||
if not action:
|
||
raise RuntimeError('请至少选择一个执行过程(下载数据 / 更新核对)')
|
||
do_download = action in ('all', 'download')
|
||
do_reconcile = action in ('all', 'reconcile')
|
||
export_only = run_mode == config.RUN_MODE_EXPORT_ONLY
|
||
|
||
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))
|
||
force_login = bool(fields.get('force_login'))
|
||
# 保存目录同时是台账目录:并入台账 / 更新核对统计都读它
|
||
save_dir = config.set_work_dir(fields.get('save_dir'))
|
||
|
||
# 登录账号密码(界面配置;留空 = 该家手工登录)
|
||
# 金色印象 / 金色湖畔 是平台上的两个主体,各自一套账号,导谁用谁的
|
||
creds = {
|
||
'a': (str(fields.get('mt_username') or '').strip(),
|
||
str(fields.get('mt_password') or '').strip()),
|
||
'b': (str(fields.get('mt2_username') or '').strip(),
|
||
str(fields.get('mt2_password') or '').strip()),
|
||
}
|
||
|
||
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)
|
||
|
||
companies = config.companies_for_mode(run_mode, fields.get('export_companies'))
|
||
plan = []
|
||
if do_download:
|
||
plan.append('公司 ' + ' + '.join(c['short'] for c in companies))
|
||
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 dry_run else ''))
|
||
config.log('执行模式:' + ('仅导出(金色印象 + 金色湖畔,不写表)' if export_only
|
||
else '含写表(只导金色印象 + 并台账 + 更新核对统计)'))
|
||
|
||
detail = {'action': action, 'run_mode': run_mode, 'pay': None, 'profit': None,
|
||
'merge': None, 'links': None, 'results': {},
|
||
'companies': [c['short'] for c in companies]}
|
||
files = []
|
||
|
||
# ---------- 1~3:登录 + 下载(逐家公司:各自独立浏览器档案 + 端口) ----------
|
||
if do_download:
|
||
jobs = [(comp, *creds.get(comp['id'], ('', ''))) for comp in companies]
|
||
dl_end = 60 if do_reconcile else 95
|
||
span = (dl_end - 2) / len(jobs)
|
||
errors = []
|
||
try:
|
||
for i, (comp, user, pwd) in enumerate(jobs):
|
||
config.set_company(comp['id'])
|
||
label = comp['short']
|
||
base = 2 + span * i
|
||
ctx.progress(int(base))
|
||
if len(jobs) > 1:
|
||
config.log(f'—— {label}:档案 {comp["profile"]} / 端口 {comp["port"]} ——')
|
||
page = browser.open_page(force_login=force_login)
|
||
try:
|
||
config.log(f'{label} 登录方式:' + ('界面配置的账号密码自动登录'
|
||
if (user and pwd) else '手工登录'))
|
||
ok, msg = meituan_login.ensure_login(page, user, pwd)
|
||
config.log(msg)
|
||
if not ok:
|
||
raise RuntimeError(f'{label} 登录失败:{msg}')
|
||
ctx.progress(int(base + span * 0.4))
|
||
|
||
if pay_on:
|
||
r1 = payment_download.download(page, pay_from, pay_to, save_dir,
|
||
dry_run)
|
||
if not r1.get('ok'):
|
||
raise RuntimeError(f'{label} 打款记录下载失败:{r1.get("message")}')
|
||
config.log(r1.get('message') or '')
|
||
if r1.get('empty'):
|
||
# 区间内没有打款记录:正常跳过,不影响收益明细下载与核对
|
||
config.log('打款记录区间内无数据,已跳过本项', 'WARN')
|
||
elif r1.get('path'):
|
||
files.append(r1['path'])
|
||
if comp.get('ledger'):
|
||
detail['pay'] = r1
|
||
ctx.progress(int(base + span * 0.7))
|
||
|
||
if codes:
|
||
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
||
codes, dry_run)
|
||
if not r2.get('ok'):
|
||
raise RuntimeError(f'{label} 收益明细下载失败:{r2.get("message")}')
|
||
config.log(r2.get('message') or '')
|
||
files.extend(r2.get('paths') or [])
|
||
if comp.get('ledger'):
|
||
detail['profit'] = r2
|
||
ctx.progress(int(base + span))
|
||
detail['results'] = detail.get('results') or {}
|
||
detail['results'][label] = {'ok': True}
|
||
except Exception as e:
|
||
if len(jobs) == 1:
|
||
raise
|
||
config.log(f'{label} 导出失败:{e}', 'ERROR')
|
||
errors.append(str(e))
|
||
detail['results'] = detail.get('results') or {}
|
||
detail['results'][label] = {'ok': False, 'message': str(e)}
|
||
finally:
|
||
browser.close_page(page)
|
||
finally:
|
||
config.set_company('a')
|
||
if errors:
|
||
raise RuntimeError(';'.join(errors))
|
||
|
||
# ---------- 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 detail['pay'] and detail['pay'].get('empty'):
|
||
parts.append(f'打款记录 {pay_from}~{pay_to} 无数据')
|
||
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())
|