Files
37duAutomation/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/crm_store.py
T

153 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""CRM 门店归属数据层:券号 → 内部门店 / 品牌。
为什么不按门店名匹配:美团门店名与内部门店名是两套口径(改名 / 错字 / 别名,
如「大渡口店」实际是「春晖路CEO会馆」),字符串匹配只能到 89%,剩下的必须人工。
**券号是订单级唯一关联**:CRM 团购核销记录里同一条数据就带 ``ticketCode`` +
``shopName`` + ``shopId``,与美团收益明细的「券号」join,实测命中 100%。
数据来自 ``crm_sdk``(执行机按插件 ``requires.sdks`` 下发挂载):
* 门店主数据:``stores.Catalog``(品牌 → 门店,含 OLD 旧店,按名称反查品牌)
* 核销明细:``reports.list_all(client, 'groupData', reportDate=日)``
SDK 未挂载 / CRM 未登录时**不阻断主流程**:返回 ``ok=False``,由调用方降级提示。
"""
import datetime
from .. import config
def _sdk():
"""延迟 import,SDK 未挂载时返回 None(不抛,便于降级)。"""
try:
import crm_sdk # noqa: WPS433 - 运行时由执行机挂载
return crm_sdk
except ImportError:
return None
def available():
"""crm_sdk 是否可用(插件被单独拷贝/未下发 SDK 时为 False)。"""
return _sdk() is not None
def _day_range(days, window=None):
"""把日期集合按 ±N 天展开成待查日期列表(升序去重)。"""
window = config.CRM_DATE_WINDOW if window is None else int(window)
out = set()
for d in days or ():
base = _to_date(d)
if not base:
continue
for delta in range(-window, window + 1):
out.add((base + datetime.timedelta(days=delta)).isoformat())
return sorted(out)
def _to_date(value):
"""兼容 date / datetime / 'YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS'。"""
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
text = str(value or '').strip()[:10]
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return datetime.datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def _client():
"""构建 CRM 客户端:优先复用落盘登录态,失效时用 SDK 内置凭证做纯 API 登录。
凭证由 ``crm_sdk.creds`` 解密(插件/界面都不出现账号密码);验证码 OCR 失败时
**直接失败**,不走 ``ensure_login`` 的钉钉扫码兜底,避免无人值守时挂等 300 秒。
"""
sdk = _sdk()
if sdk is None:
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
try:
if not sdk.auth.is_session_valid(log=config.log):
res = sdk.auth.login_by_password(log=config.log)
if not res.get('success'):
return None, None, f"CRM 登录失败:{res.get('message') or '未知原因'}"
config.log(f"CRM 登录:{res.get('message') or '账号密码登录成功'}")
except Exception as e: # noqa: BLE001 - 缺凭证/网络异常都降级为提示
return None, None, f'CRM 登录异常:{e}'
session = sdk.auth.build_session()
if session is None:
return None, None, 'CRM 登录态不可用(Cookie 缺失)'
return sdk, sdk.CrmClient(session, log=config.log), ''
def load(days, *, window=None, progress_from=0, progress_to=0):
"""拉取指定日期窗口内全部团购核销记录,建「券号 → 门店」索引。
Args:
days: 美团收益明细里出现的验券日期(``date`` / ``str`` 均可)
window: 前后各多看几天(默认 :data:`config.CRM_DATE_WINDOW`)
progress_from / progress_to: 进度区间(0~100),逐日拉取时上报
Returns:
``{"ok", "message", "tickets": {券号: {shop, shop_id, brand, date}},
"days": [...], "count": n}``
"""
empty = {'ok': False, 'message': '', 'tickets': {}, 'days': [], 'count': 0}
wanted = _day_range(days, window)
if not wanted:
empty['message'] = '收益明细里没有可解析的验券日期,跳过门店归属'
return empty
sdk, client, err = _client()
if err:
empty['message'] = err
return empty
# 门店主数据:品牌 → 门店(用于给 shopName 反查品牌 + 校验门店名是否在册)
try:
catalog = sdk.stores.Catalog.load(client)
except Exception as e: # noqa: BLE001 - 网络/权限异常降级
empty['message'] = f'拉取 CRM 门店树失败:{e}'
return empty
if not len(catalog):
# 接口对未认证/无授权账号返回 S0 + 空数组,不是 401,必须按失败处理
empty['message'] = 'CRM 门店树为空(登录态失效或无门店授权)'
return empty
config.log(f'CRM 门店主数据:{len(catalog)} 家 / 品牌 {"/".join(catalog.brands)}')
tickets = {}
total_days = len(wanted)
span = max(0, int(progress_to) - int(progress_from))
for idx, day in enumerate(wanted, 1):
try:
rows = sdk.reports.list_all(client, config.CRM_GROUP_REPORT,
reportDate=day, page_size=config.CRM_PAGE_SIZE)
except Exception as e: # noqa: BLE001 - 单日失败不影响整体
config.log(f'CRM {day} 团购核销取数失败(跳过):{e}', 'WARN')
continue
for row in rows or ():
code = str(row.get('ticketCode') or '').strip()
shop = str(row.get('shopName') or '').strip()
if not code or not shop:
continue
tickets[code] = {
'shop': shop,
'shop_id': str(row.get('shopId') or '').strip(),
'brand': catalog.brand_of(shop),
'date': day,
}
config.log(f'CRM {day}:{len(rows or [])} 行(累计券号 {len(tickets)})')
if span:
config.progress(int(progress_from + span * idx / total_days))
return {
'ok': bool(tickets),
'message': (f'CRM 券号 {len(tickets)} 条({wanted[0]}~{wanted[-1]})' if tickets
else f'{wanted[0]}~{wanted[-1]} 未取到 CRM 核销记录'),
'tickets': tickets,
'days': wanted,
'count': len(tickets),
}