feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 0a32518060
commit c77a26cd99
494 changed files with 66923 additions and 2714 deletions
+229
View File
@@ -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())