feat: 新增 CRM 数据导出插件(XQ0048)
新增 XQ0048 CRM 数据导出插件,包含储值卡余额整页截图、18 张报表自动导出功能。 支持登录态钉钉扫码一次后缓存复用(约 30 分钟免扫码),按报表日期规则自动计算导出区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。 插件包含 requirements.txt、plugin.json、打包脚本、数据层及业务逻辑代码,可直接通过 agent_cli 发布。
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CRM数据导出 - webhost 场景插件(XQ0048)
|
||||
|
||||
流程:
|
||||
1) 登录态预检(API 校验 %LOCALAPPDATA%\\37duAutomation\\.sessions\\crm_cookie_header.txt);
|
||||
有效则全程免扫码,失效则打开可见浏览器等钉钉扫码一次(同次运行最多弹一次);
|
||||
2) 打开「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png;
|
||||
3) requests 复用同一登录态,按日期规则导出 18 张报表 xlsx
|
||||
(礼品卡订单因接口限制跨度 ≤31 天,近 3 个自然月按月拆分)。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import crm_export
|
||||
|
||||
|
||||
class CrmDataExportPlugin(ScenePlugin):
|
||||
id = "xq0048"
|
||||
name = "CRM数据导出"
|
||||
version = "1.0.0"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出,"
|
||||
"登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),"
|
||||
"按各报表日期规则自动计算区间,礼品卡订单按月拆分")
|
||||
platform = "" # CRM 为钉钉扫码登录,插件内自带登录流程,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0048"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致
|
||||
fields = {
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": "",
|
||||
"description": "留空=D:\\资料\\财务\\CRM数据导出"},
|
||||
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
|
||||
result = crm_export.run_export(save_dir)
|
||||
config.progress(100)
|
||||
|
||||
files = result.get("exports") or []
|
||||
summary = (f"截图 {1 if result.get('screenshot') else 0}/1,"
|
||||
f"报表 {result.get('done')}/{result.get('total')},共 {len(files) + 1} 个文件")
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
"screenshot": result.get("screenshot") or "",
|
||||
"reports_done": result.get("done", 0),
|
||||
"reports_total": result.get("total", 0),
|
||||
"files": files,
|
||||
"save_dir": save_dir,
|
||||
},
|
||||
"path": save_dir,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(CrmDataExportPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0048 CRM数据导出 插件打包脚本(统一规范版,与 xq0011/xq0038 一致)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0048 CRM数据导出\\_pack.py"
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0048_v<版本>.zip --id xq0048 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件
|
||||
_EXCLUDE_DIRS = {"ui-src", "node_modules", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0048 CRM 数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 站点与路由 ====================
|
||||
SITE_URL = 'https://crm.37du.co/'
|
||||
LOGIN_URL = 'https://crm.37du.co/#/login'
|
||||
# 会话校验接口:cookies 有效返回 {"code":"S0","success":true,...}
|
||||
VALIDATE_URL = 'https://crm.37du.co/membership/main/user'
|
||||
BASE = 'https://crm.37du.co/membership/'
|
||||
BALANCE_URL = 'https://crm.37du.co/#/reort/balance' # 报表统计/储值卡余额(reort 为站点实际拼写)
|
||||
LOGIN_KEYWORD = 'login' # hash 片段含 login 即登录页
|
||||
PAGE_TITLE_KEYWORD = '储值卡余额' # 截图页就绪判定
|
||||
CRM_DOMAIN = 'crm.37du.co'
|
||||
|
||||
# ==================== 输出路径 ====================
|
||||
DEFAULT_SAVE_DIR = r'D:\资料\财务\CRM数据导出'
|
||||
|
||||
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'crm_cookies.json') # 与影刀版同名,可互相复用
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'crm_cookie_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'crm_tokens.json')
|
||||
|
||||
|
||||
def default_output_dir():
|
||||
"""默认输出目录(与影刀版一致)。"""
|
||||
return DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。
|
||||
|
||||
与影刀版(browser_sessions/crm)分开,避免两个宿主同时运行时抢同一 profile。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0048')
|
||||
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3 # 截图/单报表重试
|
||||
PAGE_SIZE = 13 # 与页面一致;实测服务端导出不受分页影响
|
||||
TIMEOUT = 180 # 大报表(数万行)下载超时
|
||||
LOAD_TIMEOUT = 30 # 等页面标题就绪的最长秒数
|
||||
PAGE_SETTLE = 5 # 数据渲染稳定等待(秒)
|
||||
LOGIN_SETTLE = 8 # 登录成功后等首屏请求结束再抓 cookie(过早快照会被轮换作废)
|
||||
LOGIN_WAIT = 300 # 等待扫码超时(秒),人工操作给足窗口
|
||||
PROFILE_REUSE_WAIT = 10 # 浏览器 profile 残留会话 / 静默重登的观察窗口
|
||||
SCAN_WAIT = 300 # 登录模块等待扫码超时(秒)
|
||||
HEADLESS = False # 扫码兜底需可见浏览器
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
# ==================== 报表清单(名称, 导出接口, 日期规则, 附加参数, 日期参数字段) ====================
|
||||
# 规则:prev=前一天单日;prev_today=昨日~今日;month_to_today=本月1日~今日;
|
||||
# prev_prev=昨日~昨日;month1_to_prev=本月1日~前一天;last_month=上月完整;
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天)
|
||||
# 日期参数字段:报表统计类为 reportDate;开卡订单/会员退卡为 period;
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分)
|
||||
REPORTS = [
|
||||
('团购支付数据', 'report/groupPay/export', 'prev', None, 'reportDate'),
|
||||
('现金支付', 'report/cashPay/export', 'prev', None, 'reportDate'),
|
||||
('第三方支付(门店)', 'report/thirdPayShop/export', 'prev', None, 'reportDate'),
|
||||
('支付数据', 'report/unionPay/export', 'prev', None, 'reportDate'),
|
||||
('团购数据', 'report/groupData/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'reportDate'),
|
||||
('技师综合业绩', 'report/comprehensivePerformance/export', 'month_to_today', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'last_month', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'month_to_today', None, 'reportDate'),
|
||||
('储值卡消费', 'report/debitCardConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('储值卡线上充值', 'report/depositData/export', 'month1_to_prev', {'channel': 3}, 'reportDate'), # 渠道=管理端
|
||||
('霸王餐充值明细', 'report/overlordOrderDeposit/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('霸王餐消费明细', 'report/overlordOrderConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('霸王餐余额查询', 'report/overlordOrderBalance/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('开卡订单', 'member/order/export', 'month1_to_prev', None, 'period'),
|
||||
('会员退卡', 'member/cancel/export', 'month1_to_prev', None, 'period'),
|
||||
('礼品卡订单', 'giftcard/order/export', 'last3_months', None, 'receiveTimePeriod'),
|
||||
]
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if level == "DEBUG" and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
"""上报进度(0~100);无 ctx 或异常时静默忽略,不影响主流程。"""
|
||||
if not _progress:
|
||||
return
|
||||
try:
|
||||
_progress(max(0, min(100, int(pct))))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0048 CRM 数据导出 - 数据层(登录态 + 报表导出)。"""
|
||||
@@ -0,0 +1,392 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0048 CRM 数据导出 - 储值卡余额截图 + 18 张报表导出。
|
||||
|
||||
从影刀版 workflows/XQ0001-0100/XQ0048 CRM数据导出/crm_export_all.py 迁移,
|
||||
登录逻辑改为插件内 data/crm_login.py(自包含,不跨目录 import)。
|
||||
|
||||
一次运行只登录一次:
|
||||
0) 预检 —— 落盘 Cookie 头经 API 校验有效(服务端滑动会话约 30 分钟)就直接复用,
|
||||
全程不开浏览器、不扫码;
|
||||
1) 截图 —— 开浏览器访问「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png;
|
||||
浏览器 profile 自带会话有效就直接用;无会话才按已验证 Cookie 头去重注入;
|
||||
仍无效才等扫码(最多 5 分钟)。截图后把登录态同步落盘;
|
||||
2) 导出 —— requests 复用同一登录态,按日期规则导出 18 张 xlsx。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
from . import crm_login
|
||||
|
||||
# 本次运行登录态是否已判定无救(crm_login 的扫码闸门用尽)。
|
||||
# 置位后剩余报表直接跳过,避免逐张再发 401 请求、也不再弹扫码窗口。
|
||||
_auth_dead = False
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 登录页与 Cookie 注入 ====================
|
||||
def _is_login_page(url):
|
||||
"""SPA hash 路由判定:hash 片段含 login 即仍在登录页。"""
|
||||
url = (url or '').strip()
|
||||
if not url or not url.lower().startswith('http'):
|
||||
return True
|
||||
fragment = url.split('#', 1)[1].lower() if '#' in url else ''
|
||||
return config.LOGIN_KEYWORD in fragment
|
||||
|
||||
|
||||
def _dedupe_pairs(raw):
|
||||
"""把 Cookie 头字符串转成注入列表:同名条目只留首个(浏览器发送顺序,新 x-token 在前)。
|
||||
|
||||
本站 x-token 会并存新旧两个,而 page.set.cookies 只支持 name/value/domain,
|
||||
同名条目后写覆盖先写;整包注入只会留下作废的旧 token → 注入后仍然 401。"""
|
||||
seen, out = set(), []
|
||||
for part in (raw or '').split(';'):
|
||||
name, _, value = part.strip().partition('=')
|
||||
name = name.strip()
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append({'name': name, 'value': value.strip(), 'domain': config.CRM_DOMAIN})
|
||||
return out
|
||||
|
||||
|
||||
def _load_snapshot_cookies():
|
||||
"""读取落盘 Cookie 快照(优先已验证的真实请求头),去重后供浏览器注入。"""
|
||||
if os.path.exists(config.COOKIE_HEADER_FILE):
|
||||
try:
|
||||
with open(config.COOKIE_HEADER_FILE, encoding='utf-8') as f:
|
||||
cookies = _dedupe_pairs(f.read())
|
||||
if cookies:
|
||||
return cookies
|
||||
except Exception as e:
|
||||
_log(f"读取 Cookie 头失败:{e}", "WARN")
|
||||
if not os.path.exists(config.COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(config.COOKIE_FILE, encoding='utf-8') as f:
|
||||
raw = json.load(f)
|
||||
except Exception as e:
|
||||
_log(f"读取 cookies 文件失败:{e}", "WARN")
|
||||
return None
|
||||
seen, out = set(), []
|
||||
for c in raw or []:
|
||||
name, value = c.get('name'), c.get('value')
|
||||
if not name or name in seen or '37du.co' not in (c.get('domain') or ''):
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append({'name': name, 'value': value, 'domain': config.CRM_DOMAIN})
|
||||
return out or None
|
||||
|
||||
|
||||
def _api_ok(page):
|
||||
"""页面内 fetch 校验会话(code=S0 即有效),避免仅凭是否跳登录页误判。"""
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
return fetch('/membership/main/user', {headers: {'Accept': 'application/json'}})
|
||||
.then(r => r.status + ':' + r.text())
|
||||
.catch(e => 'ERR:' + e);
|
||||
''')
|
||||
return bool(raw) and str(raw).startswith('200:') and '"code":"S0"' in str(raw)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _inject_shared_cookies(page):
|
||||
"""注入落盘 Cookie 快照复活会话,返回是否注入成功。
|
||||
|
||||
仅在浏览器自身无有效会话时调用,避免用旧快照覆盖仍然有效的会话。"""
|
||||
cookies = _load_snapshot_cookies()
|
||||
if not cookies:
|
||||
_log("无可用 Cookie 快照,需扫码登录", "WARN")
|
||||
return False
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
_log(f"已注入共享 cookies({len(cookies)} 条,同名去重)")
|
||||
return True
|
||||
except Exception as e:
|
||||
_log(f"注入共享 cookies 失败(继续流程):{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 截图 ====================
|
||||
def _wait_login(page):
|
||||
"""等待登录完成:钉钉会话有效时自动静默重登(秒级),否则等人工扫码。"""
|
||||
_log("被弹回登录页,等待登录完成(刚扫码过会自动重登;否则请在窗口内扫码,最多等待 5 分钟)……")
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if not _is_login_page(page.url):
|
||||
time.sleep(config.LOGIN_SETTLE) # 首屏请求结束后再继续,避免会话轮换竞态
|
||||
_log(f"登录完成 → {page.url}")
|
||||
crm_login.save_from_page(page) # 同步给后续 requests 导出复用
|
||||
return True
|
||||
_log(f"等待登录超时({config.LOGIN_WAIT}s)", "ERROR")
|
||||
return False
|
||||
|
||||
|
||||
def _goto_ready(page, url):
|
||||
"""导航到目标页并等待标题就绪。
|
||||
|
||||
路由守卫可能延迟弹登录页(期间 SPA 会自动静默重登),一旦发现登录页就等待
|
||||
(静默重登优先、扫码兜底)后重导航,直到标题就绪或总超时。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT + config.LOAD_TIMEOUT + 60
|
||||
page.get(url)
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if _is_login_page(page.url):
|
||||
if not _wait_login(page):
|
||||
raise TimeoutError(f"登录未完成({config.LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
page.get(url)
|
||||
continue
|
||||
if config.PAGE_TITLE_KEYWORD in (page.title or ''):
|
||||
time.sleep(config.PAGE_SETTLE) # 等余额数字等数据渲染稳定
|
||||
return
|
||||
raise RuntimeError(f"页面未就绪(超时):{page.title}")
|
||||
|
||||
|
||||
def _capture_balance(save_dir, date_str, headless):
|
||||
"""单轮截图尝试:开浏览器 → 登录态保障 → 等渲染 → 整页截图。返回截图路径。"""
|
||||
filename = f"储值卡余额-{date_str}.png"
|
||||
save_path = os.path.join(save_dir, filename)
|
||||
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录:与 crm_login 共用,钉钉会话支撑静默重登
|
||||
profile_dir = config.get_browser_profile_dir()
|
||||
os.makedirs(profile_dir, exist_ok=True)
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
# 先看浏览器 profile 自身会话:有效就不注入,避免用旧快照覆盖仍有效的会话
|
||||
page.get(config.BALANCE_URL)
|
||||
if _is_login_page(page.url) or not _api_ok(page):
|
||||
if _inject_shared_cookies(page):
|
||||
page.get(config.BALANCE_URL)
|
||||
_goto_ready(page, config.BALANCE_URL)
|
||||
# 浏览器已登录,先把登录态同步落盘,截图失败也不影响第 2 步导出
|
||||
crm_login.save_from_page(page)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
page.get_screenshot(path=save_dir, name=filename, full_page=True)
|
||||
if not os.path.exists(save_path) or os.path.getsize(save_path) == 0:
|
||||
raise RuntimeError("截图文件未生成或为空")
|
||||
_log(f"截图完成 → {save_path}({os.path.getsize(save_path)} bytes)")
|
||||
return save_path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _screenshot(save_dir, date_str):
|
||||
"""截图重试 3 次;登录超时属人工未完成,不再重开浏览器。"""
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次截图 → {config.BALANCE_URL}")
|
||||
return _capture_balance(save_dir, date_str, config.HEADLESS)
|
||||
except TimeoutError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次截图异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"储值卡余额截图失败(重试 {config.RETRY_MAX} 次耗尽):{last_err}")
|
||||
|
||||
|
||||
# ==================== 报表导出 ====================
|
||||
def _date_window(rule):
|
||||
"""按规则返回 (起, 止) 日期。"""
|
||||
today = date.today()
|
||||
prev = today - timedelta(days=1)
|
||||
if rule == 'prev' or rule == 'prev_prev':
|
||||
return prev, prev
|
||||
if rule == 'prev_today':
|
||||
return prev, today
|
||||
if rule == 'month_to_today':
|
||||
return today.replace(day=1), today
|
||||
if rule == 'month1_to_prev':
|
||||
return today.replace(day=1), prev
|
||||
if rule == 'last_month':
|
||||
lm_last = today.replace(day=1) - timedelta(days=1)
|
||||
return lm_last.replace(day=1), lm_last
|
||||
raise ValueError(f"未知日期规则:{rule}")
|
||||
|
||||
|
||||
def _month_end(day):
|
||||
"""所在自然月最后一天。"""
|
||||
return (day.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1)
|
||||
|
||||
|
||||
def _date_windows(rule):
|
||||
"""把日期规则展开成 [(起, 止), ...]。
|
||||
|
||||
普通规则只有一个窗口;last3_months 用于礼品卡订单(接口限制查询跨度 ≤31 天),
|
||||
拆成近 3 个自然月分段,止日不超过前一天;月初运行时当月分段为空,自动跳过。"""
|
||||
if rule != 'last3_months':
|
||||
return [_date_window(rule)]
|
||||
prev = date.today() - timedelta(days=1)
|
||||
months, cur = [], date.today().replace(day=1)
|
||||
for _ in range(3):
|
||||
months.append(cur)
|
||||
cur = (cur - timedelta(days=1)).replace(day=1)
|
||||
windows = []
|
||||
for start in reversed(months):
|
||||
end = min(_month_end(start), prev)
|
||||
if start <= end:
|
||||
windows.append((start, end))
|
||||
return windows
|
||||
|
||||
|
||||
def _filename(title, beg, end):
|
||||
"""单日/起止统一命名(起=止退化为单日期)。"""
|
||||
if beg == end:
|
||||
return f"{title}-{beg:%Y%m%d}.xlsx"
|
||||
return f"{title}-{beg:%Y%m%d}-{end:%Y%m%d}.xlsx"
|
||||
|
||||
|
||||
def _download(session, url, params):
|
||||
"""下载并校验 xlsx 字节流;返回 (content, auth_failed)。"""
|
||||
resp = session.get(url, params=params, timeout=config.TIMEOUT)
|
||||
if resp.status_code == 200 and resp.content[:2] == b'PK':
|
||||
return resp.content, False
|
||||
if resp.status_code == 401 or b'E401' in resp.content[:200] or '未认证'.encode('utf-8') in resp.content[:200]:
|
||||
return None, True
|
||||
return None, False
|
||||
|
||||
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key):
|
||||
"""导出单张报表(按月规则会产出多个文件),返回落盘路径列表。"""
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key)
|
||||
for beg, end in _date_windows(rule)]
|
||||
|
||||
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
"""导出某个日期窗口(含 401 → 刷新登录态 → 重试),返回落盘路径。"""
|
||||
global _auth_dead
|
||||
|
||||
filename = _filename(title, beg, end)
|
||||
save_path = os.path.join(save_dir, filename)
|
||||
url = config.BASE + path
|
||||
date_val = f'{beg:%Y-%m-%d} {end:%Y-%m-%d}'
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params = {'pageNum': 1, 'pageSize': config.PAGE_SIZE, date_key: date_val}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
|
||||
session = crm_login.build_session()
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
if session is None:
|
||||
_log("无可用登录态,先触发登录流程……", "WARN")
|
||||
if not crm_login.ensure_login().get('success'):
|
||||
last_err = "登录态不可用(需人工扫码)"
|
||||
_auth_dead = True
|
||||
break
|
||||
session = crm_login.build_session()
|
||||
if session is None:
|
||||
last_err = "登录态不可用"
|
||||
_auth_dead = True
|
||||
break
|
||||
try:
|
||||
_log(f"[{attempt}/{config.RETRY_MAX}] {filename} ← {path} {date_key}={date_val}")
|
||||
content, auth_failed = _download(session, url, params)
|
||||
if content:
|
||||
with open(save_path, 'wb') as f:
|
||||
f.write(content)
|
||||
_log(f"导出完成 → {save_path}({len(content)} bytes)")
|
||||
return save_path
|
||||
last_err = "响应非 xlsx(可能未认证或接口变更)"
|
||||
if auth_failed:
|
||||
_log("登录态已失效,刷新登录态后重试……", "WARN")
|
||||
# 刷新失败(扫码超时/本次运行已扫过码)必须立即退出,
|
||||
# 否则每轮重试都会再弹一次扫码窗口
|
||||
if not crm_login.ensure_login().get('success'):
|
||||
last_err = "登录态刷新失败(需重新运行并扫码)"
|
||||
_auth_dead = True
|
||||
break
|
||||
session = crm_login.build_session()
|
||||
except Exception as e:
|
||||
last_err = f"下载异常:{e}"
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"{filename} 导出失败:{last_err}")
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def run_export(save_dir='', date_str=''):
|
||||
"""截图 + 18 张报表导出。
|
||||
|
||||
参数:
|
||||
save_dir 保存目录,默认 D:\\资料\\财务\\CRM数据导出
|
||||
date_str 截图文件名日期(YYYYMMDD),默认当日
|
||||
返回:
|
||||
{'screenshot': 截图路径, 'exports': [xlsx 路径...], 'errors': [],
|
||||
'done': 成功报表数, 'total': 报表总数}
|
||||
存在失败项时抛 RuntimeError(含明细)。
|
||||
"""
|
||||
global _auth_dead
|
||||
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
date_str = (date_str or '').strip() or time.strftime('%Y%m%d')
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
_auth_dead = False
|
||||
errors = []
|
||||
|
||||
# ---------- 0) 预检登录态:30 分钟内滑动会话直接命中,不开浏览器、不扫码 ----------
|
||||
config.progress(2)
|
||||
if crm_login.is_session_valid():
|
||||
_log("登录态有效(API 校验),本次运行免扫码")
|
||||
else:
|
||||
_log("登录态无效,本次运行需扫码一次(成功后后续步骤全部复用)……", "WARN")
|
||||
|
||||
# ---------- 1) 储值卡余额截图 ----------
|
||||
config.progress(5)
|
||||
shot = ''
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except TimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
config.progress(12)
|
||||
|
||||
# ---------- 2) 18 张报表导出 ----------
|
||||
saved, skipped = [], []
|
||||
done = 0
|
||||
total = len(config.REPORTS)
|
||||
for idx, (title, path, rule, extra, date_key) in enumerate(config.REPORTS, start=1):
|
||||
if _auth_dead:
|
||||
skipped.append(title)
|
||||
continue
|
||||
try:
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key))
|
||||
done += 1
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
_log(str(e), "ERROR")
|
||||
config.progress(12 + int(83 * idx / total))
|
||||
if skipped:
|
||||
errors.append(f"{'、'.join(skipped)}:登录态失效,已跳过")
|
||||
|
||||
_log(f"本次运行完成:截图 {1 if shot else 0}/1,报表 {done}/{total}(文件 {len(saved)} 个)")
|
||||
if errors:
|
||||
raise RuntimeError(f"存在失败项:{';'.join(errors)}")
|
||||
return {'screenshot': shot, 'exports': saved, 'errors': [],
|
||||
'done': done, 'total': total}
|
||||
@@ -0,0 +1,405 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0048 CRM 数据导出 - CRM(crm.37du.co)钉钉扫码登录模块。
|
||||
|
||||
从影刀版 workflows/share/crm_login.py 复制改造,插件内自包含,不跨目录 import。
|
||||
|
||||
流程(全程走官方登录页,零逆向):
|
||||
1. 纯 API 校验优先:落盘 Cookie 头 GET /membership/main/user 返回 code=S0 即复用
|
||||
(服务端滑动会话约 30 分钟,期间完全免扫码、不开浏览器);
|
||||
2. 失效才开浏览器:先给 profile 里残留会话一次短窗口机会(钉钉会话存活时 SPA
|
||||
静默重登),仍无效则停官方登录页等人工钉钉扫码(最多 5 分钟);
|
||||
3. 登录成功后抓浏览器实际发送的 Cookie 头(listen 捕获),经「浏览器 S0 + requests
|
||||
端到端 S0」双校验后原子落盘,供导出模块原样复刻。
|
||||
|
||||
扫码闸门:同一进程(= 同一次运行)最多弹一次扫码窗口,后续失效快速失败,
|
||||
绝不逐张报表重复弹窗把任务挂死。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
# ==================== 本次运行扫码闸门 ====================
|
||||
_scan_attempted = False
|
||||
_scan_failed_msg = None
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 登录页判定 ====================
|
||||
def _is_login_page(url):
|
||||
"""SPA hash 路由判定:hash 片段含 login 即仍在登录页。"""
|
||||
url = (url or '').strip()
|
||||
if not url or not url.lower().startswith('http'):
|
||||
return True
|
||||
fragment = url.split('#', 1)[1].lower() if '#' in url else ''
|
||||
return config.LOGIN_KEYWORD in fragment
|
||||
|
||||
|
||||
# ==================== 登录态落盘 ====================
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免并发/中断留下半截文件(半截快照必然 401)。"""
|
||||
_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 _save_login_state(page):
|
||||
"""保存 Cookies 与 localStorage/sessionStorage 票据(SPA 常把 token 放 storage)。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
_log(f"已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}")
|
||||
else:
|
||||
_log("未取到 Cookies(仅保存了 storage 票据?)", "WARN")
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const pick = (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: pick(window.localStorage),
|
||||
sessionStorage: pick(window.sessionStorage)
|
||||
});
|
||||
''')
|
||||
st = json.loads(raw) if raw else {}
|
||||
ls, ss = st.get('localStorage') or {}, st.get('sessionStorage') or {}
|
||||
if ls or ss:
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps(
|
||||
{"localStorage": ls, "sessionStorage": ss,
|
||||
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
|
||||
ensure_ascii=False, indent=2))
|
||||
_log(f"已保存票据 localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项")
|
||||
except Exception as e:
|
||||
_log(f"保存 storage 票据失败(不影响 Cookies):{e}", "WARN")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
"""读取落盘 Cookies;仅保留 37du.co 域(钉钉域 cookie 无需复用)。"""
|
||||
if not os.path.exists(config.COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(config.COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
except Exception as e:
|
||||
_log(f"读取 Cookies 文件失败:{e}", "WARN")
|
||||
return None
|
||||
return [c for c in (cookies or []) if '37du.co' in (c.get('domain') or '')] or None
|
||||
|
||||
|
||||
# ==================== 有效 Cookie 头捕获(requests 复放的权威来源) ====================
|
||||
def _load_header():
|
||||
if not os.path.exists(config.COOKIE_HEADER_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(config.COOKIE_HEADER_FILE, encoding='utf-8') as f:
|
||||
return f.read().strip() or None
|
||||
except Exception as e:
|
||||
_log(f"读取有效 Cookie 头失败:{e}", "WARN")
|
||||
return None
|
||||
|
||||
|
||||
def _header_from_json():
|
||||
"""按 cookies.json 原始顺序拼接 Cookie 头,保留同名重复项(轮换期并存的两个 x-token)。
|
||||
|
||||
不能走 session.cookies.set:requests 的 CookieJar 按 (domain, path, name) 去重,
|
||||
后写覆盖先写,会把新的 x-token 换成旧的 → 服务端取到作废 token 直接 401。"""
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return None
|
||||
return '; '.join(f'{c["name"]}={c["value"]}' for c in cookies if c.get('name'))
|
||||
|
||||
|
||||
def _verify_header(raw):
|
||||
"""端到端校验:用待落盘的 Cookie 头真实发一次 requests 请求。"""
|
||||
try:
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": config.SITE_URL,
|
||||
"Cookie": raw,
|
||||
})
|
||||
r = s.get(config.VALIDATE_URL, timeout=15)
|
||||
if r.status_code != 200:
|
||||
return False
|
||||
return r.json().get('code') == 'S0'
|
||||
except Exception as e:
|
||||
_log(f"Cookie 头端到端校验异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _save_effective_header(page):
|
||||
"""页面内发起一次 /membership/main/user,捕获浏览器实际发送的完整 Cookie 头,
|
||||
经「浏览器内 code=S0」+「requests 端到端 code=S0」双重校验后原子落盘。"""
|
||||
try:
|
||||
page.listen.start('main/user')
|
||||
page.run_js("fetch('/membership/main/user', {headers:{'Accept':'application/json'}})")
|
||||
p = page.listen.wait(timeout=10)
|
||||
page.listen.stop()
|
||||
if not p:
|
||||
_log("未捕获到浏览器验证请求,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
raw = None
|
||||
for k, v in (p.request.headers or {}).items():
|
||||
if k.lower() == 'cookie':
|
||||
raw = v
|
||||
if not raw:
|
||||
_log("验证请求无 Cookie 头,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
try:
|
||||
data = p.response.body if isinstance(p.response.body, dict) else json.loads(str(p.response.body))
|
||||
except Exception:
|
||||
data = {}
|
||||
if not (isinstance(data, dict) and data.get('code') == 'S0'):
|
||||
_log(f"捕获的 Cookie 头校验未通过:{str(data)[:120]}", "WARN")
|
||||
return False
|
||||
if not _verify_header(raw):
|
||||
_log("捕获的 Cookie 头在 requests 侧校验未通过,不覆盖已有快照", "WARN")
|
||||
return False
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, raw)
|
||||
_log(f"已保存有效 Cookie 头(浏览器 + requests 双校验 S0)")
|
||||
return True
|
||||
except Exception as e:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
_log(f"捕获有效 Cookie 头异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _repair_header_from_json():
|
||||
"""Cookie 头文件失效/损坏时的自愈:用 cookies.json 保序重建并端到端校验,成功回写。"""
|
||||
raw = _header_from_json()
|
||||
if not raw or not _verify_header(raw):
|
||||
return False
|
||||
if _load_header() != raw:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, raw)
|
||||
_log("已用 cookies.json 重建有效 Cookie 头并回写")
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 纯 API 校验与业务会话(免开浏览器) ====================
|
||||
def build_session():
|
||||
"""构建可复用登录态的 requests.Session(原样复刻浏览器 Cookie 头)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": config.SITE_URL,
|
||||
})
|
||||
raw = _load_header()
|
||||
if not raw:
|
||||
raw = _header_from_json()
|
||||
if raw:
|
||||
_log("Cookie 头文件缺失,已按 cookies.json 原始顺序重建", "WARN")
|
||||
if not raw:
|
||||
return None
|
||||
session.headers['Cookie'] = raw
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid():
|
||||
"""API 轻量校验登录态:GET /membership/main/user 返回 code=S0 视为有效。"""
|
||||
session = build_session()
|
||||
if session is None:
|
||||
return False
|
||||
try:
|
||||
resp = session.get(config.VALIDATE_URL, timeout=15)
|
||||
except Exception as e:
|
||||
_log(f"API 校验登录态异常:{e}")
|
||||
return False
|
||||
if resp.status_code != 200:
|
||||
_log(f"API 校验登录态状态码异常:{resp.status_code}")
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return False
|
||||
if data.get("success") and data.get("code") == "S0":
|
||||
return True
|
||||
_log(f"API 校验返回非成功码:{str(data)[:200]}")
|
||||
return False
|
||||
|
||||
|
||||
def keep_alive():
|
||||
"""轻量保活:一次 API 请求刷新服务端会话的空闲计时(会话为滑动过期)。"""
|
||||
return is_session_valid()
|
||||
|
||||
|
||||
def save_from_page(page):
|
||||
"""登录态已由浏览器建立时,把 cookies 与有效 Cookie 头同步落盘,供 requests 复用。"""
|
||||
_save_login_state(page)
|
||||
if not _save_effective_header(page):
|
||||
_repair_header_from_json()
|
||||
ok = is_session_valid()
|
||||
if ok:
|
||||
_log("登录态已同步落盘(requests 侧校验 S0 通过)")
|
||||
else:
|
||||
_log("登录态同步后 requests 侧仍不可用", "WARN")
|
||||
return ok
|
||||
|
||||
|
||||
# ==================== 登录态复用校验 ====================
|
||||
def _api_ok_in_browser(page):
|
||||
"""页面内 fetch 调 /membership/main/user 确定性校验会话(code=S0 即有效)。"""
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
return fetch('/membership/main/user', {headers: {'Accept': 'application/json'}})
|
||||
.then(r => r.status + ':' + r.text())
|
||||
.catch(e => 'ERR:' + e);
|
||||
''')
|
||||
return bool(raw) and str(raw).startswith('200:') and '"code":"S0"' in str(raw)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_api_ok(page, seconds):
|
||||
"""轮询等待页面内 API 校验通过(覆盖 SPA 首屏加载与静默重登耗时)。"""
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if _api_ok_in_browser(page):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _check_reuse(page):
|
||||
"""尝试复用浏览器 profile 里上一次残留的会话,返回是否成功。
|
||||
|
||||
走到这里说明落盘快照已经过纯 API 校验且失败(服务端会话已作废),因此**不再注入
|
||||
快照 Cookie**:注入既救不活作废票据,还可能把 profile 里仍有效的会话覆盖成作废值。"""
|
||||
page.get(config.SITE_URL)
|
||||
if _wait_api_ok(page, config.PROFILE_REUSE_WAIT):
|
||||
_log("浏览器 profile 自身会话有效,直接续用")
|
||||
return True
|
||||
_log("浏览器 profile 无有效会话(落盘 Cookie 快照已在服务端失效)", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 扫码等待 ====================
|
||||
def _wait_scan(page, wait_scan):
|
||||
"""等待登录完成(hash 离开 #/login 即成功)。
|
||||
|
||||
浏览器 profile 内钉钉长效 cookie 有效时会静默调 /membership/dingtalkLogin 自动重登,
|
||||
无需扫码;仅钉钉会话也失效时才需人工扫码。"""
|
||||
_log("等待登录完成(刚扫码过会自动重登;否则请在窗口内扫码)……")
|
||||
deadline = time.time() + wait_scan
|
||||
hinted = False
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if not _is_login_page(page.url):
|
||||
time.sleep(2) # 让 SPA 完成跳转与 token 写入
|
||||
return True
|
||||
remaining = int(deadline - time.time())
|
||||
if not hinted and remaining <= wait_scan - 60:
|
||||
_log("仍未检测到扫码登录,请确认已用钉钉 App 扫码并点击确认……")
|
||||
hinted = True
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 单轮登录尝试 ====================
|
||||
def _attempt(force, headless, wait_scan):
|
||||
"""一轮完整流程:开浏览器 → 未 force 先尝试复用 → 失效则等待扫码。"""
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录:浏览器层也保留登录态,与 cookies 落盘双保险
|
||||
profile_dir = config.get_browser_profile_dir()
|
||||
_ensure_dir(profile_dir)
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not force and _check_reuse(page):
|
||||
# 静默重登可能已在浏览器内刷新会话,等首屏请求结束后同步文件快照
|
||||
time.sleep(config.LOGIN_SETTLE)
|
||||
save_from_page(page)
|
||||
return True, "复用缓存登录态", False
|
||||
_log("登录态失效或不存在,打开官方登录页等待扫码……")
|
||||
page.get(config.LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if _wait_scan(page, wait_scan):
|
||||
_log(f"登录成功 → {page.url}")
|
||||
time.sleep(config.LOGIN_SETTLE) # 首屏请求结束后再抓,避免轮换前快照
|
||||
save_from_page(page)
|
||||
return True, "登录成功", True
|
||||
_log(f"等待超时({wait_scan}s 内未检测到扫码登录)", "ERROR")
|
||||
return False, "扫码登录超时(未检测到登录成功)", True
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(force=False, headless=None, wait_scan=None):
|
||||
"""确保存在有效的 CRM 登录态并落盘票据(钉钉扫码,人工在场)。
|
||||
|
||||
返回 dict:{success, cookie_path, token_path, message, relogin}
|
||||
"""
|
||||
global _scan_attempted, _scan_failed_msg
|
||||
|
||||
headless = config.HEADLESS if headless is None else bool(headless)
|
||||
wait_scan = config.SCAN_WAIT if wait_scan is None else int(wait_scan)
|
||||
|
||||
# ①纯 API 校验优先:cookies 有效时全程免开浏览器
|
||||
if not force:
|
||||
if is_session_valid():
|
||||
_log("已通过缓存的 Cookies 复用 CRM 登录态(API 校验)")
|
||||
return {"success": True, "cookie_path": config.COOKIE_FILE, "token_path": config.TOKEN_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
# ①b Cookie 头文件损坏/同名项顺序错、而 cookies.json 仍完好时自愈
|
||||
if _repair_header_from_json():
|
||||
_log("已用 cookies.json 重建 Cookie 头,复用 CRM 登录态")
|
||||
return {"success": True, "cookie_path": config.COOKIE_FILE, "token_path": config.TOKEN_FILE,
|
||||
"message": "复用缓存登录态(重建 Cookie 头)", "relogin": False}
|
||||
|
||||
# ②本次运行已弹过扫码窗口:不再重复弹,直接快速失败
|
||||
if _scan_attempted:
|
||||
msg = _scan_failed_msg or "本次运行已尝试过扫码登录,登录态仍失效;请重新运行任务并完成扫码"
|
||||
_log(msg, "WARN")
|
||||
return {"success": False, "cookie_path": config.COOKIE_FILE, "token_path": config.TOKEN_FILE,
|
||||
"message": msg, "relogin": False}
|
||||
_scan_attempted = True
|
||||
|
||||
# ③开浏览器:profile 层复用兜底,失效则扫码
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
ok, msg, relogin = _attempt(force, headless, wait_scan)
|
||||
if not ok:
|
||||
_scan_failed_msg = msg
|
||||
return {"success": ok, "cookie_path": config.COOKIE_FILE, "token_path": config.TOKEN_FILE,
|
||||
"message": msg, "relogin": relogin}
|
||||
except Exception as e:
|
||||
last_msg = f"登录过程异常:{e}"
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
_scan_failed_msg = last_msg or "登录失败"
|
||||
return {"success": False, "cookie_path": config.COOKIE_FILE, "token_path": config.TOKEN_FILE,
|
||||
"message": _scan_failed_msg, "relogin": False}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0048",
|
||||
"name": "CRM数据导出",
|
||||
"version": "1.0.0",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": false,
|
||||
"capabilities": ["xq0048"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "D:\\资料\\财务\\CRM数据导出",
|
||||
"description": "截图与全部 xlsx 统一输出目录"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
@@ -0,0 +1,484 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: crm_export_all.py
|
||||
@Description: XQ0048 CRM 数据导出(单脚本全流程:储值卡余额截图 + 18 张报表导出)。
|
||||
|
||||
一次运行只登录一次:
|
||||
0) 预检 —— 落盘 Cookies 经 API 校验有效(服务端滑动会话约 30 分钟)就直接复用,
|
||||
全程不开浏览器、不扫码;
|
||||
1) 截图 —— 开浏览器访问「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png。
|
||||
浏览器 profile 自带会话有效就直接用;无会话才按已验证 Cookie 头去重注入;
|
||||
仍无效才等扫码(最多 5 分钟)。截图后把登录态同步落盘;
|
||||
2) 导出 —— requests 复用同一登录态,按日期规则导出 18 张 xlsx。
|
||||
|
||||
同一次运行最多弹一次扫码窗口(crm_login 的扫码闸门);扫码后仍失效则快速失败,
|
||||
不会逐张报表重复弹窗。进程退出闸门自动复位,下次运行重新计。
|
||||
|
||||
日期规则:
|
||||
前一天单日:团购支付数据 / 现金支付 / 第三方支付(门店)/ 支付数据
|
||||
昨日 ~ 今日:团购数据 / 淘宝订单数据
|
||||
本月 1 日 ~ 今日:技师综合业绩
|
||||
昨日 ~ 昨日:微盟核销统计
|
||||
上月完整 + 本月 1 日 ~ 今日:小程序订单(两份)
|
||||
本月 1 日 ~ 前一天:储值卡消费 / 储值卡线上充值(渠道=管理端 channel=3)/
|
||||
霸王餐充值明细 / 霸王餐消费明细 / 霸王餐余额查询 /
|
||||
用户管理-开卡订单 / 用户管理-会员退卡
|
||||
近 3 个自然月按月拆分:礼品卡订单(领取时间;接口限制查询跨度 ≤31 天,
|
||||
故每月一个文件,止日不超过前一天)
|
||||
|
||||
接口规律(2026-10-21 逆向实测):
|
||||
报表统计:GET https://crm.37du.co/membership/report/{kind}/export?pageNum=1&pageSize=13&reportDate=...
|
||||
用户管理:GET .../membership/member/order/export、.../member/cancel/export,日期参数 period
|
||||
礼品卡: GET .../membership/giftcard/order/export,日期参数 receiveTimePeriod
|
||||
单日 reportDate=YYYY-MM-DD;区间一律 YYYY-MM-DD%20YYYY-MM-DD(空格分隔)。
|
||||
礼品卡接跨度 >31 天返回 400 E1005「查询时间隔时间不能大于31天」。
|
||||
pageSize 不影响导出行数(服务端全量导出)。响应 200 且以 PK 开头即 xlsx。
|
||||
|
||||
落盘:D:\\资料\\财务\\CRM数据导出
|
||||
储值卡余额-YYYYMMDD.png、{报表名}-YYYYMMDD.xlsx / {报表名}-起-止.xlsx
|
||||
|
||||
登录态:workflows/share/crm_login.py(共用浏览器 profile 与 .sessions 快照)
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests
|
||||
|
||||
入口:
|
||||
main(save_dir='', date_str='') 影刀调用入口,返回 {screenshot, exports, errors}
|
||||
python crm_export_all.py 本地自测(默认参数)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
# ---- 引入共享登录模块(workflows/share) ----
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_SHARE_DIR = os.path.join(os.path.dirname(os.path.dirname(_HERE)), 'share')
|
||||
sys.path.insert(0, _SHARE_DIR)
|
||||
import crm_login # noqa: E402
|
||||
|
||||
# ================== 站点与路由 ==================
|
||||
BASE = 'https://crm.37du.co/membership/'
|
||||
BALANCE_URL = 'https://crm.37du.co/#/reort/balance' # 报表统计/储值卡余额(reort 为站点实际拼写)
|
||||
LOGIN_KEYWORD = 'login' # hash 片段含 login 即登录页
|
||||
PAGE_TITLE_KEYWORD = '储值卡余额' # 截图页就绪判定
|
||||
|
||||
# ================== 落盘路径 ==================
|
||||
SAVE_DIR = r'D:\资料\财务\CRM数据导出'
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'crm_cookies.json')
|
||||
SHARED_HEADER_FILE = os.path.join(SESSIONS_DIR, 'crm_cookie_header.txt')
|
||||
BROWSER_PROFILE_DIR = os.path.join(_APP_DATA_DIR, 'browser_sessions', 'crm')
|
||||
CRM_DOMAIN = 'crm.37du.co'
|
||||
|
||||
# ================== 全局配置 ==================
|
||||
RETRY_MAX = 3 # 截图/单报表重试(项目级重试机制)
|
||||
PAGE_SIZE = 13 # 与页面一致;实测服务端导出不受分页影响
|
||||
TIMEOUT = 180 # 大报表(数万行)下载超时
|
||||
LOAD_TIMEOUT = 30 # 等页面标题就绪的最长秒数
|
||||
PAGE_SETTLE = 5 # 数据渲染稳定等待(秒)
|
||||
LOGIN_SETTLE = 8 # 登录成功后等首屏请求结束再抓 cookie(过早快照会被轮换作废)
|
||||
LOGIN_WAIT = 300 # 等待扫码超时(秒),人工操作给足窗口
|
||||
HEADLESS = False # 扫码兜底需可见浏览器
|
||||
|
||||
# ================== 报表清单(名称, 导出接口, 日期规则, 附加参数, 日期参数字段) ==================
|
||||
# 规则:prev=前一天单日;prev_today=昨日~今日;month_to_today=本月1日~今日;
|
||||
# prev_prev=昨日~昨日;month1_to_prev=本月1日~前一天;last_month=上月完整;
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天)
|
||||
# 日期参数字段:报表统计类为 reportDate;开卡订单/会员退卡为 period;
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分)
|
||||
REPORTS = [
|
||||
('团购支付数据', 'report/groupPay/export', 'prev', None, 'reportDate'),
|
||||
('现金支付', 'report/cashPay/export', 'prev', None, 'reportDate'),
|
||||
('第三方支付(门店)', 'report/thirdPayShop/export', 'prev', None, 'reportDate'),
|
||||
('支付数据', 'report/unionPay/export', 'prev', None, 'reportDate'),
|
||||
('团购数据', 'report/groupData/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'reportDate'),
|
||||
('技师综合业绩', 'report/comprehensivePerformance/export', 'month_to_today', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'last_month', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'month_to_today', None, 'reportDate'),
|
||||
('储值卡消费', 'report/debitCardConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('储值卡线上充值', 'report/depositData/export', 'month1_to_prev', {'channel': 3}, 'reportDate'), # 渠道=管理端
|
||||
('霸王餐充值明细', 'report/overlordOrderDeposit/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('霸王餐消费明细', 'report/overlordOrderConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('霸王餐余额查询', 'report/overlordOrderBalance/export', 'month1_to_prev', None, 'reportDate'),
|
||||
('开卡订单', 'member/order/export', 'month1_to_prev', None, 'period'),
|
||||
('会员退卡', 'member/cancel/export', 'month1_to_prev', None, 'period'),
|
||||
('礼品卡订单', 'giftcard/order/export', 'last3_months', None, 'receiveTimePeriod'),
|
||||
]
|
||||
|
||||
# 本次运行登录态是否已判定无救(crm_login 的扫码闸门用尽)。
|
||||
# 置位后剩余报表直接跳过,避免逐张再发 401 请求、也不再弹扫码窗口。
|
||||
_auth_dead = False
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
print(f"[XQ0048] {msg}" if level == "INFO" else f"[XQ0048][{level}] {msg}")
|
||||
|
||||
|
||||
# ================== 登录页与 Cookie 注入 ==================
|
||||
def _is_login_page(url):
|
||||
"""SPA hash 路由判定:hash 片段含 login 即仍在登录页。"""
|
||||
url = (url or '').strip()
|
||||
if not url or not url.lower().startswith('http'):
|
||||
return True
|
||||
fragment = url.split('#', 1)[1].lower() if '#' in url else ''
|
||||
return LOGIN_KEYWORD in fragment
|
||||
|
||||
|
||||
def _dedupe_pairs(raw):
|
||||
"""把 Cookie 头字符串转成注入列表:同名条目只留首个(浏览器发送顺序,新 x-token 在前)。
|
||||
|
||||
本站 x-token 会并存新旧两个,而 page.set.cookies 只支持 name/value/domain,
|
||||
同名条目后写覆盖先写;整包注入只会留下作废的旧 token → 注入后仍然 401。"""
|
||||
seen, out = set(), []
|
||||
for part in (raw or '').split(';'):
|
||||
name, _, value = part.strip().partition('=')
|
||||
name = name.strip()
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append({'name': name, 'value': value.strip(), 'domain': CRM_DOMAIN})
|
||||
return out
|
||||
|
||||
|
||||
def _load_snapshot_cookies():
|
||||
"""读取落盘 Cookie 快照(优先已验证的真实请求头),去重后供浏览器注入。"""
|
||||
if os.path.exists(SHARED_HEADER_FILE):
|
||||
try:
|
||||
with open(SHARED_HEADER_FILE, encoding='utf-8') as f:
|
||||
cookies = _dedupe_pairs(f.read())
|
||||
if cookies:
|
||||
return cookies
|
||||
except Exception as e:
|
||||
_log(f"读取 Cookie 头失败:{e}", "WARN")
|
||||
if not os.path.exists(SHARED_COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(SHARED_COOKIE_FILE, encoding='utf-8') as f:
|
||||
raw = json.load(f)
|
||||
except Exception as e:
|
||||
_log(f"读取 cookies 文件失败:{e}", "WARN")
|
||||
return None
|
||||
seen, out = set(), []
|
||||
for c in raw or []:
|
||||
name, value = c.get('name'), c.get('value')
|
||||
if not name or name in seen or '37du.co' not in (c.get('domain') or ''):
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append({'name': name, 'value': value, 'domain': CRM_DOMAIN})
|
||||
return out or None
|
||||
|
||||
|
||||
def _api_ok(page):
|
||||
"""页面内 fetch 校验会话(code=S0 即有效),避免仅凭是否跳登录页误判。"""
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
return fetch('/membership/main/user', {headers: {'Accept': 'application/json'}})
|
||||
.then(r => r.status + ':' + r.text())
|
||||
.catch(e => 'ERR:' + e);
|
||||
''')
|
||||
return bool(raw) and str(raw).startswith('200:') and '"code":"S0"' in str(raw)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _inject_shared_cookies(page):
|
||||
"""注入落盘 Cookie 快照复活会话,返回是否注入成功。
|
||||
|
||||
仅在浏览器自身无有效会话时调用,避免用旧快照覆盖仍然有效的会话。"""
|
||||
cookies = _load_snapshot_cookies()
|
||||
if not cookies:
|
||||
_log("无可用 Cookie 快照,需扫码登录", "WARN")
|
||||
return False
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
_log(f"已注入共享 cookies({len(cookies)} 条,同名去重)")
|
||||
return True
|
||||
except Exception as e:
|
||||
_log(f"注入共享 cookies 失败(继续流程):{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 截图 ==================
|
||||
def _wait_login(page):
|
||||
"""等待登录完成:钉钉会话有效时自动静默重登(秒级),否则等人工扫码。"""
|
||||
_log("被弹回登录页,等待登录完成(刚扫码过会自动重登;否则请在窗口内扫码,最多等待 5 分钟)……")
|
||||
deadline = time.time() + LOGIN_WAIT
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if not _is_login_page(page.url):
|
||||
time.sleep(LOGIN_SETTLE) # 首屏请求结束后再继续,避免会话轮换竞态
|
||||
_log(f"登录完成 → {page.url}")
|
||||
crm_login.save_from_page(page) # 同步给后续 requests 导出复用
|
||||
return True
|
||||
_log(f"等待登录超时({LOGIN_WAIT}s)", "ERROR")
|
||||
return False
|
||||
|
||||
|
||||
def _goto_ready(page, url):
|
||||
"""导航到目标页并等待标题就绪。
|
||||
|
||||
统一登录态保障:路由守卫可能延迟弹登录页(期间 SPA 会自动静默重登),
|
||||
一旦发现登录页就等待(静默重登优先、扫码兜底)后重导航,直到标题就绪或总超时。"""
|
||||
deadline = time.time() + LOGIN_WAIT + LOAD_TIMEOUT + 60
|
||||
page.get(url)
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if _is_login_page(page.url):
|
||||
if not _wait_login(page):
|
||||
raise TimeoutError(f"登录未完成({LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
page.get(url)
|
||||
continue
|
||||
if PAGE_TITLE_KEYWORD in (page.title or ''):
|
||||
time.sleep(PAGE_SETTLE) # 等余额数字等数据渲染稳定
|
||||
return
|
||||
raise RuntimeError(f"页面未就绪(超时):{page.title}")
|
||||
|
||||
|
||||
def _capture_balance(save_dir, date_str, headless):
|
||||
"""单轮截图尝试:开浏览器 → 登录态保障 → 等渲染 → 整页截图。返回截图路径。"""
|
||||
filename = f"储值卡余额-{date_str}.png"
|
||||
save_path = os.path.join(save_dir, filename)
|
||||
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录:与 crm_login.py 共用,钉钉会话支撑静默重登
|
||||
os.makedirs(BROWSER_PROFILE_DIR, exist_ok=True)
|
||||
co.set_user_data_path(BROWSER_PROFILE_DIR)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
# 先看浏览器 profile 自身会话:有效就不注入,避免用旧快照覆盖仍有效的会话
|
||||
page.get(BALANCE_URL)
|
||||
if _is_login_page(page.url) or not _api_ok(page):
|
||||
if _inject_shared_cookies(page):
|
||||
page.get(BALANCE_URL)
|
||||
_goto_ready(page, BALANCE_URL)
|
||||
# 浏览器已登录,先把登录态同步落盘,截图失败也不影响第 2 步导出
|
||||
crm_login.save_from_page(page)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
page.get_screenshot(path=save_dir, name=filename, full_page=True)
|
||||
if not os.path.exists(save_path) or os.path.getsize(save_path) == 0:
|
||||
raise RuntimeError("截图文件未生成或为空")
|
||||
_log(f"截图完成 → {save_path}({os.path.getsize(save_path)} bytes)")
|
||||
return save_path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _screenshot(save_dir, date_str):
|
||||
"""截图重试 3 次;登录超时属人工未完成,不再重开浏览器。"""
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
try:
|
||||
_log(f"第 {attempt}/{RETRY_MAX} 次截图 → {BALANCE_URL}")
|
||||
return _capture_balance(save_dir, date_str, HEADLESS)
|
||||
except TimeoutError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
_log(f"第 {attempt}/{RETRY_MAX} 次截图异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"储值卡余额截图失败(重试 {RETRY_MAX} 次耗尽):{last_err}")
|
||||
|
||||
|
||||
# ================== 报表导出 ==================
|
||||
def _date_window(rule):
|
||||
"""按规则返回 (起, 止) 日期。"""
|
||||
today = date.today()
|
||||
prev = today - timedelta(days=1)
|
||||
if rule == 'prev' or rule == 'prev_prev':
|
||||
return prev, prev
|
||||
if rule == 'prev_today':
|
||||
return prev, today
|
||||
if rule == 'month_to_today':
|
||||
return today.replace(day=1), today
|
||||
if rule == 'month1_to_prev':
|
||||
return today.replace(day=1), prev
|
||||
if rule == 'last_month':
|
||||
lm_last = today.replace(day=1) - timedelta(days=1)
|
||||
return lm_last.replace(day=1), lm_last
|
||||
raise ValueError(f"未知日期规则:{rule}")
|
||||
|
||||
|
||||
def _month_end(day):
|
||||
"""所在自然月最后一天。"""
|
||||
return (day.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1)
|
||||
|
||||
|
||||
def _date_windows(rule):
|
||||
"""把日期规则展开成 [(起, 止), ...]。
|
||||
|
||||
普通规则只有一个窗口;last3_months 用于礼品卡订单(接口限制查询跨度 ≤31 天),
|
||||
拆成近 3 个自然月分段,止日不超过前一天;月初运行时当月分段为空,自动跳过。"""
|
||||
if rule != 'last3_months':
|
||||
return [_date_window(rule)]
|
||||
prev = date.today() - timedelta(days=1)
|
||||
months, cur = [], date.today().replace(day=1)
|
||||
for _ in range(3):
|
||||
months.append(cur)
|
||||
cur = (cur - timedelta(days=1)).replace(day=1)
|
||||
windows = []
|
||||
for start in reversed(months):
|
||||
end = min(_month_end(start), prev)
|
||||
if start <= end:
|
||||
windows.append((start, end))
|
||||
return windows
|
||||
|
||||
|
||||
def _filename(title, beg, end):
|
||||
"""单日/起止统一命名(起=止退化为单日期)。"""
|
||||
if beg == end:
|
||||
return f"{title}-{beg:%Y%m%d}.xlsx"
|
||||
return f"{title}-{beg:%Y%m%d}-{end:%Y%m%d}.xlsx"
|
||||
|
||||
|
||||
def _download(session, url, params):
|
||||
"""下载并校验 xlsx 字节流;返回 (content, auth_failed)。"""
|
||||
resp = session.get(url, params=params, timeout=TIMEOUT)
|
||||
if resp.status_code == 200 and resp.content[:2] == b'PK':
|
||||
return resp.content, False
|
||||
if resp.status_code == 401 or b'E401' in resp.content[:200] or '未认证'.encode('utf-8') in resp.content[:200]:
|
||||
return None, True
|
||||
return None, False
|
||||
|
||||
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key):
|
||||
"""导出单张报表(按月规则会产出多个文件),返回落盘路径列表。"""
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key)
|
||||
for beg, end in _date_windows(rule)]
|
||||
|
||||
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
"""导出某个日期窗口(含 401 → 刷新登录态 → 重试),返回落盘路径。"""
|
||||
global _auth_dead
|
||||
|
||||
filename = _filename(title, beg, end)
|
||||
save_path = os.path.join(save_dir, filename)
|
||||
url = BASE + path
|
||||
date_val = f'{beg:%Y-%m-%d} {end:%Y-%m-%d}'
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params = {'pageNum': 1, 'pageSize': PAGE_SIZE, date_key: date_val}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
|
||||
session = crm_login.build_session()
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
if session is None:
|
||||
_log("无可用登录态,先触发登录流程……", "WARN")
|
||||
if not crm_login.ensure_login().get('success'):
|
||||
last_err = "登录态不可用(需人工扫码)"
|
||||
_auth_dead = True
|
||||
break
|
||||
session = crm_login.build_session()
|
||||
if session is None:
|
||||
last_err = "登录态不可用"
|
||||
_auth_dead = True
|
||||
break
|
||||
try:
|
||||
_log(f"[{attempt}/{RETRY_MAX}] {filename} ← {path} {date_key}={date_val}")
|
||||
content, auth_failed = _download(session, url, params)
|
||||
if content:
|
||||
with open(save_path, 'wb') as f:
|
||||
f.write(content)
|
||||
_log(f"导出完成 → {save_path}({len(content)} bytes)")
|
||||
return save_path
|
||||
last_err = "响应非 xlsx(可能未认证或接口变更)"
|
||||
if auth_failed:
|
||||
_log("登录态已失效,刷新登录态后重试……", "WARN")
|
||||
# 刷新失败(如扫码超时/本次运行已扫过码)必须立即退出,
|
||||
# 否则每轮重试都会再弹一次扫码窗口
|
||||
if not crm_login.ensure_login().get('success'):
|
||||
last_err = "登录态刷新失败(需重新运行并扫码)"
|
||||
_auth_dead = True
|
||||
break
|
||||
session = crm_login.build_session()
|
||||
except Exception as e:
|
||||
last_err = f"下载异常:{e}"
|
||||
_log(f"第 {attempt}/{RETRY_MAX} 次异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"{filename} 导出失败:{last_err}")
|
||||
|
||||
|
||||
# ================== 主入口 ==================
|
||||
def main(save_dir='', date_str=''):
|
||||
"""影刀调用入口:截图 + 18 张报表导出。
|
||||
|
||||
参数:
|
||||
save_dir 保存目录,默认 D:\\资料\\财务\\CRM数据导出
|
||||
date_str 截图文件名日期(YYYYMMDD),默认当日
|
||||
返回:
|
||||
{'screenshot': 截图路径, 'exports': [xlsx 路径...], 'errors': []}
|
||||
失败时有失败项则抛 RuntimeError(含明细)。
|
||||
"""
|
||||
global _auth_dead
|
||||
|
||||
save_dir = (save_dir or '').strip().strip('"') or SAVE_DIR
|
||||
date_str = (date_str or '').strip() or time.strftime('%Y%m%d')
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
_auth_dead = False
|
||||
errors = []
|
||||
|
||||
# ---------- 0) 预检登录态:30 分钟内滑动会话直接命中,不开浏览器、不扫码 ----------
|
||||
if crm_login.is_session_valid():
|
||||
_log("登录态有效(API 校验),本次运行免扫码")
|
||||
else:
|
||||
_log("登录态无效,本次运行需扫码一次(成功后后续步骤全部复用)……", "WARN")
|
||||
|
||||
# ---------- 1) 储值卡余额截图 ----------
|
||||
shot = ''
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except TimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
|
||||
# ---------- 2) 18 张报表导出 ----------
|
||||
saved, skipped = [], []
|
||||
done = 0
|
||||
for title, path, rule, extra, date_key in REPORTS:
|
||||
if _auth_dead:
|
||||
skipped.append(title)
|
||||
continue
|
||||
try:
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key))
|
||||
done += 1
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
_log(str(e), "ERROR")
|
||||
if skipped:
|
||||
errors.append(f"{'、'.join(skipped)}:登录态失效,已跳过")
|
||||
|
||||
_log(f"本次运行完成:截图 {1 if shot else 0}/1,报表 {done}/{len(REPORTS)}(文件 {len(saved)} 个)")
|
||||
if errors:
|
||||
raise RuntimeError(f"存在失败项:{';'.join(errors)}")
|
||||
return {'screenshot': shot, 'exports': saved, 'errors': []}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
result = main()
|
||||
print("截图:", result['screenshot'])
|
||||
for p in result['exports']:
|
||||
print(" -", p)
|
||||
@@ -0,0 +1,508 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: crm_login.py
|
||||
@Description: 37du CRM(crm.37du.co)登录模块,钉钉扫码登录版。
|
||||
打开可见浏览器停在官方登录页 → 用户用钉钉 App 扫码 → 检测 URL 离开
|
||||
登录页即视为成功 → 保存 Cookies + localStorage/sessionStorage 票据落盘,
|
||||
供业务脚本构建 requests.Session 复用。全程走官方登录页,零逆向。
|
||||
|
||||
登录链路(官方页面自完成,脚本只负责等待与取票据):
|
||||
1. 打开 https://crm.37du.co/#/login(页面内嵌钉钉扫码 iframe);
|
||||
2. 人工用钉钉扫码并确认(脚本不干预跨域 iframe);
|
||||
3. 登录成功后 SPA hash 路由离开 #/login → 判定成功(钉钉会话有效时浏览器会静默
|
||||
调 /membership/dingtalkLogin 自动重登,无需扫码);
|
||||
4. 等首屏请求结束后保存 Cookies(crm_cookies.json;过早抓取会被服务端会话轮换作废),
|
||||
及 localStorage/sessionStorage(crm_tokens.json,当前站点纯 cookie 鉴权通常为空)。
|
||||
|
||||
登录态复用(两级校验):
|
||||
①纯 API 校验(免开浏览器):GET /membership/main/user 返回 {"code":"S0","success":true}
|
||||
即 cookies 有效,直接复用(服务端会话为滑动过期,实测空闲 ≥30 分钟内有效,
|
||||
期间重复运行完全免扫码、不弹浏览器);
|
||||
②①失败才开浏览器:给浏览器 profile 里上次残留的会话一次短窗口机会
|
||||
(钉钉会话存活时 SPA 会静默重登),仍无有效会话则转扫码流程。
|
||||
|
||||
扫码闸门:同一进程(= 同一次运行)最多弹一次扫码窗口。中途会话再失效时直接
|
||||
快速失败并提示重跑,绝不反复弹窗把任务挂死。
|
||||
|
||||
落盘位置(与 oa_login 等共享模块统一,%LOCALAPPDATA%\\37duAutomation\\.sessions):
|
||||
crm_cookies.json Cookies 列表(name/value/domain/path/expires/...)
|
||||
crm_tokens.json {"localStorage": {...}, "sessionStorage": {...}, "saved_at": ...}
|
||||
|
||||
浏览器:独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\crm,
|
||||
不占用用户日常 Chrome 配置,登录态跨次保留。
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests
|
||||
|
||||
入口:
|
||||
main(force=True) 影刀自定义指令调用入口,返回 JSON 安全 dict
|
||||
{success, cookie_path, token_path, message, relogin}
|
||||
crm_login(force) 同 ensure_login,返回同上
|
||||
直接运行 python crm_login.py 自测(弹浏览器扫码)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
# ================== 站点定义 ==================
|
||||
SITE_URL = 'https://crm.37du.co/'
|
||||
LOGIN_URL = 'https://crm.37du.co/#/login'
|
||||
# 会话校验接口:cookies 有效返回 {"code":"S0","success":true,"data":{userid,username}}
|
||||
VALIDATE_URL = 'https://crm.37du.co/membership/main/user'
|
||||
|
||||
# ================== 落盘路径 ==================
|
||||
_APP_DATA_DIR = 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, 'crm_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'crm_cookie_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'crm_tokens.json')
|
||||
BROWSER_PROFILE_DIR = os.path.join(_APP_DATA_DIR, 'browser_sessions', 'crm')
|
||||
|
||||
# ================== 全局配置 ==================
|
||||
RETRY_MAX = 3 # 浏览器打开/页面加载类异常重试(项目级重试机制)
|
||||
PROFILE_REUSE_WAIT = 10 # 浏览器 profile 残留会话 / 静默重登的观察窗口;无效即尽快转扫码
|
||||
SETTLE_WAIT = 8 # 登录成功后等待 SPA 首屏请求结束再抓 cookie(过早快照会被服务端轮换作废)
|
||||
SCAN_WAIT = 300 # 等待用户扫码超时(秒),人工操作给足窗口
|
||||
HEADLESS = False # 默认可见浏览器(扫码必须人工在场)
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
# ================== 本次运行扫码闸门 ==================
|
||||
# 同一进程 = 同一次运行,最多触发一次扫码窗口。多张报表连续 401 时若每张都弹一次
|
||||
# 300 秒扫码等待,任务会被挂死十几分钟;运行结束进程退出,闸门自动复位。
|
||||
_scan_attempted = False
|
||||
_scan_failed_msg = None
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
"""统一日志前缀,便于影刀日志检索。"""
|
||||
print(f"[CRM登录] {msg}" if level == "INFO" else f"[CRM登录][{level}] {msg}")
|
||||
|
||||
|
||||
# ================== 登录页判定 ==================
|
||||
def _is_login_page(url):
|
||||
"""SPA hash 路由判定:hash 片段含 login 即仍在登录页。"""
|
||||
url = (url or '').strip()
|
||||
if not url or not url.lower().startswith('http'):
|
||||
return True
|
||||
fragment = url.split('#', 1)[1].lower() if '#' in url else ''
|
||||
return 'login' in fragment
|
||||
|
||||
|
||||
# ================== 登录态落盘 ==================
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免并发/中断留下半截文件(半截快照必然 401)。"""
|
||||
_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 _save_login_state(page):
|
||||
"""保存 Cookies 与 localStorage/sessionStorage 票据(SPA 常把 token 放 storage)。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
_ensure_dir(SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
_log(f"已保存 {len(cookies)} 个 Cookies → {COOKIE_FILE}")
|
||||
else:
|
||||
_log("未取到 Cookies(仅保存了 storage 票据?)", "WARN")
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const pick = (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: pick(window.localStorage),
|
||||
sessionStorage: pick(window.sessionStorage)
|
||||
});
|
||||
''')
|
||||
st = json.loads(raw) if raw else {}
|
||||
ls, ss = st.get('localStorage') or {}, st.get('sessionStorage') or {}
|
||||
if ls or ss:
|
||||
_atomic_write(TOKEN_FILE, json.dumps(
|
||||
{"localStorage": ls, "sessionStorage": ss,
|
||||
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
|
||||
ensure_ascii=False, indent=2))
|
||||
_log(f"已保存票据 localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项 → {TOKEN_FILE}")
|
||||
except Exception as e:
|
||||
_log(f"保存 storage 票据失败(不影响 Cookies):{e}", "WARN")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
"""读取落盘 Cookies;仅保留 37du.co 域(钉钉域 cookie 无需复用),供 requests 构建会话。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
except Exception as e:
|
||||
_log(f"读取 Cookies 文件失败:{e}", "WARN")
|
||||
return None
|
||||
return [c for c in (cookies or []) if '37du.co' in (c.get('domain') or '')] or None
|
||||
|
||||
|
||||
# ================== 有效 Cookie 头捕获(requests 复放的权威来源) ==================
|
||||
def _load_header():
|
||||
"""读取落盘的有效 Cookie 头(浏览器实际发送内容)。"""
|
||||
if not os.path.exists(COOKIE_HEADER_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(COOKIE_HEADER_FILE, encoding='utf-8') as f:
|
||||
return f.read().strip() or None
|
||||
except Exception as e:
|
||||
_log(f"读取有效 Cookie 头失败:{e}", "WARN")
|
||||
return None
|
||||
|
||||
|
||||
def _header_from_json():
|
||||
"""按 cookies.json 原始顺序拼接 Cookie 头,保留同名重复项(轮换期并存的两个 x-token)。
|
||||
|
||||
不能走 session.cookies.set:requests 的 CookieJar 按 (domain, path, name) 去重,
|
||||
后写覆盖先写,会把新的 x-token 换成旧的 → 服务端取到作废 token 直接 401。"""
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return None
|
||||
return '; '.join(f'{c["name"]}={c["value"]}' for c in cookies if c.get('name'))
|
||||
|
||||
|
||||
def _verify_header(raw):
|
||||
"""端到端校验:用待落盘的 Cookie 头真实发一次 requests 请求。
|
||||
|
||||
浏览器内校验通过 ≠ requests 侧可用(同名 cookie 顺序/去重规则不同),
|
||||
只有这张头在 requests 里真能换到 S0,才允许落盘。"""
|
||||
try:
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": SITE_URL,
|
||||
"Cookie": raw,
|
||||
})
|
||||
r = s.get(VALIDATE_URL, timeout=15)
|
||||
if r.status_code != 200:
|
||||
return False
|
||||
return r.json().get('code') == 'S0'
|
||||
except Exception as e:
|
||||
_log(f"Cookie 头端到端校验异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _save_effective_header(page):
|
||||
"""页面内发起一次 /membership/main/user 请求,捕获浏览器实际发送的完整 Cookie 头,
|
||||
经「浏览器内 code=S0」+「requests 端到端 code=S0」双重校验后原子落盘。
|
||||
|
||||
为什么不用 cookie 键值对复放:本站 x-token 会轮换且同名 cookie 在浏览器与
|
||||
requests jar 中的去重/顺序规则不一致,实测 requests 按键值复放会拿到已作废的
|
||||
旧 x-token 导致 401;原样复刻浏览器发送的 Cookie 头(含同名条目与顺序)则与
|
||||
浏览器行为完全一致。"""
|
||||
try:
|
||||
page.listen.start('main/user')
|
||||
page.run_js("fetch('/membership/main/user', {headers:{'Accept':'application/json'}})")
|
||||
p = page.listen.wait(timeout=10)
|
||||
page.listen.stop()
|
||||
if not p:
|
||||
_log("未捕获到浏览器验证请求,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
raw = None
|
||||
for k, v in (p.request.headers or {}).items():
|
||||
if k.lower() == 'cookie':
|
||||
raw = v
|
||||
if not raw:
|
||||
_log("验证请求无 Cookie 头,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
try:
|
||||
data = p.response.body if isinstance(p.response.body, dict) else json.loads(str(p.response.body))
|
||||
except Exception:
|
||||
data = {}
|
||||
if not (isinstance(data, dict) and data.get('code') == 'S0'):
|
||||
_log(f"捕获的 Cookie 头校验未通过:{str(data)[:120]}", "WARN")
|
||||
return False
|
||||
if not _verify_header(raw):
|
||||
_log("捕获的 Cookie 头在 requests 侧校验未通过,不覆盖已有快照", "WARN")
|
||||
return False
|
||||
_atomic_write(COOKIE_HEADER_FILE, raw)
|
||||
_log(f"已保存有效 Cookie 头(浏览器 + requests 双校验 S0)→ {COOKIE_HEADER_FILE}")
|
||||
return True
|
||||
except Exception as e:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
_log(f"捕获有效 Cookie 头异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _repair_header_from_json():
|
||||
"""Cookie 头文件失效/损坏时的自愈:用 cookies.json 保序重建并端到端校验,成功则回写。
|
||||
|
||||
典型场景:并发写坏、历史版本把同名 x-token 去重过、或 header 文件被误删。"""
|
||||
raw = _header_from_json()
|
||||
if not raw or not _verify_header(raw):
|
||||
return False
|
||||
if _load_header() != raw:
|
||||
_atomic_write(COOKIE_HEADER_FILE, raw)
|
||||
_log("已用 cookies.json 重建有效 Cookie 头并回写")
|
||||
return True
|
||||
|
||||
|
||||
# ================== 纯 API 校验与业务会话(免开浏览器) ==================
|
||||
def build_session():
|
||||
"""构建可复用登录态的 requests.Session,供业务脚本直接发请求。
|
||||
|
||||
优先用落盘的有效 Cookie 头(浏览器实测发送内容原样复刻,最可靠);
|
||||
无有效头时按 cookies.json 原始顺序重建(同样保留同名 x-token,不做去重)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": SITE_URL,
|
||||
})
|
||||
raw = _load_header()
|
||||
if not raw:
|
||||
raw = _header_from_json()
|
||||
if raw:
|
||||
_log("Cookie 头文件缺失,已按 cookies.json 原始顺序重建", "WARN")
|
||||
if not raw:
|
||||
return None
|
||||
session.headers['Cookie'] = raw
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid():
|
||||
"""API 轻量校验登录态:GET /membership/main/user 返回 code=S0 视为有效。
|
||||
被重定向回登录页(返回 HTML)或非成功码均视为失效。"""
|
||||
session = build_session()
|
||||
if session is None:
|
||||
return False
|
||||
try:
|
||||
resp = session.get(VALIDATE_URL, timeout=15)
|
||||
except Exception as e:
|
||||
_log(f"API 校验登录态异常:{e}")
|
||||
return False
|
||||
if resp.status_code != 200:
|
||||
_log(f"API 校验登录态状态码异常:{resp.status_code}")
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return False
|
||||
if data.get("success") and data.get("code") == "S0":
|
||||
return True
|
||||
_log(f"API 校验返回非成功码:{str(data)[:200]}")
|
||||
return False
|
||||
|
||||
|
||||
def keep_alive():
|
||||
"""轻量保活:一次 API 请求刷新服务端会话的空闲计时(会话为滑动过期)。
|
||||
|
||||
本站所有 cookie 均为会话级,服务端会话空闲超时即作废(实测 Tomcat 默认 30 分钟)。
|
||||
相邻任务间隔较长时(如定时任务),调用本函数可续命,避免每次都要重新扫码。
|
||||
返回 True 表示会话仍有效。"""
|
||||
return is_session_valid()
|
||||
|
||||
|
||||
def save_from_page(page):
|
||||
"""登录态已由浏览器建立时,把 cookies 与有效 Cookie 头同步落盘,供 requests 复用。
|
||||
|
||||
顺序与 _attempt 一致:先 cookies.json,再抓有效 Cookie 头;抓取失败用 json 兜底重建,
|
||||
保证「浏览器已登录」与「requests 可用」不会分叉。返回同步后 requests 侧是否可用。"""
|
||||
_save_login_state(page)
|
||||
if not _save_effective_header(page):
|
||||
_repair_header_from_json()
|
||||
ok = is_session_valid()
|
||||
if ok:
|
||||
_log("登录态已同步落盘(requests 侧校验 S0 通过)")
|
||||
else:
|
||||
_log("登录态同步后 requests 侧仍不可用", "WARN")
|
||||
return ok
|
||||
|
||||
|
||||
# ================== 登录态复用校验 ==================
|
||||
def _api_ok_in_browser(page):
|
||||
"""页面内 fetch 调 /membership/main/user 确定性校验会话(code=S0 即有效)。
|
||||
不依赖 URL/标题猜测,杜绝路由守卫延迟导致的假阳性。"""
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
return fetch('/membership/main/user', {headers: {'Accept': 'application/json'}})
|
||||
.then(r => r.status + ':' + r.text())
|
||||
.catch(e => 'ERR:' + e);
|
||||
''')
|
||||
return bool(raw) and str(raw).startswith('200:') and '"code":"S0"' in str(raw)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_api_ok(page, seconds):
|
||||
"""轮询等待页面内 API 校验通过(覆盖 SPA 首屏加载与静默重登耗时)。"""
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if _api_ok_in_browser(page):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _check_reuse(page):
|
||||
"""尝试复用浏览器 profile 里上一次残留的会话,返回是否成功。
|
||||
|
||||
走到这里说明落盘快照已经过纯 API 校验且失败(服务端会话已作废),因此**不再注入
|
||||
快照 Cookie**:注入既救不活作废票据,还可能把 profile 里仍有效的会话覆盖成作废值,
|
||||
这正是之前「偶尔莫名掉线」的隐患来源。快照可用时 ensure_login 的①分支早已免开
|
||||
浏览器返回,不会进到这里。
|
||||
|
||||
唯一有价值的是 profile 自身残留会话:Chrome 异常退出会保留会话级 cookie;若钉钉
|
||||
会话同时存活,SPA 会自动静默重登。这里给一个小窗口观察,无效立刻转扫码。"""
|
||||
page.get(SITE_URL)
|
||||
if _wait_api_ok(page, PROFILE_REUSE_WAIT):
|
||||
_log("浏览器 profile 自身会话有效,直接续用")
|
||||
return True
|
||||
_log("浏览器 profile 无有效会话(落盘 Cookie 快照已在服务端失效)", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 扫码等待 ==================
|
||||
def _wait_scan(page, wait_scan):
|
||||
"""等待登录完成(hash 离开 #/login 即成功)。
|
||||
浏览器 profile 内钉钉长效 cookie(stayLogin 等)有效时会静默调
|
||||
/membership/dingtalkLogin 自动重登、无需扫码;仅钉钉会话也失效时才需人工扫码。"""
|
||||
_log("等待登录完成(刚扫码过会自动重登;否则请在窗口内扫码)……")
|
||||
deadline = time.time() + wait_scan
|
||||
hinted = False
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
if not _is_login_page(page.url):
|
||||
time.sleep(2) # 让 SPA 完成跳转与 token 写入
|
||||
return True
|
||||
remaining = int(deadline - time.time())
|
||||
if not hinted and remaining <= wait_scan - 60:
|
||||
_log("仍未检测到扫码登录,请确认已用钉钉 App 扫码并点击确认……")
|
||||
hinted = True
|
||||
return False
|
||||
|
||||
|
||||
# ================== 单轮登录尝试 ==================
|
||||
def _attempt(force, headless, wait_scan):
|
||||
"""一轮完整流程:开浏览器 → 未 force 先尝试复用 → 失效则等待扫码。"""
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录:浏览器层也保留登录态,与 cookies 落盘双保险
|
||||
_ensure_dir(BROWSER_PROFILE_DIR)
|
||||
co.set_user_data_path(BROWSER_PROFILE_DIR)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not force and _check_reuse(page):
|
||||
# 静默重登可能已在浏览器内刷新会话,等首屏请求结束后同步文件快照,
|
||||
# 否则 requests 侧(build_session)会一直拿到过期的旧快照。
|
||||
time.sleep(SETTLE_WAIT)
|
||||
save_from_page(page)
|
||||
return True, "复用缓存登录态", False
|
||||
_log("登录态失效或不存在,打开官方登录页等待扫码……")
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if _wait_scan(page, wait_scan):
|
||||
_log(f"登录成功 → {page.url}")
|
||||
time.sleep(SETTLE_WAIT) # 首屏请求(menu/permissions/dict 等)结束后再抓,避免轮换前快照
|
||||
save_from_page(page)
|
||||
return True, "登录成功", True
|
||||
_log(f"等待超时({wait_scan}s 内未检测到扫码登录)", "ERROR")
|
||||
return False, "扫码登录超时(未检测到登录成功)", True
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ================== 主入口 ==================
|
||||
def ensure_login(force=False, headless=None, wait_scan=None):
|
||||
"""确保存在有效的 CRM 登录态并落盘票据(钉钉扫码,人工在场)。
|
||||
|
||||
参数:
|
||||
force True 跳过缓存复用直接弹登录页扫码
|
||||
headless 是否无头(扫码场景应保持可见,默认 False)
|
||||
wait_scan 等待扫码超时秒数,默认 SCAN_WAIT
|
||||
|
||||
返回 JSON 安全 dict:{success, cookie_path, token_path, message, relogin}
|
||||
"""
|
||||
global _scan_attempted, _scan_failed_msg
|
||||
|
||||
headless = HEADLESS if headless is None else bool(headless)
|
||||
wait_scan = SCAN_WAIT if wait_scan is None else int(wait_scan)
|
||||
|
||||
# ①纯 API 校验优先:cookies 有效时全程免开浏览器(服务端滑动会话 30 分钟内均可用)
|
||||
if not force:
|
||||
if is_session_valid():
|
||||
_log("已通过缓存的 Cookies 复用 CRM 登录态(API 校验)")
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
# ①b Cookie 头文件损坏/同名项顺序错、而 cookies.json 仍完好时自愈,避免白弹一次扫码
|
||||
if _repair_header_from_json():
|
||||
_log("已用 cookies.json 重建 Cookie 头,复用 CRM 登录态")
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": "复用缓存登录态(重建 Cookie 头)", "relogin": False}
|
||||
|
||||
# ②本次运行已弹过扫码窗口:不再重复弹,直接快速失败(避免多张报表各挂 300 秒)
|
||||
if _scan_attempted:
|
||||
msg = _scan_failed_msg or "本次运行已尝试过扫码登录,登录态仍失效;请重新运行任务并完成扫码"
|
||||
_log(msg, "WARN")
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": msg, "relogin": False}
|
||||
_scan_attempted = True
|
||||
|
||||
# ③开浏览器:profile 层复用兜底,失效则扫码;扫码超时属人工未完成不自动重开
|
||||
last_msg = ""
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
try:
|
||||
ok, msg, relogin = _attempt(force, headless, wait_scan)
|
||||
if not ok:
|
||||
_scan_failed_msg = msg
|
||||
return {"success": ok, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": msg, "relogin": relogin}
|
||||
except Exception as e:
|
||||
last_msg = f"登录过程异常:{e}"
|
||||
_log(f"第 {attempt}/{RETRY_MAX} 次异常:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
_scan_failed_msg = last_msg or "登录失败"
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": _scan_failed_msg, "relogin": False}
|
||||
|
||||
|
||||
# 兼容别名:crm_login(...) 与 ensure_login 同参同返回
|
||||
crm_login = ensure_login
|
||||
|
||||
|
||||
def main(force=True):
|
||||
"""影刀自定义指令入口;独立运行 python crm_login.py 等价 main(force=True)。"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "token_path": TOKEN_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
Reference in New Issue
Block a user