feat(libs): 新增 crm_sdk CRM 接口封装(0.3.3)
账号密码登录(验证码 OCR 自动识别)优先、钉钉扫码兜底;登录态 Cookie 保序复用与落盘、JSON 请求与 S0 信封校验、分页、授权品牌门店树索引。
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
# crm_sdk · 37du CRM 接口 SDK
|
||||
|
||||
37du CRM(`crm.37du.co`)接口封装。**纯运行库**:没有独立执行入口,只能被插件调用,
|
||||
通过 `plugin.json` 的 `requires.sdks` 下发挂载。
|
||||
|
||||
## 定位
|
||||
|
||||
| 归 SDK | 归插件 |
|
||||
|---|---|
|
||||
| 登录态复用/落盘、Cookie 头保序自愈 | 什么时候要求重新登录、弹窗提示文案 |
|
||||
| `code=S0` 信封校验、重试、分页、下载 | 导出哪些报表、列名映射、落盘目录 |
|
||||
| 授权品牌-门店树、门店名/ID 索引 | 门店归属业务规则、对账口径 |
|
||||
|
||||
## 安装
|
||||
|
||||
正常由执行机按 `requires.sdks` 自动下载挂载;本地开发可:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe tools\sdk_pack.py --sdk libs\crm_sdk --install
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
```python
|
||||
from crm_sdk import CrmClient, auth, stores
|
||||
|
||||
# 1) 登录态:缓存有效时零请求;失效时用账号密码自动登录(验证码 OCR),全程无人值守
|
||||
result = auth.ensure_login(log=ctx.log)
|
||||
if not result["success"]:
|
||||
raise RuntimeError(result["message"])
|
||||
|
||||
# 2) 客户端:宿主已注入会话时用 ctx.get_session("crm")
|
||||
client = CrmClient(auth.build_session(), log=ctx.log)
|
||||
|
||||
# 3) 授权品牌-门店树(一次请求,多次查询)
|
||||
cat = stores.Catalog.load(client)
|
||||
cat.brands # ['金色印象', '金色春天', '康多巴巴', '金色湖畔']
|
||||
cat.brand_of("北城天街CEO会馆") # '金色印象'
|
||||
cat.shop_id("北城天街CEO会馆") # '10084'
|
||||
cat.names("金色春天") # ['广厦经典SPA会馆', '黄泥磅SPA会馆', '石油路SPA会馆']
|
||||
```
|
||||
|
||||
### 凭证配置(账号密码登录)
|
||||
|
||||
二选一,**环境变量优先**:
|
||||
|
||||
```powershell
|
||||
# ① 环境变量(执行机按账号注入时用)
|
||||
$env:CRM_USERNAME = "登录名"
|
||||
$env:CRM_PASSWORD = "密码"
|
||||
```
|
||||
|
||||
```json
|
||||
// ② 凭证文件:%LOCALAPPDATA%\37duAutomation\.sessions\<账号>\crm_credentials.json
|
||||
{ "username": "登录名", "password": "密码" }
|
||||
```
|
||||
|
||||
两者都没有时 `ensure_login` 直接跳过密码登录、回退到钉钉扫码兜底;
|
||||
不想让它弹浏览器就显式调 `auth.login_by_password()`,它只做纯 API 登录。
|
||||
|
||||
### 插件里推荐写法
|
||||
|
||||
```python
|
||||
def run(self, fields, ctx):
|
||||
client = CrmClient(ctx.get_session("crm"), log=ctx.log)
|
||||
cat = stores.Catalog.load(client)
|
||||
...
|
||||
```
|
||||
|
||||
## 接口
|
||||
|
||||
| 入口 | 说明 |
|
||||
|---|---|
|
||||
| `auth.ensure_login()` | 登录总入口:缓存复用 → 账号密码登录 → 钉钉扫码兜底 |
|
||||
| `auth.login_by_password()` | **账号密码纯 API 登录**:取验证码 → ddddocr 识别 → 提交 → 落盘 |
|
||||
| `auth.has_credentials()` | 是否已配置账号密码(决定走密码登录还是扫码) |
|
||||
| `auth.build_session()` | 用落盘登录态构造 `requests.Session`(纯 API,不开浏览器) |
|
||||
| `auth.is_session_valid()` | `GET /membership/main/user` 返回 `S0` 即有效 |
|
||||
| `auth.save_from_page(page)` | 浏览器已登录时同步落盘(插件自管浏览器时用) |
|
||||
| `captcha.recognize(png)` | 验证码识别(ddddocr,多图变体取最佳),返回小写 4 位 |
|
||||
| `captcha.recognize_data_url(str)` | 直接识别 `data:image/png;base64,...` |
|
||||
| `CrmClient.call()` | 请求 + 校验信封,直接返回 `data` |
|
||||
| `CrmClient.paginate()` | 通用分页 `fetch_page(page_no, page_size) -> (rows, has_more)` |
|
||||
| `CrmClient.download()` | 大报表下载落盘,返回绝对路径(自动用响应头里的中文文件名) |
|
||||
| `reports.names()` | 全部报表 key(38 个) |
|
||||
| `reports.query()` | **先查询**:用导出将用的同批参数查一页,拿 `total` 与样本 |
|
||||
| `reports.list_all()` | 按页取全量数据(兼容分页型与直返数组型) |
|
||||
| `reports.list_page()` | 取一页,返回 `(rows, has_more)` |
|
||||
| `reports.export()` | 导出报表 Excel 到本地,返回绝对路径 |
|
||||
| `stores.tree()` | 原始品牌-门店树(`getAuthorizedBrandShops`) |
|
||||
| `stores.brands()` | **授权**品牌名列表 |
|
||||
| `stores.shops(brand=)` | 扁平门店条目 `{brand, brand_id, name, shop_id}` |
|
||||
| `stores.Catalog` | 内存索引:`brand_of` / `shop_id` / `names` / `of_brand` / `duplicates` |
|
||||
| `stores.all_brands()` | **全部品牌**(`getAllBrand`,含未授权的)`{brand, brand_id}` |
|
||||
| `stores.all_brand_names()` | 全部品牌名列表 |
|
||||
| `stores.brand_id(name)` | 品牌名 → 品牌 ID(查 `getAllBrand`) |
|
||||
| `stores.unauthorized_brands()` | 有品牌但本账号无授权门店的品牌(排查用) |
|
||||
|
||||
## 报表(0.3.0 新增)
|
||||
|
||||
接口清单不是猜的,是从前端 `src/api/setting.ts` 的声明式接口表里还原的:
|
||||
**38 组 `list` / `export` 成对**,覆盖菜单「报表统计」下全部页面。
|
||||
|
||||
```python
|
||||
from crm_sdk import CrmClient, auth, reports
|
||||
|
||||
client = CrmClient(auth.build_session())
|
||||
|
||||
rows = reports.list_all(client, "unionPay", reportDate="2026-11-25")
|
||||
path = reports.export(client, "unionPay", reportDate="2026-11-25",
|
||||
save_dir=r"D:\报表") # → 支付数据2026-11-25~2026-11-25.xlsx
|
||||
```
|
||||
|
||||
### 两种响应形态(实测,SDK 已兼容)
|
||||
|
||||
| 形态 | 例子 | 分页 |
|
||||
|---|---|---|
|
||||
| `{data: {list: [...], total: 120}}` | `unionPay` / `groupPay` | 按 `total` 翻页 |
|
||||
| `{data: [...]}` | `posPay` / `debitCard` | 服务端一次返全量,只请求一次 |
|
||||
|
||||
### 常用 key
|
||||
|
||||
| 分类 | key |
|
||||
|---|---|
|
||||
| 支付账单 | `groupPay` `posPay` `cashPay` `thirdPayShop` `thirdPayHeadquarters` `unionPay` `groupData` `unionPayRefund` `employeeUnionPay` |
|
||||
| 储值卡 | `debitCard` `debitCardConsume` `debitCardBalance` `debitCardDeposit` `debitCardAccountBook` `debitCardMemberBalance` `depositData` `abnormalDeposit` `debitCardAbnormal` `discountCardAbnormal` `discountCardRecord` `consumeOrderDeposit` |
|
||||
| 员工业绩 | `comprehensivePerformance` `employeeWork` `employeeWorkRank` `employeeSpecialWork` `consumeSubjectCount` |
|
||||
| 霸王餐 | `overlordOrderDeposit` `overlordOrderConsume` `overlordOrderBalance` |
|
||||
| 小程序 | `miniProgramOrder` `miniProgramPay` `overnightSettlement` |
|
||||
| 第三方 | `taobaoTicket` `weimengValidate` `weimengValidateSum` `weimengFundsSum` |
|
||||
| 会员券 | `memberCoupon` |
|
||||
| 其它 | `orderSubjectAddition` |
|
||||
|
||||
完整清单与中文标题:`reports.names()` / `reports.titles()`。
|
||||
|
||||
### 先查询再导出(重要)
|
||||
|
||||
有的报表**不传条件会导出全表**——实测 `debitCardMemberBalance`(储值余额)
|
||||
无参数直接导出 **70,200 行**。所以导出支持前置查询闸门:
|
||||
|
||||
```python
|
||||
# 先查一眼:总量、样本、权限都在这一步暴露
|
||||
info = reports.query(client, "debitCardMemberBalance", brandId="1", shopId="10084")
|
||||
info["total"] # 70200 或具体门店的行数
|
||||
|
||||
# 带闸门导出:超量直接拒绝,不会白下几十兆
|
||||
path = reports.export(client, "unionPay", reportDate="2026-11-25",
|
||||
query_first=True, max_rows=5000,
|
||||
save_dir=r"D:\报表")
|
||||
```
|
||||
|
||||
`query_first=True` 会**用同一批参数**先打一次 list,`total==0` 抛 `ConfigError`
|
||||
(不产出空文件),超过 `max_rows` 也抛 `ConfigError`。
|
||||
|
||||
### 接口差异(踩过)
|
||||
|
||||
| 差异 | 说明 |
|
||||
|---|---|
|
||||
| 请求方法 | 绝大多数 list 是 GET,**`memberCoupon` 只接受 POST**(GET 直接 `E1004 Request method 'GET' is not supported`),SDK 按报表配置走 |
|
||||
| `total` 类型 | 后端可能返回数字或字符串,SDK 已统一转 int |
|
||||
| 权限 | `memberCoupon` 对本账号返回 **HTTP 403 未授权**(不是登录失效),SDK 现在抛 `ApiError(code=E403)`,不会误触发重登 |
|
||||
| 无参数导出 | 见上,可能导出全表,务必用 `query_first` + `max_rows` |
|
||||
|
||||
- 返回的是真 Excel(`application/vnd.ms-excel`,文件头 `PK`)
|
||||
- 文件名在 `Content-Disposition` 里且是 **URL 编码的中文**,SDK 已解码还原;
|
||||
不传 `filename` 就用服务端原名
|
||||
- 服务端把错误也当 HTTP 200 返回 JSON 信封,`export()` 会识别并抛 `ApiError`,
|
||||
不会把错误 JSON 存成 xlsx
|
||||
|
||||
### 验证记录(2026-11-25,真实登录态)
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| `unionPay/list`(分页型) | S0,`total=80`,首页 5 行 |
|
||||
| `posPay/list`(数组型) | S0,1 行 |
|
||||
| `list_all(unionPay, page_size=20)` | 翻 4 页取到 80 行,0.4s |
|
||||
| `export(unionPay)` | 26,599 字节 xlsx,文件名 `支付数据2026-11-25~2026-11-25.xlsx` |
|
||||
| `export(groupPay)` | 4,934 字节 xlsx,文件名 `团购支付统计2026-11-25.xlsx` |
|
||||
|
||||
> 其余 34 个接口未逐个打(避免无意义请求量),机制同源:同一张声明式接口表、
|
||||
> 同一套信封与下载逻辑。插件首次用到某个报表时若报错,大概率是**查询参数名**差异,
|
||||
> 按该页面 `searchFromList` 里的 `prop` 补参数即可。
|
||||
|
||||
## 坑位(都是实测踩出来的)
|
||||
|
||||
0. **两个品牌接口别混用**:`getAllBrand` 是**扁平**的 `[{value,label}]`(系统里全部品牌),
|
||||
`getAuthorizedBrandShops` 是**两层树**(只有本账号授权的品牌→门店)。
|
||||
做报表筛选要用后者的门店 ID;只做品牌名↔ID 反查用前者更快。
|
||||
实测本账号:4 个品牌全部授权、81 家门店。
|
||||
|
||||
1. **Cookie 头要原样复放**:CRM 的 `x-token` 在轮换期并存新旧两条同名 Cookie,
|
||||
`requests` 的 CookieJar 按 `(domain, path, name)` 去重会把新的盖成旧的 → 401。
|
||||
一律走 `session_from_header()`,不要用 `cookies.set()` 逐条塞。
|
||||
2. **抓 Cookie 要等首屏结束**:登录成功后立刻抓会拿到轮换前的作废票据,默认
|
||||
`LOGIN_SETTLE=8` 秒,且落盘前做「浏览器 S0 + requests 端到端 S0」双校验。
|
||||
3. **profile 残留会话优先于快照**:快照已失效时不要再把它注入浏览器,否则会把
|
||||
profile 里仍有效的会话覆盖成作废值。
|
||||
4. **`(OLD)` 旧店**:康多巴巴下的 `石碾盘CEO会馆(OLD)`、`洋河北路CEO会馆(OLD)`
|
||||
是搬迁前旧店,按门店名做匹配时必须显式排除,否则会静默错配。
|
||||
5. **会话按账号隔离**:执行机 `.sessions/<账号>/`,SDK 读 `PLATFORM_ACCOUNT` 环境变量
|
||||
对齐;无账号时回落共享目录(兼容旧文件)。
|
||||
|
||||
### 账号密码登录(0.2.0 新增)实测规则
|
||||
|
||||
6. **一个会话只能提交一次登录**:验证码错一次后该会话永久返回 `E1006 重复提交`,
|
||||
所以每次尝试都必须换新 `Session`——复用会话只会把重试次数耗光。
|
||||
7. **验证码不区分大小写**:图上 `cK7r`,提交 `ck7r` 一样通过;识别结果统一转小写。
|
||||
8. **单次识别率约 80%**(20 次采样即停,未做批量压测):失败多为 ddddocr 把相邻字符
|
||||
粘成 3 位,`captcha.recognize()` 已内置「原图 + 放大灰度」多变体取最佳,并按位数
|
||||
校验;剩余概率靠有限次重试兜住(3 次 ≈ 99%)。
|
||||
9. **不要批量刷验证码**:连续失败登录是风控特征(账号枚举 + 撞库),SDK 刻意把
|
||||
`PASSWORD_LOGIN_ATTEMPTS` 压到 3 并加 `PASSWORD_RETRY_DELAY` 间隔。要评估识别率
|
||||
请用离线样本,不要打线上接口。
|
||||
10. **登录失败要区分类型**:`E10001 用户不存在` / 密码错误属于终态,重试无意义且会
|
||||
累计失败次数触发锁定;只有验证码类错误(`E50002`/`E50004`/`E1006`)才换会话重试。
|
||||
|
||||
## 发版
|
||||
|
||||
三处版本号保持一致(`sdk.json` / `crm_sdk.__version__` / `pyproject.toml`),流程见
|
||||
`.skills/37du-SDK-Deploy/SKILL.md`:`sdk_pack --install` → 兼容预检 → `sdk-publish --prod`。
|
||||
@@ -0,0 +1,453 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "crm_sdk",
|
||||
"version": "0.3.3",
|
||||
"modules": {
|
||||
"crm_sdk": {
|
||||
"exports": [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CRM_BASE_URL",
|
||||
"Catalog",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmClient",
|
||||
"CrmError",
|
||||
"SessionExpiredError",
|
||||
"SessionLike",
|
||||
"USER_URL",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"auth",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"build_session",
|
||||
"captcha",
|
||||
"client",
|
||||
"config",
|
||||
"cookie_header_from_cookies",
|
||||
"cookies_file",
|
||||
"ensure_login",
|
||||
"errors",
|
||||
"has_credentials",
|
||||
"index",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reports",
|
||||
"session",
|
||||
"session_from_cookies",
|
||||
"session_from_header",
|
||||
"shops",
|
||||
"stores",
|
||||
"unauthorized_brands",
|
||||
"tree",
|
||||
"__version__"
|
||||
],
|
||||
"all": [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CRM_BASE_URL",
|
||||
"Catalog",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmClient",
|
||||
"CrmError",
|
||||
"SessionExpiredError",
|
||||
"SessionLike",
|
||||
"USER_URL",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"auth",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"build_session",
|
||||
"captcha",
|
||||
"client",
|
||||
"config",
|
||||
"cookie_header_from_cookies",
|
||||
"cookies_file",
|
||||
"ensure_login",
|
||||
"errors",
|
||||
"has_credentials",
|
||||
"index",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reports",
|
||||
"session",
|
||||
"session_from_cookies",
|
||||
"session_from_header",
|
||||
"shops",
|
||||
"stores",
|
||||
"unauthorized_brands",
|
||||
"tree",
|
||||
"__version__"
|
||||
],
|
||||
"signatures": {
|
||||
"ApiError": "(message: 'str', *, code: 'str' = '', payload: 'Optional[Any]' = None) -> 'None'",
|
||||
"Catalog": "(nodes: 'Iterable[dict]') -> 'None'",
|
||||
"CrmClient": "(session: 'SessionLike', *, timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[LOGGER]' = None) -> 'None'",
|
||||
"SessionLike": "(*args, **kwargs)",
|
||||
"all_brand_names": "(client) -> 'List[str]'",
|
||||
"all_brands": "(client) -> 'List[Dict[str, str]]'",
|
||||
"brand_id": "(client, brand_name: 'str') -> 'str'",
|
||||
"brand_of": "(client, shop_name: 'str') -> 'str'",
|
||||
"brands": "(client) -> 'List[str]'",
|
||||
"build_session": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None, user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'Optional[requests.Session]'",
|
||||
"cookie_header_from_cookies": "(path: 'str' = '', *, account: 'str' = '') -> 'str'",
|
||||
"cookies_file": "(account: 'str' = '') -> 'str'",
|
||||
"ensure_login": "(*, account: 'str' = '', force: 'bool' = False, headless: 'Optional[bool]' = None, wait_scan: 'Optional[float]' = None, prefer_password: 'bool' = True, log: 'Optional[LOGGER]' = None) -> 'dict'",
|
||||
"has_credentials": "(account: 'str' = '') -> 'bool'",
|
||||
"index": "(client, *, brand: 'str' = '') -> 'Dict[str, Dict[str, str]]'",
|
||||
"is_session_valid": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None) -> 'bool'",
|
||||
"keep_alive": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None) -> 'bool'",
|
||||
"login_by_password": "(*, username: 'Optional[str]' = None, password: 'Optional[str]' = None, account: 'str' = '', attempts: 'Optional[int]' = None, log: 'Optional[LOGGER]' = None) -> 'dict'",
|
||||
"session_from_cookies": "(path: 'str' = '', *, account: 'str' = '', user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'requests.Session'",
|
||||
"session_from_header": "(header: 'str', *, user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'requests.Session'",
|
||||
"shops": "(client, *, brand: 'str' = '') -> 'List[Dict[str, str]]'",
|
||||
"unauthorized_brands": "(client) -> 'List[str]'",
|
||||
"tree": "(client) -> 'List[dict]'"
|
||||
}
|
||||
},
|
||||
"crm_sdk._selftest": {
|
||||
"exports": [
|
||||
"ApiError",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmClient",
|
||||
"SAMPLE_TREE",
|
||||
"SessionExpiredError",
|
||||
"annotations",
|
||||
"auth",
|
||||
"captcha",
|
||||
"config",
|
||||
"json",
|
||||
"main",
|
||||
"os",
|
||||
"reports",
|
||||
"session",
|
||||
"stores",
|
||||
"tempfile",
|
||||
"test_captcha",
|
||||
"test_catalog",
|
||||
"test_client_envelope",
|
||||
"test_cookie_header_order",
|
||||
"test_credentials",
|
||||
"test_empty_tree",
|
||||
"test_login_by_password",
|
||||
"test_paths",
|
||||
"test_reports"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"ApiError": "(message: 'str', *, code: 'str' = '', payload: 'Optional[Any]' = None) -> 'None'",
|
||||
"CrmClient": "(session: 'SessionLike', *, timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[LOGGER]' = None) -> 'None'",
|
||||
"main": "() -> 'int'",
|
||||
"test_captcha": "() -> 'None'",
|
||||
"test_catalog": "() -> 'None'",
|
||||
"test_client_envelope": "() -> 'None'",
|
||||
"test_cookie_header_order": "() -> 'None'",
|
||||
"test_credentials": "() -> 'None'",
|
||||
"test_empty_tree": "() -> 'None'",
|
||||
"test_login_by_password": "() -> 'None'",
|
||||
"test_paths": "() -> 'None'",
|
||||
"test_reports": "() -> 'None'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.auth": {
|
||||
"exports": [
|
||||
"AuthError",
|
||||
"build_session",
|
||||
"ensure_login",
|
||||
"has_credentials",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reset_scan_gate",
|
||||
"save_from_page"
|
||||
],
|
||||
"all": [
|
||||
"AuthError",
|
||||
"build_session",
|
||||
"ensure_login",
|
||||
"has_credentials",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reset_scan_gate",
|
||||
"save_from_page"
|
||||
],
|
||||
"signatures": {
|
||||
"build_session": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None, user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'Optional[requests.Session]'",
|
||||
"ensure_login": "(*, account: 'str' = '', force: 'bool' = False, headless: 'Optional[bool]' = None, wait_scan: 'Optional[float]' = None, prefer_password: 'bool' = True, log: 'Optional[LOGGER]' = None) -> 'dict'",
|
||||
"has_credentials": "(account: 'str' = '') -> 'bool'",
|
||||
"is_session_valid": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None) -> 'bool'",
|
||||
"keep_alive": "(*, account: 'str' = '', log: 'Optional[LOGGER]' = None) -> 'bool'",
|
||||
"login_by_password": "(*, username: 'Optional[str]' = None, password: 'Optional[str]' = None, account: 'str' = '', attempts: 'Optional[int]' = None, log: 'Optional[LOGGER]' = None) -> 'dict'",
|
||||
"reset_scan_gate": "() -> 'None'",
|
||||
"save_from_page": "(page, *, account: 'str' = '', log: 'Optional[LOGGER]' = None) -> 'bool'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.captcha": {
|
||||
"exports": [
|
||||
"decode_data_url",
|
||||
"normalize",
|
||||
"recognize",
|
||||
"recognize_data_url"
|
||||
],
|
||||
"all": [
|
||||
"decode_data_url",
|
||||
"normalize",
|
||||
"recognize",
|
||||
"recognize_data_url"
|
||||
],
|
||||
"signatures": {
|
||||
"decode_data_url": "(text: 'str') -> 'bytes'",
|
||||
"normalize": "(text: 'str', *, length: 'int' = 4) -> 'str'",
|
||||
"recognize": "(png: 'bytes', *, length: 'int' = 4) -> 'str'",
|
||||
"recognize_data_url": "(text: 'str', *, length: 'int' = 4) -> 'str'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.client": {
|
||||
"exports": [
|
||||
"CrmClient"
|
||||
],
|
||||
"all": [
|
||||
"CrmClient"
|
||||
],
|
||||
"signatures": {
|
||||
"CrmClient": "(session: 'SessionLike', *, timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[LOGGER]' = None) -> 'None'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.config": {
|
||||
"exports": [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CAPTCHA_LENGTH",
|
||||
"CAPTCHA_URL",
|
||||
"CODE_CAPTCHA_EMPTY",
|
||||
"CODE_CAPTCHA_WRONG",
|
||||
"CODE_DUPLICATE_SUBMIT",
|
||||
"CODE_USER_NOT_FOUND",
|
||||
"COOKIE_DOMAIN_FILTER",
|
||||
"COOKIES_FILE",
|
||||
"CRM_BASE_URL",
|
||||
"CRM_DOMAIN",
|
||||
"CRM_LOGIN_URL",
|
||||
"CRM_PASSWORD",
|
||||
"CRM_SITE_URL",
|
||||
"CRM_USERNAME",
|
||||
"DEFAULT_TIMEOUT",
|
||||
"DOWNLOAD_TIMEOUT",
|
||||
"HEADLESS",
|
||||
"LOGIN_PAGE_KEYWORD",
|
||||
"LOGIN_SETTLE",
|
||||
"LOGIN_URL",
|
||||
"LOGOUT_URL",
|
||||
"MAX_ATTEMPTS",
|
||||
"MAX_PAGES",
|
||||
"MEMBERSHIP",
|
||||
"PASSWORD_LOGIN_ATTEMPTS",
|
||||
"PASSWORD_RETRY_DELAY",
|
||||
"PROFILE_REUSE_WAIT",
|
||||
"SCAN_WAIT",
|
||||
"SESSION_EXPIRED_CODES",
|
||||
"SUCCESS_CODE",
|
||||
"USER_AGENT",
|
||||
"USER_URL",
|
||||
"XHR_HEADERS",
|
||||
"app_data_dir",
|
||||
"browser_profile_dir",
|
||||
"cookie_header_file",
|
||||
"cookies_file",
|
||||
"credentials_file",
|
||||
"resolve_account",
|
||||
"sessions_dir",
|
||||
"token_file"
|
||||
],
|
||||
"all": [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CAPTCHA_LENGTH",
|
||||
"CAPTCHA_URL",
|
||||
"CODE_CAPTCHA_EMPTY",
|
||||
"CODE_CAPTCHA_WRONG",
|
||||
"CODE_DUPLICATE_SUBMIT",
|
||||
"CODE_USER_NOT_FOUND",
|
||||
"COOKIE_DOMAIN_FILTER",
|
||||
"COOKIES_FILE",
|
||||
"CRM_BASE_URL",
|
||||
"CRM_DOMAIN",
|
||||
"CRM_LOGIN_URL",
|
||||
"CRM_PASSWORD",
|
||||
"CRM_SITE_URL",
|
||||
"CRM_USERNAME",
|
||||
"DEFAULT_TIMEOUT",
|
||||
"DOWNLOAD_TIMEOUT",
|
||||
"HEADLESS",
|
||||
"LOGIN_PAGE_KEYWORD",
|
||||
"LOGIN_SETTLE",
|
||||
"LOGIN_URL",
|
||||
"LOGOUT_URL",
|
||||
"MAX_ATTEMPTS",
|
||||
"MAX_PAGES",
|
||||
"MEMBERSHIP",
|
||||
"PASSWORD_LOGIN_ATTEMPTS",
|
||||
"PASSWORD_RETRY_DELAY",
|
||||
"PROFILE_REUSE_WAIT",
|
||||
"SCAN_WAIT",
|
||||
"SESSION_EXPIRED_CODES",
|
||||
"SUCCESS_CODE",
|
||||
"USER_AGENT",
|
||||
"USER_URL",
|
||||
"XHR_HEADERS",
|
||||
"app_data_dir",
|
||||
"browser_profile_dir",
|
||||
"cookie_header_file",
|
||||
"cookies_file",
|
||||
"credentials_file",
|
||||
"resolve_account",
|
||||
"sessions_dir",
|
||||
"token_file"
|
||||
],
|
||||
"signatures": {
|
||||
"app_data_dir": "() -> 'str'",
|
||||
"browser_profile_dir": "(account: 'str' = '') -> 'str'",
|
||||
"cookie_header_file": "(account: 'str' = '') -> 'str'",
|
||||
"cookies_file": "(account: 'str' = '') -> 'str'",
|
||||
"credentials_file": "(account: 'str' = '') -> 'str'",
|
||||
"resolve_account": "(account: 'str' = '') -> 'str'",
|
||||
"sessions_dir": "(account: 'str' = '') -> 'str'",
|
||||
"token_file": "(account: 'str' = '') -> 'str'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.errors": {
|
||||
"exports": [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmError",
|
||||
"SessionExpiredError"
|
||||
],
|
||||
"all": [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmError",
|
||||
"SessionExpiredError"
|
||||
],
|
||||
"signatures": {
|
||||
"ApiError": "(message: 'str', *, code: 'str' = '', payload: 'Optional[Any]' = None) -> 'None'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.reports": {
|
||||
"exports": [
|
||||
"REPORTS",
|
||||
"export",
|
||||
"list_all",
|
||||
"list_page",
|
||||
"names",
|
||||
"query",
|
||||
"titles"
|
||||
],
|
||||
"all": [
|
||||
"REPORTS",
|
||||
"export",
|
||||
"list_all",
|
||||
"list_page",
|
||||
"names",
|
||||
"query",
|
||||
"titles"
|
||||
],
|
||||
"signatures": {
|
||||
"export": "(client, name: 'str', *, save_dir: 'str' = '', filename: 'str' = '', timeout: 'Optional[float]' = None, extra: 'str' = '', query_first: 'bool' = False, max_rows: 'Optional[int]' = None, **params) -> 'str'",
|
||||
"list_all": "(client, name: 'str', *, page_size: 'int' = 200, max_pages: 'int' = 200, sleep: 'float' = 0.2, **params) -> 'List[dict]'",
|
||||
"list_page": "(client, name: 'str', page_no: 'int' = 1, page_size: 'int' = 200, *, extra: 'str' = '', **params) -> 'Tuple[List[dict], bool]'",
|
||||
"names": "() -> 'List[str]'",
|
||||
"query": "(client, name: 'str', *, page_size: 'int' = 20, **params) -> 'dict'",
|
||||
"titles": "() -> 'Dict[str, str]'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.session": {
|
||||
"exports": [
|
||||
"SessionLike",
|
||||
"cookie_header_from_cookies",
|
||||
"looks_like_login_page",
|
||||
"read_cookie_header",
|
||||
"read_cookies",
|
||||
"resolve_account",
|
||||
"session_from_cookies",
|
||||
"session_from_header"
|
||||
],
|
||||
"all": [
|
||||
"SessionLike",
|
||||
"cookie_header_from_cookies",
|
||||
"looks_like_login_page",
|
||||
"read_cookie_header",
|
||||
"read_cookies",
|
||||
"resolve_account",
|
||||
"session_from_cookies",
|
||||
"session_from_header"
|
||||
],
|
||||
"signatures": {
|
||||
"SessionLike": "(*args, **kwargs)",
|
||||
"cookie_header_from_cookies": "(path: 'str' = '', *, account: 'str' = '') -> 'str'",
|
||||
"looks_like_login_page": "(text: 'Optional[str]') -> 'bool'",
|
||||
"read_cookie_header": "(path: 'str' = '', *, account: 'str' = '') -> 'Optional[str]'",
|
||||
"read_cookies": "(path: 'str' = '', *, account: 'str' = '', domain_filter: 'str' = '37du.co') -> 'List[dict]'",
|
||||
"resolve_account": "(account: 'str' = '') -> 'str'",
|
||||
"session_from_cookies": "(path: 'str' = '', *, account: 'str' = '', user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'requests.Session'",
|
||||
"session_from_header": "(header: 'str', *, user_agent: 'str' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') -> 'requests.Session'"
|
||||
}
|
||||
},
|
||||
"crm_sdk.stores": {
|
||||
"exports": [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"Catalog",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"index",
|
||||
"shops",
|
||||
"tree",
|
||||
"unauthorized_brands"
|
||||
],
|
||||
"all": [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"Catalog",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"index",
|
||||
"shops",
|
||||
"tree",
|
||||
"unauthorized_brands"
|
||||
],
|
||||
"signatures": {
|
||||
"Catalog": "(nodes: 'Iterable[dict]') -> 'None'",
|
||||
"all_brand_names": "(client) -> 'List[str]'",
|
||||
"all_brands": "(client) -> 'List[Dict[str, str]]'",
|
||||
"brand_id": "(client, brand_name: 'str') -> 'str'",
|
||||
"brand_of": "(client, shop_name: 'str') -> 'str'",
|
||||
"brands": "(client) -> 'List[str]'",
|
||||
"index": "(client, *, brand: 'str' = '') -> 'Dict[str, Dict[str, str]]'",
|
||||
"shops": "(client, *, brand: 'str' = '') -> 'List[Dict[str, str]]'",
|
||||
"tree": "(client) -> 'List[dict]'",
|
||||
"unauthorized_brands": "(client) -> 'List[str]'"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""crm_sdk · 37du CRM(crm.37du.co)接口 SDK(纯运行库,只能被调用)。
|
||||
|
||||
分工:**SDK 出接口,插件出业务**。这里封装登录态复用与落盘、``code=S0`` 信封校验、
|
||||
分页与下载、授权品牌门店树等接口事实;异常判定、门店归属业务规则、导出哪些报表、
|
||||
文案与落盘策略留在插件。
|
||||
|
||||
当前版本(0.3.3)覆盖:
|
||||
|
||||
========================== ==========================================================
|
||||
接口 入口
|
||||
========================== ==========================================================
|
||||
通用请求 / 信封 / 分页 / 下载 :class:`client.CrmClient`
|
||||
登录态(账号密码 OCR 优先,扫码兜底):mod:`auth`(``ensure_login`` / ``login_by_password``
|
||||
/ ``build_session`` / ``is_session_valid`` / ``save_from_page``)
|
||||
验证码识别(ddddocr) :mod:`captcha`(``recognize`` / ``recognize_data_url``)
|
||||
会话与 Cookie 保序 :mod:`session`(``session_from_header`` /
|
||||
``cookie_header_from_cookies``)
|
||||
授权品牌-门店树 :mod:`stores`(``tree`` / ``brands`` / ``shops`` /
|
||||
``Catalog``)
|
||||
========================== ==========================================================
|
||||
|
||||
典型用法::
|
||||
|
||||
from crm_sdk import CrmClient, auth, stores
|
||||
|
||||
auth.ensure_login(log=ctx.log) # 有凭证静默登录,无需人工
|
||||
client = CrmClient(auth.build_session(), log=ctx.log)
|
||||
cat = stores.Catalog.load(client) # 一次请求,多次查询
|
||||
cat.brand_of("北城天街CEO会馆") # '金色印象'
|
||||
|
||||
契约:不读命令行参数、不 ``sys.exit``、不 ``print``(用 ``log`` 回调)、
|
||||
不 ``close()`` 借来的 session;异常统一为 :class:`errors.CrmError` 子类。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.3.3"
|
||||
|
||||
from . import auth, captcha, client, config, errors, reports, session, stores
|
||||
from .auth import (build_session, ensure_login, has_credentials, is_session_valid,
|
||||
keep_alive, login_by_password)
|
||||
from .client import CrmClient
|
||||
from .config import BRAND_SHOPS_URL, CRM_BASE_URL, USER_URL, cookies_file
|
||||
from .errors import (ApiError, AuthError, CaptchaError, ConfigError, CrmError,
|
||||
SessionExpiredError)
|
||||
from .session import (SessionLike, cookie_header_from_cookies, session_from_cookies,
|
||||
session_from_header)
|
||||
from .stores import (Catalog, all_brand_names, all_brands, brand_id, brand_of,
|
||||
brands, index, shops, tree, unauthorized_brands)
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CRM_BASE_URL",
|
||||
"Catalog",
|
||||
"CaptchaError",
|
||||
"ConfigError",
|
||||
"CrmClient",
|
||||
"CrmError",
|
||||
"SessionExpiredError",
|
||||
"SessionLike",
|
||||
"USER_URL",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"auth",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"build_session",
|
||||
"captcha",
|
||||
"client",
|
||||
"config",
|
||||
"cookie_header_from_cookies",
|
||||
"cookies_file",
|
||||
"ensure_login",
|
||||
"errors",
|
||||
"has_credentials",
|
||||
"index",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reports",
|
||||
"session",
|
||||
"session_from_cookies",
|
||||
"session_from_header",
|
||||
"shops",
|
||||
"stores",
|
||||
"unauthorized_brands",
|
||||
"tree",
|
||||
"__version__",
|
||||
]
|
||||
@@ -0,0 +1,409 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""crm_sdk 离线自测:不联网、不登录、不开浏览器(``sdk_pack`` 安装后会自动跑)。
|
||||
|
||||
覆盖:版本一致性、路径按账号隔离、Cookie 头保序、``code=S0`` 信封、门店树索引。
|
||||
运行:``python -m crm_sdk._selftest``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from . import __version__, auth, captcha, config, reports, session, stores
|
||||
from .client import CrmClient
|
||||
from .errors import ApiError, CaptchaError, ConfigError, SessionExpiredError
|
||||
|
||||
_CHECKS = 0
|
||||
|
||||
|
||||
def _ok(cond, message: str) -> None:
|
||||
global _CHECKS
|
||||
_CHECKS += 1
|
||||
if not cond:
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def _eq(actual, expected, message: str) -> None:
|
||||
_ok(actual == expected, f"{message}(期望 {expected!r},实际 {actual!r})")
|
||||
|
||||
|
||||
def _raises(exc_type, fn, message: str) -> None:
|
||||
global _CHECKS
|
||||
_CHECKS += 1
|
||||
try:
|
||||
fn()
|
||||
except exc_type:
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise AssertionError(f"{message}(抛了 {type(exc).__name__}: {exc})") from None
|
||||
raise AssertionError(f"{message}(未抛异常)")
|
||||
|
||||
|
||||
# ==================== 假会话 / 假响应 ====================
|
||||
class _Resp:
|
||||
def __init__(self, payload=None, *, status: int = 200, text: str = "") -> None:
|
||||
self.status_code = status
|
||||
self._payload = payload
|
||||
self.text = text or json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
def json(self):
|
||||
if self._payload is None:
|
||||
raise ValueError("no json")
|
||||
return self._payload
|
||||
|
||||
|
||||
class _Session:
|
||||
def __init__(self, resp: _Resp) -> None:
|
||||
self.resp = resp
|
||||
self.headers = {}
|
||||
self.cookies = None
|
||||
self.calls = []
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
self.calls.append(("GET", url, kwargs))
|
||||
return self.resp
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
self.calls.append(("POST", url, kwargs))
|
||||
return self.resp
|
||||
|
||||
|
||||
class _StubClient:
|
||||
"""只实现 stores 需要的 ``call``。"""
|
||||
|
||||
def __init__(self, data) -> None:
|
||||
self.data = data
|
||||
self.calls = []
|
||||
|
||||
def call(self, method, url, **kwargs):
|
||||
self.calls.append((method, url, kwargs))
|
||||
return self.data
|
||||
|
||||
|
||||
SAMPLE_TREE = [
|
||||
{"label": "金色印象", "value": 10001, "children": [
|
||||
{"label": "北城天街CEO会馆", "value": 10084},
|
||||
{"label": "石碾盘CEO会馆", "value": 2010103},
|
||||
{"label": "黄泥磅行政会馆", "value": 10075},
|
||||
]},
|
||||
{"label": "金色春天", "value": 10002, "children": [
|
||||
{"label": "黄泥磅SPA会馆", "value": 10107},
|
||||
]},
|
||||
{"label": "康多巴巴", "value": 10003, "children": [
|
||||
{"label": "石碾盘CEO会馆(OLD)", "value": 10100},
|
||||
]},
|
||||
]
|
||||
|
||||
|
||||
# ==================== 用例 ====================
|
||||
def test_paths() -> None:
|
||||
root = config.app_data_dir()
|
||||
_ok(root.endswith("37duAutomation"), "运行数据根")
|
||||
_ok(config.cookies_file().endswith(os.path.join(".sessions", "crm_cookies.json")),
|
||||
"无账号时落共享会话目录")
|
||||
isolated = config.cookies_file("puddy")
|
||||
_ok(os.path.join(".sessions", "puddy") in isolated, "账号隔离目录")
|
||||
_ok("crm_puddy" in config.browser_profile_dir("puddy"), "浏览器 profile 按账号隔离")
|
||||
_eq(config.BRAND_SHOPS_URL, config.MEMBERSHIP + "/common/getAuthorizedBrandShops",
|
||||
"门店树接口地址")
|
||||
|
||||
|
||||
def test_cookie_header_order() -> None:
|
||||
"""轮换期同名 x-token 必须保序全留(CookieJar 会去重成作废值)。"""
|
||||
tmp = tempfile.mkdtemp(prefix="crm_sdk_")
|
||||
path = os.path.join(tmp, "crm_cookies.json")
|
||||
items = [
|
||||
{"name": "x-token", "value": "NEW", "domain": ".37du.co", "path": "/"},
|
||||
{"name": "x-token", "value": "OLD", "domain": ".37du.co", "path": "/"},
|
||||
{"name": "other", "value": "1", "domain": "dingtalk.com", "path": "/"},
|
||||
]
|
||||
with open(path, "w", encoding="utf-8") as fp:
|
||||
json.dump(items, fp)
|
||||
header = session.cookie_header_from_cookies(path)
|
||||
_eq(header, "x-token=NEW; x-token=OLD", "同名 Cookie 保序且过滤非 CRM 域")
|
||||
sess = session.session_from_header(header)
|
||||
_eq(sess.headers.get("Cookie"), "x-token=NEW; x-token=OLD", "Cookie 头原样复放")
|
||||
_raises(ConfigError, lambda: session.cookie_header_from_cookies(os.path.join(tmp, "none.json")),
|
||||
"缺失 cookies 文件")
|
||||
|
||||
|
||||
def test_client_envelope() -> None:
|
||||
ok_resp = _Resp({"code": "S0", "success": True, "message": "操作成功",
|
||||
"data": [{"label": "金色印象", "value": 10001, "children": []}]})
|
||||
client = CrmClient(_Session(ok_resp))
|
||||
data = client.call("GET", config.BRAND_SHOPS_URL, label="门店树")
|
||||
_eq(data[0]["label"], "金色印象", "S0 信封返回 data")
|
||||
|
||||
expired = CrmClient(_Session(_Resp({"code": "E401", "success": False, "message": "未认证"})))
|
||||
_raises(SessionExpiredError, lambda: expired.call("GET", config.USER_URL), "E401 判登录失效")
|
||||
|
||||
denied = CrmClient(_Session(_Resp({"code": "E302", "success": False, "message": "无权限"})))
|
||||
try:
|
||||
denied.call("GET", config.USER_URL, label="用户")
|
||||
except ApiError as exc:
|
||||
_eq(exc.code, "E302", "业务错误码透出")
|
||||
else:
|
||||
raise AssertionError("E302 应抛 ApiError")
|
||||
|
||||
_raises(SessionExpiredError,
|
||||
lambda: CrmClient(_Session(_Resp(None, status=401))).call("GET", config.USER_URL),
|
||||
"HTTP 401 判登录失效")
|
||||
|
||||
html = _Resp(None, text="<html>login</html>")
|
||||
_raises(SessionExpiredError,
|
||||
lambda: CrmClient(_Session(html)).call("GET", config.USER_URL),
|
||||
"返回 HTML 判登录失效")
|
||||
|
||||
|
||||
def test_catalog() -> None:
|
||||
stub = _StubClient(SAMPLE_TREE)
|
||||
cat = stores.Catalog.load(stub)
|
||||
_eq(len(stub.calls), 1, "Catalog.load 只发一次请求")
|
||||
_eq(cat.brands, ["金色印象", "金色春天", "康多巴巴"], "品牌列表")
|
||||
_eq(len(cat), 5, "门店总数")
|
||||
_eq(cat.brand_of("北城天街CEO会馆"), "金色印象", "门店→品牌")
|
||||
_eq(cat.shop_id("北城天街CEO会馆"), "10084", "门店 ID 转字符串")
|
||||
_eq(cat.brand_of("不存在的店"), "", "未收录返回空串")
|
||||
_eq(cat.brand_of(" 北城天街CEO会馆 "), "金色印象", "首尾空白忽略")
|
||||
_eq(cat.names("金色春天"), ["黄泥磅SPA会馆"], "按品牌筛门店")
|
||||
_ok("石碾盘CEO会馆" in cat.by_name and "石碾盘CEO会馆(OLD)" in cat.by_name,
|
||||
"新旧店名各自独立(避免把 OLD 匹配成新店)")
|
||||
|
||||
rows = stores.shops(stub, brand="康多巴巴")
|
||||
_eq(rows, [{"brand": "康多巴巴", "brand_id": "10003",
|
||||
"name": "石碾盘CEO会馆(OLD)", "shop_id": "10100"}], "扁平门店结构")
|
||||
|
||||
filtered = stores.Catalog.from_tree(SAMPLE_TREE, brand="金色春天")
|
||||
_eq(len(filtered), 1, "按品牌构建子索引")
|
||||
_eq(stores.brand_of(stub, "黄泥磅SPA会馆"), "金色春天", "单次查询版 brand_of")
|
||||
|
||||
|
||||
def test_empty_tree() -> None:
|
||||
stub = _StubClient(None)
|
||||
_eq(stores.tree(stub), [], "data 为 None 时返回空列表")
|
||||
|
||||
class _Bad:
|
||||
def call(self, method, url, **kwargs):
|
||||
return {"label": "不是数组"}
|
||||
|
||||
try:
|
||||
stores.tree(_Bad())
|
||||
except ApiError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("非数组 data 应抛 ApiError")
|
||||
|
||||
|
||||
def _patch(pairs):
|
||||
"""临时替换属性:``pairs = [(obj, attr, value), ...]``,返回 restore()。"""
|
||||
saved = []
|
||||
for obj, attr, value in pairs:
|
||||
saved.append((obj, attr, getattr(obj, attr)))
|
||||
setattr(obj, attr, value)
|
||||
|
||||
def restore():
|
||||
for obj, attr, value in reversed(saved):
|
||||
setattr(obj, attr, value)
|
||||
|
||||
return restore
|
||||
|
||||
|
||||
def test_captcha() -> None:
|
||||
import base64
|
||||
|
||||
_eq(captcha.normalize("A1B2"), "a1b2", "验证码清洗转小写")
|
||||
_eq(captcha.normalize(" a-1b2 "), "a1b2", "丢弃非法字符")
|
||||
_raises(CaptchaError, lambda: captcha.normalize("ab"), "位数不足视为识别失败")
|
||||
_eq(captcha.decode_data_url("data:image/png;base64," + base64.b64encode(b"PNG").decode()),
|
||||
b"PNG", "data-url 解码")
|
||||
_raises(CaptchaError, lambda: captcha.decode_data_url(""), "空验证码数据")
|
||||
|
||||
class _Engine:
|
||||
def __init__(self, text):
|
||||
self.text = text
|
||||
|
||||
def classification(self, png, probability=False):
|
||||
return {"text": self.text, "probabilities": [[[0.9]], [[0.8]], [[0.7]], [[0.6]]]}
|
||||
|
||||
restore = _patch([(captcha, "_load_engine", lambda: _Engine("A1B2"))])
|
||||
try:
|
||||
_eq(captcha.recognize(b"png"), "a1b2", "识别结果规整")
|
||||
finally:
|
||||
restore()
|
||||
|
||||
restore = _patch([(captcha, "_load_engine", lambda: _Engine("ab"))])
|
||||
try:
|
||||
_raises(CaptchaError, lambda: captcha.recognize(b"png"), "所有变体位数不对即失败")
|
||||
finally:
|
||||
restore()
|
||||
_raises(CaptchaError, lambda: captcha.recognize(b""), "空图片不识别")
|
||||
|
||||
|
||||
def test_reports() -> None:
|
||||
_ok("unionPay" in reports.names(), "报表注册表非空")
|
||||
_eq(reports.titles()["unionPay"], "支付数据", "报表标题")
|
||||
_raises(ConfigError, lambda: reports._spec_of("不存在的报表"), "未知报表报错")
|
||||
|
||||
paged = CrmClient(_Session(_Resp(
|
||||
{"code": "S0", "success": True,
|
||||
"data": {"list": [{"a": 1}, {"a": 2}], "total": 2}})))
|
||||
probe = reports.query(paged, "unionPay", reportDate="2026-11-25")
|
||||
_eq(probe["total"], 2, "分页型 total")
|
||||
_eq(len(probe["rows"]), 2, "分页型 rows")
|
||||
_eq(probe["has_more"], False, "分页型 has_more")
|
||||
|
||||
arrayed = CrmClient(_Session(_Resp({"code": "S0", "success": True, "data": [{"a": 1}]})))
|
||||
probe = reports.query(arrayed, "posPay")
|
||||
_eq(probe["total"], 1, "直返数组型 total 取长度")
|
||||
_eq(probe["has_more"], False, "直返数组型一次到底")
|
||||
|
||||
calls = []
|
||||
|
||||
class _PostOnly(_Session):
|
||||
def get(self, url, **kwargs):
|
||||
calls.append("GET")
|
||||
return super().get(url, **kwargs)
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
calls.append("POST")
|
||||
return _Resp({"code": "S0", "success": True, "data": {"list": [], "total": 0}})
|
||||
|
||||
reports.query(CrmClient(_PostOnly(_Resp(None, status=200))), "memberCoupon")
|
||||
_eq(calls, ["POST"], "memberCoupon 列表走 POST(GET 会 400)")
|
||||
|
||||
|
||||
def test_login_by_password() -> None:
|
||||
"""三条分支:成功落盘、验证码错换会话重试、账号错立即返回不重试。"""
|
||||
tmp = tempfile.mkdtemp(prefix="crm_login_")
|
||||
cookie_path = os.path.join(tmp, "crm_cookies.json")
|
||||
header_path = os.path.join(tmp, "crm_cookie_header.txt")
|
||||
|
||||
class _Cookie:
|
||||
def __init__(self, name, value):
|
||||
self.name, self.value = name, value
|
||||
self.domain, self.path = ".37du.co", "/"
|
||||
|
||||
class _LoginSession:
|
||||
def __init__(self, payload, cookies):
|
||||
self.payload = payload
|
||||
self.cookies = cookies
|
||||
self.posts = []
|
||||
|
||||
def get(self, url, **kwargs): # _fetch_captcha_png 已被 patch
|
||||
return _Resp({"success": True, "data": "data:image/png;base64,AAAA"})
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
self.posts.append(kwargs)
|
||||
return _Resp(self.payload)
|
||||
|
||||
created = []
|
||||
|
||||
def _run(payload, cookies, attempts):
|
||||
created.clear()
|
||||
|
||||
def _factory():
|
||||
sess = _LoginSession(payload, cookies)
|
||||
created.append(sess)
|
||||
return sess
|
||||
|
||||
restore = _patch([
|
||||
(auth, "_fresh_session", _factory),
|
||||
(auth, "_fetch_captcha_png", lambda sess: b"png"),
|
||||
(auth, "_verify_header", lambda raw, log=None: bool(raw)),
|
||||
(captcha, "recognize", lambda png, length=4: "abcd"),
|
||||
(config, "cookies_file", lambda account="": cookie_path),
|
||||
(config, "cookie_header_file", lambda account="": header_path),
|
||||
(config, "token_file", lambda account="": os.path.join(tmp, "crm_tokens.json")),
|
||||
(config, "PASSWORD_RETRY_DELAY", 0),
|
||||
])
|
||||
try:
|
||||
return auth.login_by_password(username="u", password="p", attempts=attempts)
|
||||
finally:
|
||||
restore()
|
||||
|
||||
# ① 成功:落盘 + Cookie 头保序
|
||||
result = _run({"success": True, "code": "S0", "data": None},
|
||||
[_Cookie("x-token", "NEW"), _Cookie("x-token", "OLD")], attempts=1)
|
||||
_eq(result["success"], True, "密码登录成功")
|
||||
_eq(result["relogin"], True, "relogin 标记")
|
||||
with open(header_path, encoding="utf-8") as fp:
|
||||
_eq(fp.read().strip(), "x-token=NEW; x-token=OLD", "登录后 Cookie 头保序落盘")
|
||||
with open(cookie_path, encoding="utf-8") as fp:
|
||||
_eq(len(json.load(fp)), 2, "cookies.json 落盘条数")
|
||||
|
||||
# ② 验证码错:换新会话重试,用满次数
|
||||
result = _run({"success": False, "code": config.CODE_CAPTCHA_WRONG, "message": "验证码错误"},
|
||||
[_Cookie("x-token", "X")], attempts=2)
|
||||
_eq(result["success"], False, "验证码错判失败")
|
||||
_eq(len(created), 2, "每次尝试换新会话(复用会 E1006 重复提交)")
|
||||
|
||||
# ③ 账号错:立即返回,绝不重试(防锁定)
|
||||
result = _run({"success": False, "code": config.CODE_USER_NOT_FOUND, "message": "用户不存在"},
|
||||
[_Cookie("x-token", "X")], attempts=3)
|
||||
_eq(result["success"], False, "账号错判失败")
|
||||
_eq(len(created), 1, "账号错不重试(避免累计触发平台锁定)")
|
||||
_ok("用户不存在" in result["message"], "回传服务端提示")
|
||||
|
||||
|
||||
def test_credentials() -> None:
|
||||
restore = _patch([
|
||||
(config, "CRM_USERNAME", "u"),
|
||||
(config, "CRM_PASSWORD", "p"),
|
||||
(config, "credentials_file", lambda account="": os.path.join(tempfile.mkdtemp(), "nope.json")),
|
||||
])
|
||||
try:
|
||||
_eq(auth.has_credentials(), True, "环境变量凭证可用")
|
||||
_eq(auth._resolve_credentials(), ("u", "p"), "凭证解析")
|
||||
finally:
|
||||
restore()
|
||||
|
||||
restore = _patch([
|
||||
(config, "CRM_USERNAME", ""),
|
||||
(config, "CRM_PASSWORD", ""),
|
||||
(config, "credentials_file", lambda account="": os.path.join(tempfile.mkdtemp(), "nope.json")),
|
||||
])
|
||||
try:
|
||||
_eq(auth.has_credentials(), False, "无凭证时判定为 False")
|
||||
_raises(ConfigError, lambda: auth._resolve_credentials(), "无凭证时报错提示配置方式")
|
||||
finally:
|
||||
restore()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
tests = [
|
||||
("paths", test_paths),
|
||||
("cookie_header_order", test_cookie_header_order),
|
||||
("client_envelope", test_client_envelope),
|
||||
("catalog", test_catalog),
|
||||
("empty_tree", test_empty_tree),
|
||||
("captcha", test_captcha),
|
||||
("reports", test_reports),
|
||||
("login_by_password", test_login_by_password),
|
||||
("credentials", test_credentials),
|
||||
]
|
||||
failed = 0
|
||||
try:
|
||||
meta_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"sdk.json")
|
||||
with open(meta_path, encoding="utf-8") as fp:
|
||||
meta = json.load(fp)
|
||||
_eq(__version__, meta.get("version"), "包版本与 sdk.json 一致")
|
||||
for name, fn in tests:
|
||||
try:
|
||||
fn()
|
||||
print(f"[ok] {name}")
|
||||
except AssertionError as exc:
|
||||
failed += 1
|
||||
print(f"[FAIL] {name}: {exc}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
print(f"[ERROR] {name}: {type(exc).__name__}: {exc}")
|
||||
finally:
|
||||
print(f"自测完成:{_CHECKS} 项断言,失败 {failed} 组")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,652 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CRM 登录态:账号密码登录(验证码 OCR)、钉钉扫码兜底、Cookie 复用与落盘。
|
||||
|
||||
登录顺序(先无人值守,再人工兜底)::
|
||||
|
||||
1. 纯 API 校验优先:落盘 Cookie 头 GET /membership/main/user 返回 code=S0 即复用
|
||||
(服务端滑动会话约 30 分钟,期间完全免登录、不开浏览器);
|
||||
2. 已配置账号密码(环境变量或凭证文件)时走 :func:`login_by_password`:
|
||||
取验证码 → ddddocr 识别 → 表单提交 → 校验并落盘,**全程无需人工**;
|
||||
3. 密码登录不可用时才开浏览器:先给 profile 里残留会话一次短窗口机会(钉钉会话
|
||||
存活时 SPA 静默重登),仍无效则停官方登录页等人工钉钉扫码(默认最多 300 秒)。
|
||||
|
||||
密码登录的两个硬约束(实测,别踩)::
|
||||
|
||||
* 验证码与取码会话绑定,且 **一个会话只能提交一次登录**——验证码错一次后
|
||||
该会话永久返回 E1006 重复提交,所以每次尝试都必须换新会话;
|
||||
* 验证码不区分大小写,图上是 cK7r,提交 ck7r 一样通过(故识别结果统一转小写)。
|
||||
|
||||
扫码闸门:同一进程最多弹一次扫码窗口,后续失效快速失败,绝不把任务挂死。
|
||||
|
||||
典型用法::
|
||||
|
||||
from crm_sdk import auth, CrmClient, stores
|
||||
|
||||
result = auth.ensure_login(log=ctx.log) # 有凭证就静默登录
|
||||
client = CrmClient(auth.build_session(), log=ctx.log)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
import requests
|
||||
|
||||
from . import captcha, config
|
||||
from .errors import AuthError, CaptchaError, ConfigError
|
||||
from .session import cookie_header_from_cookies, read_cookie_header, session_from_header
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
#: 本次进程的扫码闸门:同一次运行只允许弹一次扫码窗口
|
||||
_scan_attempted = False
|
||||
_scan_failed_msg: Optional[str] = None
|
||||
|
||||
|
||||
def _logger(log: Optional[LOGGER]) -> LOGGER:
|
||||
return log or (lambda msg: None)
|
||||
|
||||
|
||||
def _log(log: Optional[LOGGER], msg: str, level: str = "INFO") -> None:
|
||||
_logger(log)(f"[{level}] {msg}" if level != "INFO" else msg)
|
||||
|
||||
|
||||
# ==================== 落盘工具 ====================
|
||||
def _ensure_dir(path: str) -> None:
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path: str, text: str) -> None:
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截快照(半截必然 401)。"""
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f"{path}.tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as fp:
|
||||
fp.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _set_topmost(pid: Optional[int], on: bool = True) -> None:
|
||||
"""把指定进程主窗口设为 HWND_TOPMOST / 取消(仅 Windows,失败忽略)。"""
|
||||
if not pid or os.name != "nt":
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
hwnds: list = []
|
||||
|
||||
@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(_collect, 0)
|
||||
target = -1 if on else -2 # HWND_TOPMOST / HWND_NOTOPMOST
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(wintypes.HWND(hwnd), wintypes.HWND(target), 0, 0, 0, 0,
|
||||
0x0001 | 0x0002) # NOSIZE | NOMOVE
|
||||
|
||||
|
||||
def _apply_window_mode(page, log: Optional[LOGGER]) -> None:
|
||||
"""全屏 + 置顶:扫码窗口被遮挡时用户找不到窗口,也避免渲染进程不出帧。"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as exc: # noqa: BLE001 - 界面操作失败不影响登录
|
||||
_log(log, f"设置窗口全屏失败(忽略):{exc}", "WARN")
|
||||
try:
|
||||
_set_topmost(page.process_id, True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log(log, f"设置窗口置顶失败(忽略):{exc}", "WARN")
|
||||
|
||||
|
||||
def _restore_window_mode(page, log: Optional[LOGGER]) -> None:
|
||||
try:
|
||||
page.set.window.normal()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log(log, f"恢复窗口大小失败(忽略):{exc}", "WARN")
|
||||
try:
|
||||
_set_topmost(page.process_id, False)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log(log, f"取消窗口置顶失败(忽略):{exc}", "WARN")
|
||||
|
||||
|
||||
# ==================== 会话构造与校验(纯 API,免开浏览器) ====================
|
||||
def build_session(*, account: str = "", log: Optional[LOGGER] = None,
|
||||
user_agent: str = config.USER_AGENT) -> Optional[requests.Session]:
|
||||
"""构建可复用登录态的会话:优先有效 Cookie 头,缺失则按 cookies.json 保序重建。
|
||||
|
||||
Returns:
|
||||
会话;两个文件都没有时返回 ``None``(不抛,便于调用方先判空)
|
||||
"""
|
||||
header = read_cookie_header(account=account)
|
||||
if header:
|
||||
return session_from_header(header, user_agent=user_agent)
|
||||
try:
|
||||
rebuilt = cookie_header_from_cookies(account=account)
|
||||
except ConfigError:
|
||||
return None
|
||||
_log(log, "Cookie 头文件缺失,已按 cookies.json 原始顺序重建", "WARN")
|
||||
return session_from_header(rebuilt, user_agent=user_agent)
|
||||
|
||||
|
||||
def _verify_header(raw: str, log: Optional[LOGGER] = None) -> bool:
|
||||
"""端到端校验:用待落盘的 Cookie 头真实发一次请求(防抓到时已是作废票据)。"""
|
||||
if not raw:
|
||||
return False
|
||||
try:
|
||||
resp = session_from_header(raw).get(config.USER_URL, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
return False
|
||||
return resp.json().get("code") == config.SUCCESS_CODE
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log(log, f"Cookie 头端到端校验异常:{exc}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def is_session_valid(*, account: str = "", log: Optional[LOGGER] = None) -> bool:
|
||||
"""API 轻量校验:``GET /membership/main/user`` 返回 ``code=S0`` 视为有效。"""
|
||||
sess = build_session(account=account, log=log)
|
||||
if sess is None:
|
||||
return False
|
||||
try:
|
||||
resp = sess.get(config.USER_URL, timeout=15)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log(log, f"API 校验登录态异常:{exc}", "WARN")
|
||||
return False
|
||||
if resp.status_code != 200:
|
||||
_log(log, f"API 校验登录态状态码异常:{resp.status_code}", "WARN")
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
except ValueError:
|
||||
return False
|
||||
if isinstance(data, dict) and data.get("code") == config.SUCCESS_CODE:
|
||||
return True
|
||||
_log(log, f"API 校验返回非成功码:{str(data)[:200]}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def keep_alive(*, account: str = "", log: Optional[LOGGER] = None) -> bool:
|
||||
"""轻量保活:一次请求刷新滑动会话的空闲计时。"""
|
||||
return is_session_valid(account=account, log=log)
|
||||
|
||||
|
||||
def _repair_header_from_json(*, account: str = "", log: Optional[LOGGER] = None) -> bool:
|
||||
"""Cookie 头文件失效/损坏时自愈:用 cookies.json 保序重建并校验,成功回写。"""
|
||||
try:
|
||||
raw = cookie_header_from_cookies(account=account)
|
||||
except ConfigError:
|
||||
return False
|
||||
if not _verify_header(raw, log):
|
||||
return False
|
||||
if read_cookie_header(account=account) != raw:
|
||||
_atomic_write(config.cookie_header_file(account), raw)
|
||||
_log(log, "已用 cookies.json 重建有效 Cookie 头并回写")
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 浏览器侧落盘 ====================
|
||||
def _save_login_state(page, *, account: str = "", log: Optional[LOGGER] = None) -> None:
|
||||
"""保存 cookies 与 localStorage/sessionStorage 票据(SPA 常把 token 放 storage)。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
_atomic_write(config.cookies_file(account),
|
||||
json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
_log(log, f"已保存 {len(cookies)} 个 Cookies → {config.cookies_file(account)}")
|
||||
else:
|
||||
_log(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)
|
||||
});
|
||||
''')
|
||||
state = json.loads(raw) if raw else {}
|
||||
ls = state.get("localStorage") or {}
|
||||
ss = state.get("sessionStorage") or {}
|
||||
if ls or ss:
|
||||
_atomic_write(config.token_file(account), json.dumps(
|
||||
{"localStorage": ls, "sessionStorage": ss,
|
||||
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
|
||||
ensure_ascii=False, indent=2))
|
||||
_log(log, f"已保存票据 localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项")
|
||||
except Exception as exc: # noqa: BLE001 - 票据只是辅助,失败不阻断
|
||||
_log(log, f"保存 storage 票据失败(不影响 Cookies):{exc}", "WARN")
|
||||
|
||||
|
||||
def _save_effective_header(page, *, account: str = "",
|
||||
log: Optional[LOGGER] = None) -> bool:
|
||||
"""捕获浏览器实际发送的完整 Cookie 头,双校验后原子落盘。"""
|
||||
try:
|
||||
page.listen.start("main/user")
|
||||
page.run_js("fetch('/membership/main/user', {headers:{'Accept':'application/json'}})")
|
||||
packet = page.listen.wait(timeout=10)
|
||||
page.listen.stop()
|
||||
if not packet:
|
||||
_log(log, "未捕获到浏览器验证请求,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
raw = None
|
||||
for key, value in (packet.request.headers or {}).items():
|
||||
if key.lower() == "cookie":
|
||||
raw = value
|
||||
if not raw:
|
||||
_log(log, "验证请求无 Cookie 头,跳过有效 Cookie 头落盘", "WARN")
|
||||
return False
|
||||
try:
|
||||
body = packet.response.body if isinstance(packet.response.body, dict) \
|
||||
else json.loads(str(packet.response.body))
|
||||
except Exception: # noqa: BLE001
|
||||
body = {}
|
||||
if not (isinstance(body, dict) and body.get("code") == config.SUCCESS_CODE):
|
||||
_log(log, f"捕获的 Cookie 头校验未通过:{str(body)[:120]}", "WARN")
|
||||
return False
|
||||
if not _verify_header(raw, log):
|
||||
_log(log, "捕获的 Cookie 头在 requests 侧校验未通过,不覆盖已有快照", "WARN")
|
||||
return False
|
||||
_atomic_write(config.cookie_header_file(account), raw)
|
||||
_log(log, "已保存有效 Cookie 头(浏览器 + requests 双校验 S0)")
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_log(log, f"捕获有效 Cookie 头异常:{exc}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def save_from_page(page, *, account: str = "", log: Optional[LOGGER] = None) -> bool:
|
||||
"""登录态已由浏览器建立时,把 cookies 与有效 Cookie 头同步落盘,供纯 API 复用。"""
|
||||
_save_login_state(page, account=account, log=log)
|
||||
if not _save_effective_header(page, account=account, log=log):
|
||||
_repair_header_from_json(account=account, log=log)
|
||||
ok = is_session_valid(account=account, log=log)
|
||||
if ok:
|
||||
_log(log, "登录态已同步落盘(requests 侧校验 S0 通过)")
|
||||
else:
|
||||
_log(log, "登录态同步后 requests 侧仍不可用", "WARN")
|
||||
return ok
|
||||
|
||||
|
||||
# ==================== 浏览器轮询 ====================
|
||||
def _is_login_page(url: str) -> bool:
|
||||
"""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_PAGE_KEYWORD in fragment
|
||||
|
||||
|
||||
def _api_ok_in_browser(page) -> bool:
|
||||
"""页面内 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);
|
||||
''')
|
||||
text = str(raw or "")
|
||||
return text.startswith("200:") and f'"code":"{config.SUCCESS_CODE}"' in text
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _wait_api_ok(page, seconds: float) -> bool:
|
||||
"""轮询等待页面内 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, log: Optional[LOGGER] = None) -> bool:
|
||||
"""复用浏览器 profile 残留会话。
|
||||
|
||||
走到这里说明落盘快照已失效,因此**不再注入快照 Cookie**:既救不活作废票据,
|
||||
还可能把 profile 里仍有效的会话覆盖成作废值。
|
||||
"""
|
||||
page.get(config.CRM_SITE_URL)
|
||||
if _wait_api_ok(page, config.PROFILE_REUSE_WAIT):
|
||||
_log(log, "浏览器 profile 自身会话有效,直接续用")
|
||||
return True
|
||||
_log(log, "浏览器 profile 无有效会话(落盘 Cookie 快照已在服务端失效)", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _wait_scan(page, wait_scan: float, log: Optional[LOGGER] = None) -> bool:
|
||||
"""等待人工扫码:URL 离开登录页即成功(钉钉会话存活时会静默重登)。"""
|
||||
_log(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(log, "仍未检测到扫码登录,请确认已用钉钉 App 扫码并点击确认……")
|
||||
hinted = True
|
||||
return False
|
||||
|
||||
|
||||
def _attempt(force: bool, headless: bool, wait_scan: float, *,
|
||||
account: str = "", log: Optional[LOGGER] = None):
|
||||
"""一轮完整流程:开浏览器 → 未 force 先尝试复用 → 失效则等待扫码。"""
|
||||
from DrissionPage import ChromiumOptions, ChromiumPage # 延迟导入:纯 API 场景不装浏览器
|
||||
|
||||
options = ChromiumOptions()
|
||||
if headless:
|
||||
options.headless()
|
||||
options.set_argument("--start-maximized")
|
||||
options.set_pref("credentials_enable_service", False)
|
||||
options.set_pref("profile.password_manager_enabled", False)
|
||||
profile_dir = config.browser_profile_dir(account)
|
||||
_ensure_dir(profile_dir)
|
||||
options.set_user_data_path(profile_dir)
|
||||
|
||||
page = ChromiumPage(options)
|
||||
try:
|
||||
if not headless:
|
||||
_apply_window_mode(page, log) # 全屏 + 置顶,扫码窗口不被遮挡
|
||||
if not force and _check_reuse(page, log):
|
||||
time.sleep(config.LOGIN_SETTLE) # 静默重登可能已刷新会话,等首屏结束再抓
|
||||
save_from_page(page, account=account, log=log)
|
||||
_restore_window_mode(page, log)
|
||||
return True, "复用缓存登录态", False
|
||||
_log(log, "登录态失效或不存在,打开官方登录页等待扫码……")
|
||||
page.get(config.CRM_LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if _wait_scan(page, wait_scan, log):
|
||||
_log(log, f"登录成功 → {page.url}")
|
||||
time.sleep(config.LOGIN_SETTLE) # 首屏请求结束后再抓,避免轮换前快照
|
||||
save_from_page(page, account=account, log=log)
|
||||
_restore_window_mode(page, log)
|
||||
return True, "登录成功", True
|
||||
_log(log, f"等待超时({wait_scan}s 内未检测到扫码登录)", "ERROR")
|
||||
return False, "扫码登录超时(未检测到登录成功)", True
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 账号密码登录(验证码 OCR,纯 API) ====================
|
||||
def _resolve_credentials(username: Optional[str] = None, password: Optional[str] = None,
|
||||
account: str = ""):
|
||||
"""凭证优先级:入参 > 环境变量 ``CRM_USERNAME``/``CRM_PASSWORD`` > 凭证文件。
|
||||
|
||||
Raises:
|
||||
ConfigError: 账号或密码缺任意一项
|
||||
"""
|
||||
user = (username or config.CRM_USERNAME or "").strip()
|
||||
pwd = password if password is not None else config.CRM_PASSWORD
|
||||
if not user or not pwd:
|
||||
path = config.credentials_file(account)
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as fp:
|
||||
data = json.load(fp)
|
||||
except (OSError, ValueError):
|
||||
data = {}
|
||||
if isinstance(data, dict):
|
||||
user = user or str(data.get("username") or "").strip()
|
||||
pwd = pwd or str(data.get("password") or "")
|
||||
if not user or not pwd:
|
||||
raise ConfigError(
|
||||
"缺少 CRM 账号密码:请设置环境变量 CRM_USERNAME / CRM_PASSWORD,"
|
||||
f"或写入凭证文件 {config.credentials_file(account)}"
|
||||
)
|
||||
return user, pwd
|
||||
|
||||
|
||||
def has_credentials(account: str = "") -> bool:
|
||||
"""是否已配置账号密码(用于决定走密码登录还是扫码兜底)。"""
|
||||
try:
|
||||
_resolve_credentials(account=account)
|
||||
return True
|
||||
except ConfigError:
|
||||
return False
|
||||
|
||||
|
||||
def _fresh_session() -> requests.Session:
|
||||
"""一次登录尝试专用会话(失败即丢弃,绝不复用:会话只能提交一次)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.USER_AGENT,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": config.CRM_SITE_URL,
|
||||
"Origin": config.CRM_BASE_URL,
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def _fetch_captcha_png(session) -> bytes:
|
||||
"""取一张验证码图片的 PNG 字节。"""
|
||||
resp = session.get(config.CAPTCHA_URL, timeout=config.DEFAULT_TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
try:
|
||||
payload = resp.json()
|
||||
except ValueError:
|
||||
raise AuthError(f"验证码接口返回非 JSON:{resp.text[:200]}") from None
|
||||
if not payload.get("success"):
|
||||
raise AuthError(f"取验证码失败:{str(payload)[:200]}")
|
||||
return captcha.decode_data_url(payload.get("data") or "")
|
||||
|
||||
|
||||
def _persist_from_requests(session, *, account: str = "",
|
||||
log: Optional[LOGGER] = None) -> bool:
|
||||
"""把纯 API 登录成功后的 Cookie 原子落盘(cookies.json + Cookie 头原文)。"""
|
||||
jar = list(session.cookies)
|
||||
if not jar:
|
||||
_log(log, "登录返回成功但未拿到任何 Cookie", "WARN")
|
||||
return False
|
||||
items = [{"name": c.name, "value": c.value,
|
||||
"domain": c.domain or config.CRM_DOMAIN, "path": c.path or "/"}
|
||||
for c in jar]
|
||||
header = "; ".join(f"{c.name}={c.value}" for c in jar)
|
||||
_atomic_write(config.cookies_file(account),
|
||||
json.dumps(items, ensure_ascii=False, indent=2))
|
||||
_atomic_write(config.cookie_header_file(account), header)
|
||||
_log(log, f"已保存 {len(items)} 个 Cookie(账号密码登录)")
|
||||
return True
|
||||
|
||||
|
||||
def login_by_password(*, username: Optional[str] = None, password: Optional[str] = None,
|
||||
account: str = "", attempts: Optional[int] = None,
|
||||
log: Optional[LOGGER] = None) -> dict:
|
||||
"""账号密码登录:取验证码 → ddddocr 识别 → 表单提交 → 校验并落盘。
|
||||
|
||||
**每次尝试都换新会话**:CRM 一个会话只允许提交一次登录,验证码错一次后
|
||||
该会话即永久返回 ``E1006 重复提交``,复用它只会把重试次数耗光。
|
||||
|
||||
Args:
|
||||
username / password: 为空时按 :func:`_resolve_credentials` 的顺序回退
|
||||
account: 账号(决定会话落盘目录)
|
||||
attempts: 尝试次数(默认 :data:`config.PASSWORD_LOGIN_ATTEMPTS`)
|
||||
|
||||
Returns:
|
||||
``{"success", "cookie_path", "token_path", "message", "relogin"}``
|
||||
|
||||
Raises:
|
||||
ConfigError: 未配置账号密码
|
||||
"""
|
||||
result = {"success": False, "cookie_path": config.cookies_file(account),
|
||||
"token_path": config.token_file(account), "relogin": True, "message": ""}
|
||||
user, pwd = _resolve_credentials(username, password, account)
|
||||
|
||||
attempts = config.PASSWORD_LOGIN_ATTEMPTS if attempts is None else max(1, int(attempts))
|
||||
last_msg = ""
|
||||
for attempt in range(1, attempts + 1):
|
||||
session = _fresh_session()
|
||||
try:
|
||||
png = _fetch_captcha_png(session)
|
||||
except Exception as exc: # noqa: BLE001 - 网络抖动可重试
|
||||
last_msg = f"取验证码失败:{exc}"
|
||||
_log(log, f"第 {attempt}/{attempts} 次 {last_msg}", "WARN")
|
||||
continue
|
||||
|
||||
try:
|
||||
code = captcha.recognize(png, length=config.CAPTCHA_LENGTH)
|
||||
except CaptchaError as exc:
|
||||
last_msg = f"验证码识别失败:{exc}"
|
||||
_log(log, f"第 {attempt}/{attempts} 次 {last_msg}", "WARN")
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = session.post(
|
||||
config.LOGIN_URL,
|
||||
data={"username": user, "password": pwd, "captchaCode": code},
|
||||
timeout=config.DEFAULT_TIMEOUT,
|
||||
)
|
||||
payload = resp.json()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last_msg = f"登录请求异常:{exc}"
|
||||
_log(log, f"第 {attempt}/{attempts} 次 {last_msg}", "WARN")
|
||||
continue
|
||||
|
||||
code_ret = str(payload.get("code") or "")
|
||||
if payload.get("success") and code_ret == config.SUCCESS_CODE:
|
||||
if not _persist_from_requests(session, account=account, log=log):
|
||||
result["message"] = "登录成功但未能保存 Cookie"
|
||||
return result
|
||||
raw = read_cookie_header(account=account)
|
||||
if _verify_header(raw, log):
|
||||
result.update(success=True, message="账号密码登录成功")
|
||||
_log(log, f"账号密码登录成功(验证码 {code},第 {attempt} 次)")
|
||||
return result
|
||||
last_msg = "登录成功但落盘 Cookie 校验未通过"
|
||||
_log(log, last_msg, "WARN")
|
||||
continue
|
||||
|
||||
# 验证码类失败:换会话重试(间隔一小段,避免连续 POST 形成机器节奏)
|
||||
if code_ret in (config.CODE_CAPTCHA_WRONG, config.CODE_CAPTCHA_EMPTY,
|
||||
config.CODE_DUPLICATE_SUBMIT):
|
||||
last_msg = f"验证码未通过({code_ret}),换会话重试"
|
||||
_log(log, f"第 {attempt}/{attempts} 次 {last_msg}", "WARN")
|
||||
if attempt < attempts:
|
||||
time.sleep(config.PASSWORD_RETRY_DELAY)
|
||||
continue
|
||||
|
||||
# 账号密码错误 / 账号锁定等:重试无意义
|
||||
result["message"] = f"{payload.get('message') or '登录失败'}({code_ret})"
|
||||
_log(log, result["message"], "ERROR")
|
||||
return result
|
||||
|
||||
result["message"] = last_msg or "账号密码登录失败"
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(*, account: str = "", force: bool = False,
|
||||
headless: Optional[bool] = None, wait_scan: Optional[float] = None,
|
||||
prefer_password: bool = True, log: Optional[LOGGER] = None) -> dict:
|
||||
"""确保存在有效的 CRM 登录态并落盘票据。
|
||||
|
||||
顺序:纯 API 复用 → Cookie 头自愈 → **账号密码登录(验证码 OCR,无人值守)**
|
||||
→ 钉钉扫码兜底(人工在场)。
|
||||
|
||||
Args:
|
||||
account: 账号(按账号隔离会话目录;空则读环境变量 ``PLATFORM_ACCOUNT``)
|
||||
force: 忽略缓存直接重新登录
|
||||
headless: 是否无头(默认 :data:`config.HEADLESS`,扫码必须可见)
|
||||
wait_scan: 等扫码超时秒数(默认 :data:`config.SCAN_WAIT`)
|
||||
prefer_password: 已配置账号密码时优先走密码登录(不弹浏览器)
|
||||
|
||||
Returns:
|
||||
``{"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 float(wait_scan)
|
||||
result = {"success": False, "cookie_path": config.cookies_file(account),
|
||||
"token_path": config.token_file(account), "relogin": False}
|
||||
|
||||
# ① 纯 API 校验优先:cookies 有效时全程免开浏览器
|
||||
if not force:
|
||||
if is_session_valid(account=account, log=log):
|
||||
_log(log, "已通过缓存的 Cookies 复用 CRM 登录态(API 校验)")
|
||||
result.update(success=True, message="复用缓存登录态")
|
||||
return result
|
||||
# ①b Cookie 头损坏/同名项顺序错、而 cookies.json 仍完好时自愈
|
||||
if _repair_header_from_json(account=account, log=log):
|
||||
_log(log, "已用 cookies.json 重建 Cookie 头,复用 CRM 登录态")
|
||||
result.update(success=True, message="复用缓存登录态(重建 Cookie 头)")
|
||||
return result
|
||||
|
||||
# ①c 已配置账号密码时优先走密码登录:验证码 OCR,全程不需要人工
|
||||
if prefer_password and has_credentials(account):
|
||||
pwd_result = login_by_password(account=account, log=log)
|
||||
if pwd_result["success"]:
|
||||
result.update(success=True, relogin=True, message=pwd_result["message"])
|
||||
return result
|
||||
_log(log, f"账号密码登录未成功:{pwd_result['message']};改走扫码兜底", "WARN")
|
||||
|
||||
# ② 本次运行已弹过扫码窗口:不再重复弹,快速失败
|
||||
if _scan_attempted:
|
||||
msg = _scan_failed_msg or "本次运行已尝试过扫码登录,登录态仍失效;请重新运行任务并完成扫码"
|
||||
_log(log, msg, "WARN")
|
||||
result.update(message=msg)
|
||||
return result
|
||||
_scan_attempted = True
|
||||
|
||||
# ③ 开浏览器:profile 层复用兜底,失效则扫码
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
ok, msg, relogin = _attempt(force, headless, wait_scan,
|
||||
account=account, log=log)
|
||||
if not ok:
|
||||
_scan_failed_msg = msg
|
||||
result.update(success=ok, message=msg, relogin=relogin)
|
||||
return result
|
||||
except Exception as exc: # noqa: BLE001 - 浏览器抖动重试
|
||||
last_msg = f"登录过程异常:{exc}"
|
||||
_log(log, f"第 {attempt}/{config.MAX_ATTEMPTS} 次异常:{exc}", "WARN")
|
||||
time.sleep(1)
|
||||
_scan_failed_msg = last_msg or "登录失败"
|
||||
result.update(message=_scan_failed_msg)
|
||||
return result
|
||||
|
||||
|
||||
def reset_scan_gate() -> None:
|
||||
"""重置本次进程的扫码闸门(长驻进程 / 换账号重试时用)。"""
|
||||
global _scan_attempted, _scan_failed_msg
|
||||
_scan_attempted = False
|
||||
_scan_failed_msg = None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AuthError",
|
||||
"build_session",
|
||||
"ensure_login",
|
||||
"has_credentials",
|
||||
"is_session_valid",
|
||||
"keep_alive",
|
||||
"login_by_password",
|
||||
"reset_scan_gate",
|
||||
"save_from_page",
|
||||
]
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""验证码识别(ddddocr 单例封装)。
|
||||
|
||||
CRM 登录验证码的实测事实(决定了本模块的写法):
|
||||
|
||||
1. 图片 100×50 PNG,**4 位字母数字**;
|
||||
2. 服务端**不区分大小写**——图上写 ``cK7r``,提交 ``ck7r`` 一样通过;
|
||||
3. 验证码与取码会话绑定且一次性,一个会话只能提交一次登录;
|
||||
4. 因此识别结果统一转小写即可,无需大小写分类器。
|
||||
|
||||
``ddddocr`` 为可选依赖:只在真正调用识别时才导入,未装时给出明确提示,
|
||||
不影响纯 Cookie 复用等场景。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from typing import Optional
|
||||
|
||||
from .errors import CaptchaError, ConfigError
|
||||
|
||||
#: 识别结果允许的字符集(小写字母 + 数字)
|
||||
_CHARSET = frozenset("abcdefghijklmnopqrstuvwxyz0123456789")
|
||||
|
||||
#: ddddocr 引擎单例(模型加载约 1~2 秒,务必复用)
|
||||
_engine: Optional[object] = None
|
||||
|
||||
|
||||
def _load_engine():
|
||||
"""惰性加载 ddddocr 引擎(只加载一次)。"""
|
||||
global _engine
|
||||
if _engine is None:
|
||||
try:
|
||||
import ddddocr # noqa: PLC0415 - 延迟导入:非登录场景不装也能用 SDK
|
||||
except ImportError as exc: # pragma: no cover - 环境缺依赖才触发
|
||||
raise ConfigError(
|
||||
"缺少验证码识别依赖 ddddocr,请先安装:"
|
||||
"pip install ddddocr(首次加载会下载 ONNX 模型)"
|
||||
) from exc
|
||||
_engine = ddddocr.DdddOcr(show_ad=False)
|
||||
return _engine
|
||||
|
||||
|
||||
def decode_data_url(text: str) -> bytes:
|
||||
"""把 ``data:image/png;base64,...`` 解成原始字节;也接受裸 base64。"""
|
||||
if not text:
|
||||
raise CaptchaError("验证码数据为空")
|
||||
raw = text.split(",", 1)[1] if text.startswith("data:") else text
|
||||
try:
|
||||
return base64.b64decode(raw)
|
||||
except Exception as exc: # noqa: BLE001 - base64 非法
|
||||
raise CaptchaError(f"验证码 base64 解码失败:{exc}") from None
|
||||
|
||||
|
||||
def normalize(text: str, *, length: int = 4) -> str:
|
||||
"""清洗识别结果:只留合法字符并转小写(服务端不区分大小写)。
|
||||
|
||||
Raises:
|
||||
CaptchaError: 清洗后长度不等于 ``length``(视为本次识别失败)
|
||||
"""
|
||||
code = "".join(ch for ch in str(text or "").lower() if ch in _CHARSET)
|
||||
if len(code) != length:
|
||||
raise CaptchaError(f"验证码识别结果长度异常:{text!r} → {code!r}(期望 {length} 位)")
|
||||
return code
|
||||
|
||||
|
||||
def _variants(png: bytes):
|
||||
"""生成识别用的图片变体(原图 + 放大灰度增强)。
|
||||
|
||||
实测:约 15% 的图 ddddocr 会把相邻字符粘连成 3 位,放大 2 倍后基本能拆开;
|
||||
灰度 + 自动对比度能压掉彩色干扰线。变体全部失败才判定识别失败。
|
||||
"""
|
||||
yield png
|
||||
try:
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
except ImportError: # 没装 Pillow 就只用原图
|
||||
return
|
||||
try:
|
||||
img = Image.open(io.BytesIO(png)).convert("L")
|
||||
img = ImageOps.autocontrast(img)
|
||||
big = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
big.save(buf, "PNG")
|
||||
yield buf.getvalue()
|
||||
except Exception: # noqa: BLE001 - 预处理失败不影响原图识别
|
||||
return
|
||||
|
||||
|
||||
def _confidence(probs) -> float:
|
||||
"""把 ddddocr 的逐字符概率矩阵折算成平均置信度(失败给 0)。"""
|
||||
try:
|
||||
vals = []
|
||||
for item in probs or []:
|
||||
vec = item[0] if item and isinstance(item[0], (list, tuple)) else item
|
||||
vals.append(max(vec))
|
||||
return float(sum(vals) / len(vals)) if vals else 0.0
|
||||
except Exception: # noqa: BLE001 - 概率结构变化只影响排序
|
||||
return 0.0
|
||||
|
||||
|
||||
def _classify(engine, png: bytes):
|
||||
"""单次识别,返回 ``(文本, 置信度)``。
|
||||
|
||||
ddddocr 各版本返回形态不同,这里全部兼容:
|
||||
``probability=True`` 在 1.6.x 返回 ``{"text": ..., "probabilities": [...]}``,
|
||||
老版本返回 ``(text, prob)`` 或纯字符串。
|
||||
"""
|
||||
try:
|
||||
result = engine.classification(png, probability=True)
|
||||
except TypeError: # 老版本没有 probability 参数
|
||||
return engine.classification(png), 0.0
|
||||
if isinstance(result, dict) and "text" in result:
|
||||
return result.get("text") or "", _confidence(result.get("probabilities"))
|
||||
if isinstance(result, tuple) and len(result) == 2:
|
||||
return result[0], float(result[1] or 0.0)
|
||||
return result, 0.0
|
||||
|
||||
|
||||
def recognize(png: bytes, *, length: int = 4) -> str:
|
||||
"""识别 PNG 字节,返回小写验证码。
|
||||
|
||||
依次尝试原图与增强图,取「长度合法且置信度最高」的结果。
|
||||
|
||||
Raises:
|
||||
CaptchaError: 图片为空、引擎报错,或所有变体都得不到 ``length`` 位结果
|
||||
ConfigError: 未安装 ddddocr
|
||||
"""
|
||||
if not png:
|
||||
raise CaptchaError("验证码图片为空")
|
||||
engine = _load_engine()
|
||||
|
||||
best: Optional[tuple] = None # (置信度, 文本)
|
||||
errors: list = []
|
||||
for variant in _variants(png):
|
||||
try:
|
||||
text, prob = _classify(engine, variant)
|
||||
except Exception as exc: # noqa: BLE001 - 引擎内部异常
|
||||
errors.append(str(exc))
|
||||
continue
|
||||
try:
|
||||
code = normalize(text, length=length)
|
||||
except CaptchaError:
|
||||
continue # 该变体位数不对,换下一个
|
||||
if best is None or prob > best[0]:
|
||||
best = (prob, code)
|
||||
if best is not None:
|
||||
return best[1]
|
||||
detail = f";引擎报错:{errors[0]}" if errors else ""
|
||||
raise CaptchaError(f"验证码识别失败:所有变体均未得到 {length} 位结果{detail}")
|
||||
|
||||
|
||||
def recognize_data_url(text: str, *, length: int = 4) -> str:
|
||||
"""识别 ``data:image/...;base64,...`` 形式的验证码。"""
|
||||
return recognize(decode_data_url(text), length=length)
|
||||
|
||||
|
||||
__all__ = ["decode_data_url", "normalize", "recognize", "recognize_data_url"]
|
||||
@@ -0,0 +1,204 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CRM 接口通用客户端:请求、``code=S0`` 信封校验、分页、下载。
|
||||
|
||||
只做「机制」:不内置任何业务 URL;各接口模块(stores/...)传入地址调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
from .config import (DEFAULT_TIMEOUT, DOWNLOAD_TIMEOUT, MAX_ATTEMPTS, MAX_PAGES,
|
||||
SESSION_EXPIRED_CODES, SUCCESS_CODE, USER_AGENT, XHR_HEADERS)
|
||||
from .errors import ApiError, ConfigError, CrmError, SessionExpiredError
|
||||
from .session import SessionLike, looks_like_login_page
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
|
||||
class CrmClient:
|
||||
"""借来的会话 + 通用请求能力。
|
||||
|
||||
Args:
|
||||
session: 宿主注入的会话(``ctx.get_session("crm")``)或 :func:`session.build_session` 的产物
|
||||
timeout: 普通请求超时(秒)
|
||||
retries: 重试次数(含首次,默认 3);登录态失效与业务错误不重试
|
||||
log: 日志回调(默认静默)
|
||||
"""
|
||||
|
||||
def __init__(self, session: SessionLike, *, timeout: Optional[float] = None,
|
||||
retries: Optional[int] = None, log: Optional[LOGGER] = None) -> None:
|
||||
if session is None:
|
||||
raise ConfigError("会话不能为空:插件里请用 ctx.get_session('crm')")
|
||||
self.session = session
|
||||
self.timeout = float(timeout if timeout is not None else DEFAULT_TIMEOUT)
|
||||
self.retries = max(1, int(retries if retries is not None else MAX_ATTEMPTS))
|
||||
self.log: LOGGER = log or (lambda msg: None)
|
||||
|
||||
# ---------------- 底层 ----------------
|
||||
def _headers(self, headers: Optional[dict]) -> dict:
|
||||
merged = dict(XHR_HEADERS)
|
||||
merged.setdefault("User-Agent", USER_AGENT)
|
||||
merged.update(headers or {})
|
||||
return merged
|
||||
|
||||
def get(self, url: str, *, params: Optional[dict] = None,
|
||||
timeout: Optional[float] = None, headers: Optional[dict] = None):
|
||||
return self.session.get(url, params=params, headers=self._headers(headers),
|
||||
timeout=timeout or self.timeout)
|
||||
|
||||
def post(self, url: str, *, data: Optional[dict] = None,
|
||||
json_body: Optional[dict] = None, params: Optional[dict] = None,
|
||||
timeout: Optional[float] = None, headers: Optional[dict] = None):
|
||||
kwargs: Dict[str, Any] = {"params": params, "headers": self._headers(headers),
|
||||
"timeout": timeout or self.timeout}
|
||||
if json_body is not None:
|
||||
kwargs["json"] = json_body
|
||||
else:
|
||||
kwargs["data"] = data if data is not None else {}
|
||||
return self.session.post(url, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def as_json(response, label: str = "", *, allow_list: bool = False):
|
||||
"""响应 → dict(``allow_list`` 时也接受裸数组);HTML/登录页视为登录态失效。
|
||||
|
||||
HTTP 语义(实测):
|
||||
|
||||
* ``401`` → 登录态失效(CRM 的未认证就是 401 + ``code=E401``);
|
||||
* ``403`` → **无权限**(如某报表账号未开通),不是登录失效,不能触发重登;
|
||||
"""
|
||||
if response.status_code == 401:
|
||||
raise SessionExpiredError(
|
||||
f"{label or '接口'}未认证(HTTP 401),请重新登录 CRM")
|
||||
if response.status_code == 403:
|
||||
payload = None
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
pass
|
||||
message = str((payload or {}).get("message") or "无权限")[:200]
|
||||
code = str((payload or {}).get("code") or "E403")
|
||||
raise ApiError(f"{label or '接口'}无权限(HTTP 403):{message}",
|
||||
code=code, payload=payload)
|
||||
text = (response.text or "").strip()
|
||||
if looks_like_login_page(text):
|
||||
raise SessionExpiredError(
|
||||
f"{label or '接口'}返回非 JSON(登录态可能已失效):{text[:120]}")
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
raise ApiError(f"{label or '接口'}响应不是 JSON:{text[:200]}") from None
|
||||
if isinstance(data, dict) or (allow_list and isinstance(data, list)):
|
||||
return data
|
||||
raise ApiError(f"{label or '接口'}响应结构异常:{text[:200]}")
|
||||
|
||||
def request_json(self, method: str, url: str, *, params=None, data: Optional[dict] = None,
|
||||
json_body: Optional[dict] = None, timeout: Optional[float] = None,
|
||||
label: str = "", allow_list: bool = False):
|
||||
"""带重试的 JSON 请求;登录态失效/业务错误不重试。"""
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, self.retries + 1):
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = self.get(url, params=params, timeout=timeout)
|
||||
else:
|
||||
resp = self.post(url, data=data, json_body=json_body,
|
||||
params=params, timeout=timeout)
|
||||
if resp.status_code >= 500:
|
||||
raise CrmError(f"{label or '接口'}服务端 {resp.status_code}")
|
||||
return self.as_json(resp, label, allow_list=allow_list)
|
||||
except (SessionExpiredError, ApiError, ConfigError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - 网络抖动重试
|
||||
last = exc
|
||||
if attempt >= self.retries:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
self.log(f"[WARN] {label or '接口'}第 {attempt} 次失败:{exc};{delay:.0f}s 后重试")
|
||||
time.sleep(delay)
|
||||
raise CrmError(f"{label or '接口'}请求失败(重试 {self.retries} 次):{last}")
|
||||
|
||||
# ---------------- 业务信封 ----------------
|
||||
def check_code(self, data: dict, label: str = "") -> dict:
|
||||
"""校验 CRM 信封 ``code == 'S0'``;未认证转 :class:`SessionExpiredError`。"""
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(f"{label or '接口'}响应结构异常:{str(data)[:200]}")
|
||||
code = str(data.get("code") or "").strip()
|
||||
if code == SUCCESS_CODE:
|
||||
return data
|
||||
message = str(data.get("message") or data.get("msg") or data)[:300]
|
||||
if code.upper() in SESSION_EXPIRED_CODES:
|
||||
raise SessionExpiredError(f"{label or '接口'}登录态失效({code}):{message}")
|
||||
raise ApiError(f"{label or '接口'}返回错误:{message}", code=code, payload=data)
|
||||
|
||||
def call(self, method: str, url: str, *, params=None, data: Optional[dict] = None,
|
||||
json_body: Optional[dict] = None, timeout: Optional[float] = None,
|
||||
label: str = "") -> Any:
|
||||
"""请求 + 校验,返回信封里的 ``data`` 字段。"""
|
||||
envelope = self.request_json(method, url, params=params, data=data,
|
||||
json_body=json_body, timeout=timeout, label=label)
|
||||
self.check_code(envelope, label)
|
||||
return envelope.get("data")
|
||||
|
||||
# ---------------- 分页 ----------------
|
||||
def paginate(self, fetch_page: Callable[[int, int], Tuple[List[dict], bool]], *,
|
||||
page_size: int = 200, max_pages: int = MAX_PAGES,
|
||||
sleep: float = 0.2) -> List[dict]:
|
||||
"""通用分页:``fetch_page(page_no, page_size) -> (rows, has_more)``。"""
|
||||
rows: List[dict] = []
|
||||
for page_no in range(1, max_pages + 1):
|
||||
page_rows, has_more = fetch_page(page_no, page_size)
|
||||
rows.extend(page_rows or [])
|
||||
if not has_more or not page_rows:
|
||||
break
|
||||
if sleep:
|
||||
time.sleep(sleep)
|
||||
return rows
|
||||
|
||||
# ---------------- 文件 ----------------
|
||||
def download(self, url: str, *, save_dir: str = "", filename: str = "",
|
||||
params: Optional[dict] = None, timeout: Optional[float] = None) -> str:
|
||||
"""下载到本地,返回绝对路径(大报表统一走这里,避免插件各写一份)。
|
||||
|
||||
文件名优先级:``filename`` > 响应 ``Content-Disposition`` 原名 > URL 末段。
|
||||
CRM 导出的文件名在头部且是 URL 编码的中文,直接取 URL 末段会得到 ``export``。
|
||||
"""
|
||||
resp = self.session.get(url, params=params,
|
||||
timeout=timeout or DOWNLOAD_TIMEOUT,
|
||||
headers=self._headers(None))
|
||||
if resp.status_code != 200 or not resp.content:
|
||||
raise CrmError(f"下载失败:HTTP {resp.status_code},{len(resp.content or b'')} 字节")
|
||||
name = (filename
|
||||
or self._filename_from_disposition(
|
||||
resp.headers.get("content-disposition") or "")
|
||||
or os.path.basename(url.split("?", 1)[0])
|
||||
or "download.bin")
|
||||
name = "".join(ch for ch in name if ch not in '\\/:*?"<>|').strip() or "download.bin"
|
||||
target_dir = save_dir or os.getcwd()
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
path = os.path.abspath(os.path.join(target_dir, name))
|
||||
with open(path, "wb") as fp:
|
||||
fp.write(resp.content)
|
||||
self.log(f"[INFO] 已下载:{path}({len(resp.content)} 字节)")
|
||||
return path
|
||||
|
||||
@staticmethod
|
||||
def _filename_from_disposition(header: str) -> str:
|
||||
"""从 ``Content-Disposition`` 取文件名(兼容 ``filename*=UTF-8''`` 与 URL 编码)。"""
|
||||
if not header:
|
||||
return ""
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
match = re.search(r"filename\*\s*=\s*([^']*)''([^;]+)", header, re.I)
|
||||
if match:
|
||||
return urllib.parse.unquote(match.group(2).strip().strip('"'))
|
||||
match = re.search(r'filename\s*=\s*"?([^";]+)"?', header, re.I)
|
||||
if match:
|
||||
return urllib.parse.unquote(match.group(1).strip())
|
||||
return ""
|
||||
|
||||
|
||||
__all__ = ["CrmClient"]
|
||||
@@ -0,0 +1,182 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CRM(crm.37du.co)协议事实常量与运行路径。
|
||||
|
||||
设计原则:**这里只放服务端协议事实与落盘位置**——域名、路径、成功码、重试次数、
|
||||
会话文件命名;业务语义(导出哪些报表、门店归属规则、文案)一律留在插件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
# ==================== 域名与接口 ====================
|
||||
#: CRM 站点根(可用环境变量 CRM_BASE_URL 覆盖,便于指向测试环境)
|
||||
CRM_BASE_URL = (os.getenv("CRM_BASE_URL") or "https://crm.37du.co").rstrip("/")
|
||||
CRM_SITE_URL = CRM_BASE_URL + "/"
|
||||
#: SPA hash 路由登录页
|
||||
CRM_LOGIN_URL = CRM_BASE_URL + "/#/login"
|
||||
MEMBERSHIP = CRM_BASE_URL + "/membership"
|
||||
#: 会话校验接口:有效返回 ``{"code":"S0","success":true,...}``
|
||||
USER_URL = MEMBERSHIP + "/main/user"
|
||||
#: 当前账号可授权的品牌-门店树(GET,无查询参数,两层结构 品牌→门店)
|
||||
BRAND_SHOPS_URL = MEMBERSHIP + "/common/getAuthorizedBrandShops"
|
||||
#: 全部品牌(GET,无查询参数,扁平结构 ``[{value,label}]``)——不限于本账号授权
|
||||
ALL_BRANDS_URL = MEMBERSHIP + "/common/getAllBrand"
|
||||
#: 账号密码登录:表单 POST,字段 username / password / captchaCode(密码明文)
|
||||
LOGIN_URL = MEMBERSHIP + "/login"
|
||||
#: 验证码:GET,返回 ``{"data":"data:image/png;base64,...","success":true}``
|
||||
CAPTCHA_URL = MEMBERSHIP + "/common/verifyCaptcha"
|
||||
#: 退出(GET,无参数)
|
||||
LOGOUT_URL = MEMBERSHIP + "/logout"
|
||||
CRM_DOMAIN = "crm.37du.co"
|
||||
#: Cookie 域过滤:浏览器里 CRM 会话可能挂在 ``.37du.co`` 或 ``.crm.37du.co`` 下
|
||||
COOKIE_DOMAIN_FILTER = "37du.co"
|
||||
#: hash 片段含该词即仍停在登录页
|
||||
LOGIN_PAGE_KEYWORD = "login"
|
||||
|
||||
# ==================== 服务端信封 ====================
|
||||
#: 业务成功码
|
||||
SUCCESS_CODE = "S0"
|
||||
#: 需要单独识别为「登录态失效」的码(HTTP 200 也会出现)
|
||||
SESSION_EXPIRED_CODES = ("E401", "E403")
|
||||
#: 验证码错误(换新会话重试即可)
|
||||
CODE_CAPTCHA_WRONG = "E50002"
|
||||
#: 验证码为空
|
||||
CODE_CAPTCHA_EMPTY = "E50004"
|
||||
#: 本会话已提交过一次登录,必须换新会话
|
||||
CODE_DUPLICATE_SUBMIT = "E1006"
|
||||
#: 用户不存在(识别率自测的探针账号就靠它区分「验证码对了」)
|
||||
CODE_USER_NOT_FOUND = "E10001"
|
||||
|
||||
# ==================== 账号密码登录(验证码 OCR) ====================
|
||||
#: 验证码位数(实测 4 位字母数字,服务端不区分大小写)
|
||||
CAPTCHA_LENGTH = 4
|
||||
#: 登录尝试次数:每次换新会话 + 新验证码(一个会话只能提交一次)。
|
||||
#: **刻意压到 3 次**:连续失败登录是风控特征,宁可失败让上层决定,也不要刷请求。
|
||||
PASSWORD_LOGIN_ATTEMPTS = 3
|
||||
#: 两次尝试之间的间隔(秒):避免连续 POST 形成明显的机器请求节奏
|
||||
PASSWORD_RETRY_DELAY = 1.5
|
||||
#: 凭证来源①:环境变量(优先级最高,便于执行机按账号注入)
|
||||
CRM_USERNAME = (os.getenv("CRM_USERNAME") or "").strip()
|
||||
CRM_PASSWORD = os.getenv("CRM_PASSWORD") or ""
|
||||
|
||||
# ==================== 默认值与重试 ====================
|
||||
DEFAULT_TIMEOUT = 30.0 # 普通请求超时(秒)
|
||||
DOWNLOAD_TIMEOUT = 180.0 # 大报表下载超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数(含首次)
|
||||
MAX_PAGES = 500 # 分页保护上限
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
#: 接口请求头(服务端按 XHR 处理,缺 Referer 会被判非正常来源)
|
||||
XHR_HEADERS = {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": CRM_SITE_URL,
|
||||
}
|
||||
|
||||
# ==================== 浏览器登录参数 ====================
|
||||
SCAN_WAIT = 300 # 等待人工钉钉扫码的上限(秒)
|
||||
LOGIN_SETTLE = 8 # 登录成功后等首屏请求结束再抓 Cookie(过早快照会被轮换作废)
|
||||
PROFILE_REUSE_WAIT = 10 # 浏览器 profile 残留会话 / 静默重登的观察窗口(秒)
|
||||
HEADLESS = False # 扫码兜底需可见浏览器
|
||||
|
||||
# ==================== 运行数据与会话文件 ====================
|
||||
#: 显式指定 cookies 文件时优先(宿主注入场景)
|
||||
COOKIES_FILE = (os.getenv("CRM_COOKIES_FILE") or "").strip()
|
||||
|
||||
|
||||
def app_data_dir() -> str:
|
||||
"""运行数据根:``%LOCALAPPDATA%\\37duAutomation``。"""
|
||||
base = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or os.path.expanduser("~")
|
||||
return os.path.join(base, "37duAutomation")
|
||||
|
||||
|
||||
def resolve_account(account: str = "") -> str:
|
||||
"""账号取入参 > 环境变量 ``PLATFORM_ACCOUNT`` > 空(共享目录)。"""
|
||||
return (account or os.getenv("PLATFORM_ACCOUNT") or "").strip()
|
||||
|
||||
|
||||
def sessions_dir(account: str = "") -> str:
|
||||
"""会话根目录;有账号时按账号隔离(与壳子 ``.sessions/<账号>/`` 对齐)。"""
|
||||
base = os.path.join(app_data_dir(), ".sessions")
|
||||
acc = resolve_account(account)
|
||||
return os.path.join(base, acc) if acc else base
|
||||
|
||||
|
||||
def cookies_file(account: str = "") -> str:
|
||||
"""浏览器导出的 cookies 列表(JSON 数组)。"""
|
||||
if COOKIES_FILE:
|
||||
return COOKIES_FILE
|
||||
return os.path.join(sessions_dir(account), "crm_cookies.json")
|
||||
|
||||
|
||||
def cookie_header_file(account: str = "") -> str:
|
||||
"""浏览器实际发送的 Cookie 头原文(requests 复放的权威来源)。"""
|
||||
return os.path.join(sessions_dir(account), "crm_cookie_header.txt")
|
||||
|
||||
|
||||
def token_file(account: str = "") -> str:
|
||||
"""localStorage / sessionStorage 票据快照。"""
|
||||
return os.path.join(sessions_dir(account), "crm_tokens.json")
|
||||
|
||||
|
||||
def credentials_file(account: str = "") -> str:
|
||||
"""账号密码凭证文件(JSON:``{"username": "...", "password": "..."}``)。
|
||||
|
||||
与环境变量并存:环境变量优先,便于执行机按账号注入;文件适合单机长期存放。
|
||||
文件权限由部署侧控制,SDK 不做加密。
|
||||
"""
|
||||
return os.path.join(sessions_dir(account), "crm_credentials.json")
|
||||
|
||||
|
||||
def browser_profile_dir(account: str = "") -> str:
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不与日常 Chrome 抢配置。"""
|
||||
name = "crm_" + resolve_account(account) if resolve_account(account) else "crm"
|
||||
return os.path.join(app_data_dir(), "browser_sessions", name)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"CAPTCHA_LENGTH",
|
||||
"CAPTCHA_URL",
|
||||
"CODE_CAPTCHA_EMPTY",
|
||||
"CODE_CAPTCHA_WRONG",
|
||||
"CODE_DUPLICATE_SUBMIT",
|
||||
"CODE_USER_NOT_FOUND",
|
||||
"COOKIE_DOMAIN_FILTER",
|
||||
"COOKIES_FILE",
|
||||
"CRM_BASE_URL",
|
||||
"CRM_DOMAIN",
|
||||
"CRM_LOGIN_URL",
|
||||
"CRM_PASSWORD",
|
||||
"CRM_SITE_URL",
|
||||
"CRM_USERNAME",
|
||||
"DEFAULT_TIMEOUT",
|
||||
"DOWNLOAD_TIMEOUT",
|
||||
"HEADLESS",
|
||||
"LOGIN_PAGE_KEYWORD",
|
||||
"LOGIN_SETTLE",
|
||||
"LOGIN_URL",
|
||||
"LOGOUT_URL",
|
||||
"MAX_ATTEMPTS",
|
||||
"MAX_PAGES",
|
||||
"MEMBERSHIP",
|
||||
"PASSWORD_LOGIN_ATTEMPTS",
|
||||
"PASSWORD_RETRY_DELAY",
|
||||
"PROFILE_REUSE_WAIT",
|
||||
"SCAN_WAIT",
|
||||
"SESSION_EXPIRED_CODES",
|
||||
"SUCCESS_CODE",
|
||||
"USER_AGENT",
|
||||
"USER_URL",
|
||||
"XHR_HEADERS",
|
||||
"app_data_dir",
|
||||
"browser_profile_dir",
|
||||
"cookie_header_file",
|
||||
"cookies_file",
|
||||
"credentials_file",
|
||||
"resolve_account",
|
||||
"sessions_dir",
|
||||
"token_file",
|
||||
]
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""crm_sdk 异常体系:插件只需捕获 :class:`CrmError` 即可覆盖全部 SDK 错误。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class CrmError(Exception):
|
||||
"""所有 CRM SDK 异常的基类。"""
|
||||
|
||||
|
||||
class ConfigError(CrmError):
|
||||
"""配置/入参问题(缺文件、空会话、非法参数)。"""
|
||||
|
||||
|
||||
class AuthError(CrmError):
|
||||
"""登录态获取失败(扫码超时、Cookie 落盘无效)。"""
|
||||
|
||||
|
||||
class CaptchaError(CrmError):
|
||||
"""验证码识别失败(图片为空、结果长度不符、引擎异常)。
|
||||
|
||||
属于**可重试**错误:换一张验证码重新识别即可,不应让任务失败。
|
||||
"""
|
||||
|
||||
|
||||
class SessionExpiredError(CrmError):
|
||||
"""服务端判定未登录(HTTP 401 / ``code`` 为 E401、E403)。"""
|
||||
|
||||
|
||||
class ApiError(CrmError):
|
||||
"""业务失败:``code`` 非 S0。
|
||||
|
||||
Attributes:
|
||||
code: 服务端错误码(如 ``E500``)
|
||||
payload: 完整响应体,便于插件定位
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, code: str = "", payload: Optional[Any] = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.payload = payload
|
||||
|
||||
|
||||
__all__ = ["ApiError", "AuthError", "CaptchaError", "ConfigError", "CrmError",
|
||||
"SessionExpiredError"]
|
||||
@@ -0,0 +1,315 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报表接口:列表查询与导出。
|
||||
|
||||
来源:前端 ``src/api/setting.ts`` 的声明式接口表(38 组 list/export 成对),
|
||||
已用真实登录态验证过若干组(见 README 的验证记录)。**只做机制**:
|
||||
分页、响应形态兼容、下载落盘、文件名还原;查哪些报表、怎么用数据、落哪个目录,
|
||||
全部留给插件。
|
||||
|
||||
两种响应形态(实测,必须都兼容)::
|
||||
|
||||
{data: {list: [...], total: 120}} # 分页型,如 unionPay / groupPay
|
||||
{data: [...]} # 直返数组型,如 posPay / debitCard
|
||||
|
||||
导出接口返回二进制 Excel(``application/vnd.ms-excel``),
|
||||
文件名在 ``Content-Disposition`` 里且是 URL 编码的中文。
|
||||
|
||||
典型用法::
|
||||
|
||||
from crm_sdk import CrmClient, auth, reports
|
||||
|
||||
client = CrmClient(auth.build_session())
|
||||
rows = reports.list_all(client, "unionPay", reportDate="2026-11-25")
|
||||
path = reports.export(client, "unionPay", reportDate="2026-11-25",
|
||||
save_dir=r"D:\\报表")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from .config import CRM_BASE_URL
|
||||
from .client import CrmClient
|
||||
from .errors import ApiError, ConfigError, CrmError, SessionExpiredError
|
||||
|
||||
#: 报表接口前缀
|
||||
_PREFIX = "/membership/report"
|
||||
|
||||
|
||||
def _spec(title: str, slug: str, *, list_path: str = "", export_path: str = "",
|
||||
list_suffix: str = "list", export_suffix: str = "export",
|
||||
list_method: str = "get",
|
||||
extra_exports: Optional[Dict[str, str]] = None) -> dict:
|
||||
"""构造一条报表描述(路径都补全成绝对路径)。"""
|
||||
base = f"{_PREFIX}/{slug}"
|
||||
return {
|
||||
"title": title,
|
||||
"list": list_path or f"{base}/{list_suffix}",
|
||||
"export": export_path or f"{base}/{export_suffix}",
|
||||
# 个别报表的 list 只接受 POST(GET 直接 400 Request method 'GET' is not supported)
|
||||
"list_method": list_method.lower(),
|
||||
"extra_exports": extra_exports or {},
|
||||
}
|
||||
|
||||
|
||||
#: 报表注册表:key 即插件里用的名字
|
||||
REPORTS: Dict[str, dict] = {
|
||||
# ---- 支付/账单类 ----
|
||||
"groupPay": _spec("团购支付", "groupPay"),
|
||||
"posPay": _spec("POS支付", "posPay"),
|
||||
"cashPay": _spec("现金支付", "cashPay"),
|
||||
"thirdPayShop": _spec("第三方支付(门店)", "thirdPayShop"),
|
||||
"thirdPayHeadquarters": _spec("第三方支付(总部)", "thirdPayHeadquarters"),
|
||||
"unionPay": _spec("支付数据", "unionPay"),
|
||||
"groupData": _spec("团购数据", "groupData"),
|
||||
"unionPayRefund": _spec("退单统计", "unionPayRefund"),
|
||||
"employeeUnionPay": _spec("员工内部卡消费", "employeeUnionPay"),
|
||||
"orderSubjectAddition": _spec("订单附加属性统计", "orderSubjectAddition"),
|
||||
|
||||
# ---- 储值卡类 ----
|
||||
"debitCard": _spec("储值卡充值", "debitCard"),
|
||||
"debitCardConsume": _spec("储值卡消费", "debitCardConsume"),
|
||||
"debitCardBalance": _spec("储值卡余额", "debitCardBalance"),
|
||||
"depositData": _spec("储值卡线上充值", "depositData"),
|
||||
"abnormalDeposit": _spec("储值卡异常充值", "abnormalDeposit"),
|
||||
"debitCardAbnormal": _spec("储值卡异常消费", "debitCardAbnormal"),
|
||||
"discountCardAbnormal": _spec("打折卡异常消费", "discountCardAbnormal"),
|
||||
"discountCardRecord": _spec("打折卡升级记录", "discountCardRecord"),
|
||||
"consumeOrderDeposit": _spec("储值规则统计", "consumeOrderDeposit"),
|
||||
# 储值记录 / 储值台账 / 储值余额 三个是 debitCard 下的特殊路径
|
||||
"debitCardDeposit": _spec("储值记录", "debitCard",
|
||||
list_path=f"{_PREFIX}/debitCard/depositList",
|
||||
export_path=f"{_PREFIX}/debitCard/depositExport"),
|
||||
"debitCardAccountBook": _spec(
|
||||
"储值台账", "debitCard",
|
||||
list_path=f"{_PREFIX}/debitCard/balanceAccountBookList",
|
||||
export_path=f"{_PREFIX}/debitCard/balanceAccountBookExport"),
|
||||
"debitCardMemberBalance": _spec(
|
||||
"储值余额", "debitCard",
|
||||
list_path=f"{_PREFIX}/debitCard/memberBalanceList",
|
||||
export_path=f"{_PREFIX}/debitCard/memberBalanceExport"),
|
||||
|
||||
# ---- 员工/业绩类 ----
|
||||
"comprehensivePerformance": _spec("技师综合业绩", "comprehensivePerformance"),
|
||||
"employeeWork": _spec("技师上钟数据", "employeeWork"),
|
||||
"employeeWorkRank": _spec("技师上钟数据排名", "employeeWorkRank"),
|
||||
"employeeSpecialWork": _spec("技师点钟数据", "employeeSpecialWork"),
|
||||
"consumeSubjectCount": _spec("消费项目统计", "consumeSubjectCount",
|
||||
extra_exports={"details": f"{_PREFIX}/consumeSubjectCount/exportDetails"}),
|
||||
|
||||
# ---- 霸王餐 ----
|
||||
"overlordOrderDeposit": _spec("霸王餐充值明细", "overlordOrderDeposit"),
|
||||
"overlordOrderConsume": _spec("霸王餐消费明细", "overlordOrderConsume"),
|
||||
"overlordOrderBalance": _spec("霸王餐余额查询", "overlordOrderBalance"),
|
||||
|
||||
# ---- 小程序 / 留宿 ----
|
||||
"miniProgramOrder": _spec("小程序订单", "miniProgramOrder"),
|
||||
"miniProgramPay": _spec("小程序收入", "miniProgramPay"),
|
||||
"overnightSettlement": _spec("留宿结算", "overnightSettlement"),
|
||||
|
||||
# ---- 第三方平台 ----
|
||||
"taobaoTicket": _spec("淘宝订单数据", "taobaoTicket"),
|
||||
"weimengValidate": _spec("微盟核销统计", "weimeng",
|
||||
list_path=f"{_PREFIX}/weimeng/listValidate",
|
||||
export_path=f"{_PREFIX}/weimeng/exportValidate"),
|
||||
"weimengValidateSum": _spec("微盟核销汇总", "weimeng",
|
||||
list_path=f"{_PREFIX}/weimeng/listValidateSum",
|
||||
export_path=f"{_PREFIX}/weimeng/exportValidateSum"),
|
||||
"weimengFundsSum": _spec("微盟资金汇总", "weimeng",
|
||||
list_path=f"{_PREFIX}/weimeng/listFundsSum",
|
||||
export_path=f"{_PREFIX}/weimeng/exportFundsSum"),
|
||||
|
||||
# ---- 会员券(不在 report 前缀下,且 list 只接受 POST)----
|
||||
"memberCoupon": _spec("会员优惠券", "memberCoupon",
|
||||
list_path="/membership/memberCoupon/report/list",
|
||||
export_path="/membership/memberCoupon/report/export",
|
||||
list_method="post"),
|
||||
}
|
||||
|
||||
|
||||
def names() -> List[str]:
|
||||
"""全部报表 key(可直接传给 :func:`list_all` / :func:`export`)。"""
|
||||
return sorted(REPORTS)
|
||||
|
||||
|
||||
def titles() -> Dict[str, str]:
|
||||
"""key → 中文标题。"""
|
||||
return {k: v["title"] for k, v in REPORTS.items()}
|
||||
|
||||
|
||||
def _spec_of(name: str) -> dict:
|
||||
spec = REPORTS.get(name)
|
||||
if spec is None:
|
||||
raise ConfigError(
|
||||
f"未知报表 {name!r};可用:{', '.join(names())}"
|
||||
)
|
||||
return spec
|
||||
|
||||
|
||||
def _url(path: str) -> str:
|
||||
"""相对路径 → 绝对 URL(配置里的 ``CRM_BASE_URL`` 可指向测试环境)。"""
|
||||
return CRM_BASE_URL + path
|
||||
|
||||
|
||||
# ==================== 列表 ====================
|
||||
def _as_int(value) -> Optional[int]:
|
||||
"""把后端返回的计数(可能是数字也可能是字符串)转成 int;不可解析返回 None。"""
|
||||
if isinstance(value, bool) or value is None:
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
return int(value)
|
||||
text = str(value).strip()
|
||||
return int(text) if text.isdigit() else None
|
||||
|
||||
|
||||
def _fetch_page(client, name: str, page_no: int, page_size: int,
|
||||
**params) -> Tuple[List[dict], Optional[int], bool]:
|
||||
"""取一页,返回 ``(rows, total, has_more)``;``total`` 仅分页型有。"""
|
||||
spec = _spec_of(name)
|
||||
query: Dict[str, Any] = dict(params)
|
||||
query.setdefault("pageNum", page_no)
|
||||
query.setdefault("pageSize", page_size)
|
||||
url = _url(spec["list"])
|
||||
label = f"报表 {name} 列表"
|
||||
if spec["list_method"] == "post":
|
||||
data = client.request_json("POST", url, data=query, label=label)
|
||||
else:
|
||||
data = client.request_json("GET", url, params=query, label=label)
|
||||
client.check_code(data, label)
|
||||
payload = data.get("data")
|
||||
|
||||
if isinstance(payload, dict):
|
||||
rows = list(payload.get("list") or [])
|
||||
total = _as_int(payload.get("total"))
|
||||
has_more = (total is not None and page_no * page_size < total) \
|
||||
or (total is None and len(rows) >= page_size)
|
||||
return rows, total, has_more
|
||||
|
||||
if isinstance(payload, list):
|
||||
# 直返数组型:服务端不分页,一次就是全量
|
||||
return list(payload), len(payload), False
|
||||
|
||||
raise ApiError(f"报表 {name} 返回结构不支持:{str(payload)[:200]}",
|
||||
payload=data)
|
||||
|
||||
|
||||
def list_page(client, name: str, page_no: int = 1, page_size: int = 200,
|
||||
*, extra: str = "", **params) -> Tuple[List[dict], bool]:
|
||||
"""取一页数据,返回 ``(rows, has_more)``。
|
||||
|
||||
同时兼容两种响应形态:
|
||||
|
||||
* ``{list, total}``:按 ``total`` 判断是否还有下一页;
|
||||
* 裸数组:服务端一次返回全量,``has_more`` 恒为 False。
|
||||
|
||||
请求方法按报表配置走(绝大多数 GET,``memberCoupon`` 是 POST)。
|
||||
"""
|
||||
rows, _total, has_more = _fetch_page(client, name, page_no, page_size, **params)
|
||||
return rows, has_more
|
||||
|
||||
|
||||
def query(client, name: str, *, page_size: int = 20, **params) -> dict:
|
||||
"""「先查询」:用导出将用的同一批参数查一页,拿总量与样本。
|
||||
|
||||
Returns:
|
||||
``{"total": int|None, "rows": [...], "has_more": bool}``
|
||||
|
||||
为什么需要它:
|
||||
* 有的报表**不传条件会导出全表**(实测 ``debitCardMemberBalance``
|
||||
无参数导出 70,200 行),先查一眼总量再决定导不导;
|
||||
* 查询能第一时间暴露权限问题(如 ``memberCoupon`` 对无权限账号 403),
|
||||
比下载到一半失败更早;
|
||||
* 参数拼错时查询就报错,不用等到文件下来才发现为空。
|
||||
"""
|
||||
rows, total, has_more = _fetch_page(client, name, 1, page_size, **params)
|
||||
return {"total": total, "rows": rows, "has_more": has_more}
|
||||
|
||||
|
||||
def list_all(client, name: str, *, page_size: int = 200, max_pages: int = 200,
|
||||
sleep: float = 0.2, **params) -> List[dict]:
|
||||
"""按页取全量(直返数组型只会请求一次)。"""
|
||||
return client.paginate(
|
||||
lambda page_no, size: list_page(client, name, page_no, size, **params),
|
||||
page_size=page_size, max_pages=max_pages, sleep=sleep)
|
||||
|
||||
|
||||
# ==================== 导出 ====================
|
||||
def export(client, name: str, *, save_dir: str = "", filename: str = "",
|
||||
timeout: Optional[float] = None, extra: str = "",
|
||||
query_first: bool = False, max_rows: Optional[int] = None,
|
||||
**params) -> str:
|
||||
"""导出报表到本地,返回绝对路径。
|
||||
|
||||
Args:
|
||||
name: :data:`REPORTS` 的 key
|
||||
save_dir: 落盘目录(默认当前目录)
|
||||
filename: 指定文件名;不传则用服务端 ``Content-Disposition`` 里的原名
|
||||
extra: 需要走子导出时用(如 ``consumeSubjectCount`` 的 ``details``)
|
||||
query_first: True 时先用**同一批参数**查一页(走 list 接口),确认条件有效、
|
||||
拿到总量后再导;无参数导出全表的情况会被这一步拦住
|
||||
max_rows: 配合 ``query_first``:总量超过该值时拒绝导出并抛 ``ConfigError``,
|
||||
防止误触全表导出
|
||||
**params: 查询参数(``reportDate`` / ``brandId`` / ``shopId`` 等,原样透传)
|
||||
|
||||
Raises:
|
||||
ApiError: 服务端返回 JSON 错误信封(如日期范围超限)
|
||||
SessionExpiredError: 登录态失效
|
||||
CrmError: 非 Excel 响应或落盘失败
|
||||
ConfigError: ``query_first`` 查出超量 / 无数据
|
||||
"""
|
||||
spec = _spec_of(name)
|
||||
path = spec["extra_exports"].get(extra) if extra else spec["export"]
|
||||
if not path:
|
||||
raise ConfigError(f"报表 {name} 没有名为 {extra!r} 的子导出")
|
||||
|
||||
if query_first:
|
||||
probe = query(client, name, **params)
|
||||
total = probe.get("total")
|
||||
client.log(f"[INFO] 先查询 {name}:total={total} 首行字段={len(probe.get('rows') or [])}")
|
||||
if total == 0:
|
||||
raise ConfigError(f"报表 {name} 在当前条件下没有数据,不导出")
|
||||
if max_rows is not None and total is not None and total > max_rows:
|
||||
raise ConfigError(
|
||||
f"报表 {name} 命中 {total} 行,超过 max_rows={max_rows};"
|
||||
"请收窄条件(日期/门店)后再导")
|
||||
|
||||
url = _url(path)
|
||||
resp = client.session.get(url, params=params, timeout=timeout or 180,
|
||||
headers=client._headers(None))
|
||||
if resp.status_code in (401, 403):
|
||||
raise SessionExpiredError(f"报表 {name} 导出未认证(HTTP {resp.status_code})")
|
||||
if resp.status_code != 200:
|
||||
raise CrmError(f"报表 {name} 导出失败:HTTP {resp.status_code}")
|
||||
|
||||
ctype = (resp.headers.get("content-type") or "").lower()
|
||||
if "json" in ctype: # 服务端把错误当 200 返回
|
||||
try:
|
||||
envelope = resp.json()
|
||||
except ValueError:
|
||||
envelope = {}
|
||||
client.check_code(envelope, f"报表 {name} 导出")
|
||||
raise ApiError(f"报表 {name} 导出返回 JSON 而非文件:{resp.text[:200]}",
|
||||
payload=envelope)
|
||||
|
||||
content = resp.content or b""
|
||||
if not content:
|
||||
raise CrmError(f"报表 {name} 导出内容为空")
|
||||
|
||||
fname = (filename
|
||||
or CrmClient._filename_from_disposition(resp.headers.get("content-disposition") or "")
|
||||
or f"{name}.xlsx")
|
||||
# 去掉文件名里 Windows 不接受的字符
|
||||
fname = "".join(ch for ch in fname if ch not in '\\/:*?"<>|').strip() or f"{name}.xlsx"
|
||||
target_dir = save_dir or os.getcwd()
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
out = os.path.abspath(os.path.join(target_dir, fname))
|
||||
with open(out, "wb") as fp:
|
||||
fp.write(content)
|
||||
client.log(f"[INFO] 报表 {name} 已导出:{out}({len(content)} 字节)")
|
||||
return out
|
||||
|
||||
|
||||
__all__ = ["REPORTS", "export", "list_all", "list_page", "names", "query", "titles"]
|
||||
@@ -0,0 +1,136 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""借用会话(SessionLike)与离线 Cookie 构造。
|
||||
|
||||
**SDK 不替插件编排业务**:宿主(执行机壳 / 登录子进程)已经建立登录态时,插件直接
|
||||
``CrmClient(ctx.get_session("crm"))``;只有 CLI、agent、无宿主脚本才用本模块从落盘
|
||||
文件构造会话。SDK 从不 ``close()`` 借来的 session。
|
||||
|
||||
两个关键事实(踩过坑):
|
||||
1. CRM 的 ``x-token`` 会在轮换期并存新旧两条同名 Cookie,requests 的 CookieJar 按
|
||||
``(domain, path, name)`` 去重会把新的盖成旧的 → 必须整条 Cookie 头原样复放;
|
||||
2. Cookie 头失效但 ``crm_cookies.json`` 仍完好时,按原始顺序重建即可自愈。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, List, Optional, Protocol, runtime_checkable
|
||||
|
||||
import requests
|
||||
|
||||
from .config import (COOKIE_DOMAIN_FILTER, CRM_SITE_URL, USER_AGENT, cookies_file,
|
||||
cookie_header_file, resolve_account)
|
||||
from .errors import ConfigError
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SessionLike(Protocol):
|
||||
"""借来的会话契约(requests.Session 天然满足)。"""
|
||||
|
||||
cookies: Any
|
||||
headers: Any
|
||||
|
||||
def get(self, url, **kwargs): ... # noqa: D401,E704
|
||||
|
||||
def post(self, url, **kwargs): ...
|
||||
|
||||
|
||||
def looks_like_login_page(text: Optional[str]) -> bool:
|
||||
"""接口正常返回 JSON;登录页/错误页(HTML)视为登录态过期。"""
|
||||
return bool(text) and not str(text).lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def read_cookies(path: str = "", *, account: str = "",
|
||||
domain_filter: str = COOKIE_DOMAIN_FILTER) -> List[dict]:
|
||||
"""读取落盘 Cookie 列表(仅目标域)。
|
||||
|
||||
兼容浏览器导出的 ``[{name,value,domain,path}, ...]`` 与 ``{"cookies": [...]}``。
|
||||
|
||||
Raises:
|
||||
ConfigError: 文件不存在 / 无法解析 / 无可用条目
|
||||
"""
|
||||
cookie_path = path or cookies_file(account)
|
||||
if not cookie_path or not os.path.exists(cookie_path):
|
||||
raise ConfigError(f"未找到 CRM 登录态 cookies:{cookie_path}(请先登录 CRM)")
|
||||
try:
|
||||
with open(cookie_path, encoding="utf-8") as fp:
|
||||
raw = json.load(fp)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ConfigError(f"cookies 文件无法解析:{cookie_path}({exc})") from None
|
||||
items = raw.get("cookies") if isinstance(raw, dict) else raw
|
||||
if not isinstance(items, list) or not items:
|
||||
raise ConfigError(f"cookies 文件为空:{cookie_path}")
|
||||
picked = [c for c in items
|
||||
if isinstance(c, dict) and c.get("name")
|
||||
and (not domain_filter or domain_filter in (c.get("domain") or ""))]
|
||||
if not picked:
|
||||
raise ConfigError(f"cookies 中没有 {domain_filter} 域的条目:{cookie_path}")
|
||||
return picked
|
||||
|
||||
|
||||
def cookie_header_from_cookies(path: str = "", *, account: str = "") -> str:
|
||||
"""按 cookies 文件原始顺序拼 Cookie 头,**保留同名重复项**(轮换期的两个 x-token)。"""
|
||||
pairs = [f'{c["name"]}={c.get("value", "")}' for c in read_cookies(path, account=account)]
|
||||
return "; ".join(pairs)
|
||||
|
||||
|
||||
def read_cookie_header(path: str = "", *, account: str = "") -> Optional[str]:
|
||||
"""读取浏览器捕获的有效 Cookie 头原文;不存在返回 ``None``。"""
|
||||
header_path = path or cookie_header_file(account)
|
||||
if not header_path or not os.path.exists(header_path):
|
||||
return None
|
||||
try:
|
||||
with open(header_path, encoding="utf-8") as fp:
|
||||
return fp.read().strip() or None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _base_session(user_agent: str) -> requests.Session:
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": user_agent,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Referer": CRM_SITE_URL,
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def session_from_header(header: str, *, user_agent: str = USER_AGENT) -> requests.Session:
|
||||
"""用 Cookie 头原文构造会话(推荐:原样复放,不受 CookieJar 去重影响)。"""
|
||||
if not header:
|
||||
raise ConfigError("Cookie 头为空")
|
||||
session = _base_session(user_agent)
|
||||
session.headers["Cookie"] = header.strip()
|
||||
return session
|
||||
|
||||
|
||||
def session_from_cookies(path: str = "", *, account: str = "",
|
||||
user_agent: str = USER_AGENT) -> requests.Session:
|
||||
"""从 cookies JSON 构造会话(仅取 CRM 域 cookies)。
|
||||
|
||||
Raises:
|
||||
ConfigError: 文件不存在或没有可用 cookie
|
||||
"""
|
||||
session = _base_session(user_agent)
|
||||
count = 0
|
||||
for c in read_cookies(path, account=account):
|
||||
session.cookies.set(c["name"], c.get("value", ""),
|
||||
domain=c.get("domain") or None, path=c.get("path", "/"))
|
||||
count += 1
|
||||
if not count:
|
||||
raise ConfigError("cookies 中没有可用条目")
|
||||
return session
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SessionLike",
|
||||
"cookie_header_from_cookies",
|
||||
"looks_like_login_page",
|
||||
"read_cookie_header",
|
||||
"read_cookies",
|
||||
"resolve_account",
|
||||
"session_from_cookies",
|
||||
"session_from_header",
|
||||
]
|
||||
@@ -0,0 +1,221 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""授权品牌-门店树:``GET /membership/common/getAuthorizedBrandShops``。
|
||||
|
||||
服务端返回两层结构(品牌 → 门店),是「内部门店名 ↔ 品牌」的权威字典::
|
||||
|
||||
{"code":"S0","success":true,"data":[
|
||||
{"label":"金色印象","value":10001,
|
||||
"children":[{"label":"北城天街CEO会馆","value":10084}, ...]},
|
||||
{"label":"金色春天","value":10002,
|
||||
"children":[{"label":"广厦经典SPA会馆","value":10106}, ...]}, ...]}
|
||||
|
||||
用法::
|
||||
|
||||
from crm_sdk import CrmClient, stores
|
||||
crm = CrmClient(ctx.get_session("crm"), log=ctx.log)
|
||||
cat = stores.Catalog.load(crm) # 一次请求,后续多次查询
|
||||
cat.brands # ['金色印象', '金色春天', ...]
|
||||
cat.brand_of("北城天街CEO会馆") # '金色印象'
|
||||
cat.shop_id("北城天街CEO会馆") # '10084'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Iterable, List, Optional
|
||||
|
||||
from .config import ALL_BRANDS_URL, BRAND_SHOPS_URL
|
||||
from .errors import ApiError, ConfigError
|
||||
|
||||
LABEL = "授权品牌门店"
|
||||
LABEL_ALL = "全部品牌"
|
||||
|
||||
|
||||
def _sid(value) -> str:
|
||||
"""门店/品牌 ID 统一成字符串(服务端有 int 也有 str,比较时不能混)。"""
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
def tree(client) -> List[dict]:
|
||||
"""拉取原始品牌-门店树(``data`` 数组),不做任何加工。"""
|
||||
data = client.call("GET", BRAND_SHOPS_URL, label=LABEL)
|
||||
if data is None:
|
||||
return []
|
||||
if not isinstance(data, list):
|
||||
raise ApiError(f"{LABEL}响应结构异常:期望数组,实际 {type(data).__name__}")
|
||||
return data
|
||||
|
||||
|
||||
def brands(client) -> List[str]:
|
||||
"""**授权**品牌名列表(服务端顺序)。"""
|
||||
return [_sid(node.get("label")) for node in tree(client) if node.get("label")]
|
||||
|
||||
|
||||
# ==================== 全部品牌(getAllBrand) ====================
|
||||
def all_brands(client) -> List[Dict[str, str]]:
|
||||
"""全部品牌(不限本账号授权范围):``[{"brand": 品牌, "brand_id": 品牌ID}, ...]``。
|
||||
|
||||
与 :func:`brands` 的区别:本函数拉 ``getAllBrand``,返回系统里存在的所有品牌;
|
||||
``brands()`` 拉 ``getAuthorizedBrandShops``,只包含当前账号能看到门店的品牌。
|
||||
|
||||
用途:报表筛选、品牌名反查 ID、排查「为什么某个品牌查不到门店」(未授权)。
|
||||
"""
|
||||
data = client.call("GET", ALL_BRANDS_URL, label=LABEL_ALL)
|
||||
if data is None:
|
||||
return []
|
||||
if not isinstance(data, list):
|
||||
raise ApiError(f"{LABEL_ALL}响应结构异常:期望数组,实际 {type(data).__name__}")
|
||||
out: List[Dict[str, str]] = []
|
||||
for node in data:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
name = _sid(node.get("label"))
|
||||
if name:
|
||||
out.append({"brand": name, "brand_id": _sid(node.get("value"))})
|
||||
return out
|
||||
|
||||
|
||||
def all_brand_names(client) -> List[str]:
|
||||
"""全部品牌名列表。"""
|
||||
return [row["brand"] for row in all_brands(client)]
|
||||
|
||||
|
||||
def brand_id(client, brand_name: str) -> str:
|
||||
"""品牌名 → 品牌 ID(查 ``getAllBrand``);未收录返回空串。"""
|
||||
target = _sid(brand_name)
|
||||
for row in all_brands(client):
|
||||
if row["brand"] == target:
|
||||
return row["brand_id"]
|
||||
return ""
|
||||
|
||||
|
||||
def unauthorized_brands(client) -> List[str]:
|
||||
"""有品牌记录、但本账号没有授权门店的品牌(排查用)。"""
|
||||
authorized = set(brands(client))
|
||||
return [row["brand"] for row in all_brands(client) if row["brand"] not in authorized]
|
||||
|
||||
|
||||
def shops(client, *, brand: str = "") -> List[Dict[str, str]]:
|
||||
"""扁平的授权门店列表;``brand`` 非空时只返回该品牌。
|
||||
|
||||
Returns:
|
||||
``[{"brand": 品牌, "brand_id": 品牌ID, "name": 门店, "shop_id": 门店ID}, ...]``
|
||||
"""
|
||||
out: List[Dict[str, str]] = []
|
||||
for node in tree(client):
|
||||
b_name = _sid(node.get("label"))
|
||||
if brand and b_name != brand:
|
||||
continue
|
||||
for child in (node.get("children") or []):
|
||||
out.append({
|
||||
"brand": b_name,
|
||||
"brand_id": _sid(node.get("value")),
|
||||
"name": _sid(child.get("label")),
|
||||
"shop_id": _sid(child.get("value")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def index(client, *, brand: str = "") -> Dict[str, Dict[str, str]]:
|
||||
"""门店名 → 门店条目(同名取首个,重名见 :attr:`Catalog.duplicates`)。"""
|
||||
return Catalog.from_tree(tree(client), brand=brand).by_name
|
||||
|
||||
|
||||
class Catalog:
|
||||
"""品牌-门店树的内存索引(一次请求,多次查询)。
|
||||
|
||||
Args:
|
||||
nodes: 接口 ``data`` 原始数组
|
||||
|
||||
Attributes:
|
||||
brands: 品牌名列表(服务端顺序)
|
||||
rows: 扁平门店条目列表
|
||||
duplicates: 跨品牌重名门店 → 全部条目(同名时 :meth:`get` 只返回第一个)
|
||||
"""
|
||||
|
||||
def __init__(self, nodes: Iterable[dict]) -> None:
|
||||
self.rows: List[Dict[str, str]] = []
|
||||
self.brands: List[str] = []
|
||||
self.by_name: Dict[str, Dict[str, str]] = {}
|
||||
self.duplicates: Dict[str, List[Dict[str, str]]] = {}
|
||||
for node in nodes or []:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
b_name = _sid(node.get("label"))
|
||||
if not b_name:
|
||||
continue
|
||||
self.brands.append(b_name)
|
||||
for child in (node.get("children") or []):
|
||||
name = _sid((child or {}).get("label"))
|
||||
if not name:
|
||||
continue
|
||||
row = {"brand": b_name, "brand_id": _sid(node.get("value")),
|
||||
"name": name, "shop_id": _sid(child.get("value"))}
|
||||
self.rows.append(row)
|
||||
if name in self.by_name:
|
||||
self.duplicates.setdefault(name, [self.by_name[name]]).append(row)
|
||||
else:
|
||||
self.by_name[name] = row
|
||||
|
||||
@classmethod
|
||||
def load(cls, client) -> "Catalog":
|
||||
"""从接口加载。"""
|
||||
return cls(tree(client))
|
||||
|
||||
@classmethod
|
||||
def from_tree(cls, nodes: Iterable[dict], *, brand: str = "") -> "Catalog":
|
||||
"""从原始树构建(``brand`` 非空时只保留该品牌)。"""
|
||||
cat = cls(nodes)
|
||||
if brand:
|
||||
cat.rows = [r for r in cat.rows if r["brand"] == brand]
|
||||
cat.brands = [b for b in cat.brands if b == brand]
|
||||
cat.by_name = {r["name"]: r for r in cat.rows}
|
||||
cat.duplicates = {k: v for k, v in cat.duplicates.items()
|
||||
if any(x["brand"] == brand for x in v)}
|
||||
return cat
|
||||
|
||||
# ---------------- 查询 ----------------
|
||||
def __len__(self) -> int:
|
||||
return len(self.rows)
|
||||
|
||||
def get(self, shop_name: str) -> Optional[Dict[str, str]]:
|
||||
"""按门店名取条目(首尾空白忽略;不存在返回 ``None``)。"""
|
||||
return self.by_name.get(_sid(shop_name))
|
||||
|
||||
def brand_of(self, shop_name: str) -> str:
|
||||
"""门店名 → 品牌;未收录返回空串(插件据此决定是否人工确认)。"""
|
||||
row = self.get(shop_name)
|
||||
return row["brand"] if row else ""
|
||||
|
||||
def shop_id(self, shop_name: str) -> str:
|
||||
"""门店名 → CRM 门店 ID;未收录返回空串。"""
|
||||
row = self.get(shop_name)
|
||||
return row["shop_id"] if row else ""
|
||||
|
||||
def names(self, brand: str = "") -> List[str]:
|
||||
"""门店名列表(可限定品牌)。"""
|
||||
return [r["name"] for r in self.rows if not brand or r["brand"] == brand]
|
||||
|
||||
def of_brand(self, brand: str) -> List[Dict[str, str]]:
|
||||
"""某品牌下的门店条目。"""
|
||||
return [r for r in self.rows if r["brand"] == brand]
|
||||
|
||||
|
||||
def brand_of(client, shop_name: str) -> str:
|
||||
"""门店名 → 品牌(单次调用版;批量请用 :class:`Catalog`)。"""
|
||||
return index(client).get(_sid(shop_name), {}).get("brand", "")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALL_BRANDS_URL",
|
||||
"BRAND_SHOPS_URL",
|
||||
"Catalog",
|
||||
"all_brand_names",
|
||||
"all_brands",
|
||||
"brand_id",
|
||||
"brand_of",
|
||||
"brands",
|
||||
"index",
|
||||
"shops",
|
||||
"tree",
|
||||
"unauthorized_brands",
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "crm_sdk"
|
||||
version = "0.3.3"
|
||||
description = "37du CRM(crm.37du.co)接口 SDK:账号密码登录(验证码 OCR)与登录态复用、通用 JSON 请求与 S0 信封校验、分页、授权品牌门店树与门店索引"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"requests>=2.28",
|
||||
"ddddocr>=1.4",
|
||||
"Pillow>=9.0",
|
||||
"DrissionPage>=4.1",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["crm_sdk"]
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "crm_sdk",
|
||||
"name": "CRM 系统 SDK",
|
||||
"version": "0.3.3",
|
||||
"description": "37du CRM(crm.37du.co)接口封装:账号密码登录(验证码 ddddocr 识别,无人值守)优先、钉钉扫码兜底,登录态 Cookie 头保序复用与落盘;通用 JSON 请求与 S0 信封校验、分页、授权品牌门店树(getAuthorizedBrandShops)与门店/品牌索引。登录态按账号隔离落盘,插件经 ctx 或本 SDK 构建会话后直接调用。",
|
||||
"provides": [
|
||||
"crm_sdk"
|
||||
],
|
||||
"deps": [
|
||||
"requests",
|
||||
"ddddocr",
|
||||
"PIL",
|
||||
"DrissionPage"
|
||||
],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "crm_sdk._selftest:main",
|
||||
"api": "api.json"
|
||||
}
|
||||
Reference in New Issue
Block a user