Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/config/__init__.py
T

360 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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 = 收益明细
# ==================== 台账 ====================
DEFAULT_WORK_DIR = r'D:\资料\财务\新美大平台核对' # 界面「保存目录」留空时用它
WORK_DIR = DEFAULT_WORK_DIR # 账单 + 台账统一目录(运行期可被覆盖)
LEDGER_GLOB = '新美大到账统计*.xlsx'
LEDGER_SHEET = '金色印象--新美大导出(收)'
STAT_SHEET = '新美大核对统计'
TIME_COL = '验券/退款/调整时间'
DETAIL_GLOB = '团购收益明细_*.xlsx'
# 金色湖畔的明细带「金色湖畔_」前缀,天然匹配不到上面的 glob → 并入台账只认金色印象那份
HEADER_ROW = 2
DATA_START_ROW = 3
# 「新美大核对统计」V/W 列的外部工作簿(与台账历史 62 条链接一致)
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
LINK_BOOK = '马敏团购总表'
LINK_SHEET = '资金组取数'
# ==================== 其他 ====================
# 订单收入明细 / 基础信息补维护 / 马敏总表粘贴 / 共享核对表复制 / 门店归属(CRM 券号)
# 都已在 v1.3.13 迁到 XQ0085 团购数据核对插件;本插件只保留导表与到账统计表维护。
def set_work_dir(path=None):
"""界面「保存目录」覆盖默认目录(账单 + 台账同目录)。
merge_ledger / stat_links 都在调用时读 config.WORK_DIR,改这里即全局生效。
留空 = 回到默认目录(避免上一次的目录串到下一次运行)。返回实际生效目录。
"""
global WORK_DIR
p = str(path or '').strip().strip('"').strip()
WORK_DIR = p or DEFAULT_WORK_DIR
return WORK_DIR
# ==================== 账号密码预填(可选,界面配置) ====================
# 只预填账号密码 + 勾「用户协议」,**不点登录**:登录按钮、滑块/图形验证码、
# 短信验证码、选商家全部由用户在浏览器里自己完成(脚本只等结果)。
AUTOFILL_WAIT = 45 # 等登录页账号密码输入框出现的最长时间(登录页异步渲染/多次重定向)
AUTOFILL_POLL = 1.5
# 登录表单不一定在主文档里:实测 ecom.meituan.com 的登录页是内嵌 iframe
# (<div class="loginBox"><iframe class="loginFormContent"
# src="https://epassport.meituan.com/portal/login?...">),跨域但可由 CDP 直接执行 JS。
LOGIN_FRAME_HINTS = (
'epassport.meituan.com', 'passport.meituan.com',
'passport.dianping.com', 'account.dianping.com',
)
# 登录后的「选择商家版本」页(epassport,main .biz-item 卡片):
# 「我是餐饮商家(餐饮商家版)」/「我是非餐饮商家(服务零售商家版)」
# 金色印象属服务零售(足浴/休闲);登录后如出现这一页,由人工点「我是非餐饮商家」,
# 这里只用它拼页面提示文案,不再自动点选。
BIZ_LINE_KEYWORD = '非餐饮'
# ==================== 运行参数 ====================
LOGIN_WAIT = 600 # 等待人工登录(含验证码/选商家)超时
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
SETTLE_WAIT = 8 # 进入后台后等首屏请求结束再确认状态
POLL_SECONDS = 2
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
RECORD_SECONDS = 300 # 单次等待账单出表的上限(5 分钟);超时不报错,记待续,下次运行接着下载
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')
# 断点续传状态:记录本次提交但还没出表的账单任务,下次运行接着等/下载(见 data/resume_state.py)
PENDING_STATE_PATH = os.path.join(_app_data_dir(), 'xq0041_pending.json')
# ==================== 公司与账号档案(对齐 xq0042 的多公司模式) ====================
# 美团经营宝按主体分账号:金色印象(台账那家)与金色湖畔(只导出、不写表)。
# 两个主体在平台上是两套登录,实测必须各自独立浏览器档案 + 独立端口,
# 否则在同一档案里反复切号(清 Cookie 重新登录)最容易触发风控/验证码。
# ledger=True 的那家:报表文件名保持原名(台账 glob 只认它,不会串);
# ledger=False 的那家:文件名加「金色湖畔_」前缀,既避免同日互相覆盖,也天然被台账 glob 排除。
COMPANIES = (
{'id': 'a', 'short': '金色印象',
'profile': 'xq0041', 'port': 9222, 'file_prefix': '', 'ledger': True},
{'id': 'b', 'short': '金色湖畔',
'profile': 'xq0041_b', 'port': 9333, 'file_prefix': '金色湖畔_', 'ledger': False},
)
_cur_company = 'a'
COOKIE_FILE = '' # 当前公司的 Cookie 落盘文件(set_company 时切换)
# ==================== 执行动作(三个独立分支,互不混跑) ====================
ACTION_DOWNLOAD = 'download' # 只导表:不做任何核对
ACTION_CHECK_SETTLEMENT = 'check_settlement' # 到账统计核对(新美大到账统计)
ACTIONS = (ACTION_DOWNLOAD, ACTION_CHECK_SETTLEMENT)
# ==================== 执行模式 ====================
# export_only:仅导出(两家都导,不并台账、不更新核对统计);
# full:含写表(只导 ledger=True 的金色印象,导出后并台账 + 更新核对统计)。
RUN_MODE_EXPORT_ONLY = 'export_only'
RUN_MODE_FULL = 'full'
_RUN_MODE_EXPORT_ONLY_ALIASES = ('export_only', 'export', '仅导出', '只导出')
def normalize_run_mode(raw):
"""执行模式归一:未配置/未知 → 含写表(保持历史行为)。"""
text = str(raw or '').strip().lower()
return RUN_MODE_EXPORT_ONLY if text in _RUN_MODE_EXPORT_ONLY_ALIASES else RUN_MODE_FULL
# ==================== 下载方式(断点续传 / 全新下载) ====================
# resume(默认):先认领上次没出表的账单 + 平台已在生成的记录,出表就下载;
# 单张表最多等 RECORD_SECONDS(5 分钟),没出就跳过记待续,下次运行接着下。
# fresh:不复用、不认领,一律重新提交生成任务(取最新数据;平台排队慢时要从头等)。
DOWNLOAD_MODE_RESUME = 'resume'
DOWNLOAD_MODE_FRESH = 'fresh'
DOWNLOAD_MODES = (DOWNLOAD_MODE_RESUME, DOWNLOAD_MODE_FRESH)
_FRESH_ALIASES = ('fresh', 'new', '全新', '全新下载', '重新下载', '强制重新下载')
def normalize_download_mode(raw):
"""下载方式归一:未配置/未知 → 断点续传。"""
text = str(raw or '').strip().lower()
return DOWNLOAD_MODE_FRESH if text in _FRESH_ALIASES else DOWNLOAD_MODE_RESUME
# ==================== 等待策略(单表 5 分钟跳过 / 一次等到底) ====================
# skip(默认):每张表最多等 RECORD_SECONDS(5 分钟,收益按类型数累计),没出就跳过记待续;
# until_done:不限时等出表(想一次跑完时用),受执行机「单次执行超时」(壳默认 6 小时)
# 与用户强停约束;被中断也会留待续状态,下次运行接着下载。
WAIT_SKIP = 'skip'
WAIT_UNTIL_DONE = 'until_done'
WAIT_MODES = (WAIT_SKIP, WAIT_UNTIL_DONE)
_UNTIL_DONE_ALIASES = ('until_done', 'wait', 'forever', '等到底', '一次等到底', '不限时')
def normalize_wait_mode(raw):
"""等待策略归一:未配置/未知 → 每表 5 分钟跳过。"""
text = str(raw or '').strip().lower()
return WAIT_UNTIL_DONE if text in _UNTIL_DONE_ALIASES else WAIT_SKIP
def get_company(cid=None):
"""取公司配置(默认当前档案);未知 id 回退第一家。"""
key = str(cid if cid is not None else _cur_company).strip().lower()
return next((dict(c) for c in COMPANIES if c['id'] == key), dict(COMPANIES[0]))
def companies_for_mode(mode, picks=None):
"""模式 + 勾选 → 要导出的公司列表。
仅导出:按 picks(公司 id 列表)挑,没勾或全是非法值 → 退回全部公司;
含写表:只导 ledger=True 的金色印象(台账只有这一家的 sheet)。
"""
if normalize_run_mode(mode) == RUN_MODE_EXPORT_ONLY:
want = [str(x).strip().lower() for x in (picks or []) if str(x).strip()]
picked = [dict(c) for c in COMPANIES if c['id'] in want] if want else []
return picked or [dict(c) for c in COMPANIES]
picked = [dict(c) for c in COMPANIES if c.get('ledger')]
return picked or [dict(COMPANIES[0])]
def set_company(cid='a'):
"""切换当前档案(连带切换 Cookie 落盘文件),返回生效的公司配置。
登录态优先由浏览器 profile 保存;COOKIE_FILE 是按公司分文件的备份,
profile 失效时注回浏览器再试一次。
"""
global _cur_company, COOKIE_FILE
comp = get_company(cid)
_cur_company = comp['id']
suffix = '' if comp['id'] == 'a' else f"_{comp['id']}"
COOKIE_FILE = os.path.join(SESSIONS_DIR, f'meituan_cookies{suffix}.json')
return comp
def current_company():
return get_company(_cur_company)
def company_label(cid=None):
return get_company(cid)['short']
def get_browser_profile_dir(cid=None):
"""公司专属浏览器用户目录:各自独立,登录态跨次保留,不占用日常 Chrome。"""
return os.path.join(_app_data_dir(), 'browser_sessions', get_company(cid)['profile'])
def get_browser_port(cid=None):
"""公司专属 CDP 调试端口(默认 9222,金色湖畔 9333,避免抢端口)。"""
return int(get_company(cid)['port'])
def file_prefix(cid=None):
"""报表文件名前缀:金色印象为空(与历史文件一致),金色湖畔为「金色湖畔_」。"""
return get_company(cid)['file_prefix']
set_company('a')
# ==================== 浏览器窗口(全屏 + 置顶) ====================
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, True)
except Exception as e:
log(f'设置窗口置顶失败(忽略):{e}', 'WARN')
def restore_window_mode(page):
"""登录成功、进入后台后恢复普通窗口并取消置顶 —— 全屏置顶只为登录时让人看见。
下载阶段要跑好几分钟,一直全屏置顶会让用户完全没法用电脑。失败仅告警。
"""
try:
page.set.window.normal()
except Exception as e:
log(f'恢复窗口大小失败(忽略):{e}', 'WARN')
if os.name == 'nt':
try:
_set_topmost(page.process_id, False)
except Exception as e:
log(f'取消窗口置顶失败(忽略):{e}', 'WARN')
def _set_topmost(pid, on=True):
"""把指定进程的主窗口设为 HWND_TOPMOST / 取消为 HWND_NOTOPMOST(仅 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]
target = -1 if on else -2 # HWND_TOPMOST / HWND_NOTOPMOST
for hwnd in hwnds:
user32.SetWindowPos(hwnd, wintypes.HWND(target), 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