Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/config/__init__.py
T
puddy b321209bf5 feat(xq0041): 经营宝登录改人工点确认 + 双公司独立档案与执行模式拆分(1.3.9)
- 登录改为自动填账号密码并勾选用户协议,页面右上角浮层提示人工点「登录」(按钮、滑块/短信、选门店仍人工),登录一次长期复用

- 金色印象 / 金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b,9222 / 9333),避免同浏览器反复切号触发风控

- 执行模式拆 full(只导金色印象 + 并台账 + 更新核对统计)/ export_only(按范围勾选各导一份,不写表),湖畔报表文件名带「金色湖畔_」前缀;UI 同步重建
2026-11-06 15:52:10 +08:00

306 lines
13 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 = '资金组取数'
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 = '非餐饮'
BIZ_LINE_MARKERS = ('我是餐饮商家', '我是非餐饮商家')
BIZ_LINE_MAX_TRIES = 3 # 最多尝试 3 次(卡片容器 → 确定按钮 → 卡片本身)
BIZ_LINE_INTERVAL = 6 # 每次尝试的最小间隔(秒)
# ==================== 运行参数 ====================
LOGIN_WAIT = 600 # 等待人工登录(含验证码/选商家)超时
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
POLL_SECONDS = 2
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
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')
# ==================== 公司与账号档案(对齐 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_HEADER_FILE = ''
TOKEN_FILE = ''
META_FILE = ''
# ==================== 执行模式 ====================
# 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
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 落盘文件),返回生效的公司配置。
meituan_login 直接读 config.COOKIE_FILE 等模块属性,这里改全局即全局生效。
"""
global _cur_company, COOKIE_FILE, COOKIE_HEADER_FILE, TOKEN_FILE, META_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')
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, f'meituan_cookies_header{suffix}.txt')
TOKEN_FILE = os.path.join(SESSIONS_DIR, f'meituan_tokens{suffix}.json')
META_FILE = os.path.join(SESSIONS_DIR, f'meituan_session_meta{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)
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