feat(xq0041): 美团/抖音核对迁出至 XQ0085,保留导表与到账统计核对(v1.3.13)
download=只导打款/团购/预订收益明细;check_settlement=到账统计核对(并台账/门店归属/更新核对统计);金色印象与金色湖畔独立浏览器档案;新增 CRM 门店映射、基础信息同步与贴总表逻辑。
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
# -*- 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 = _sdk()
|
||||
if sdk is None:
|
||||
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
|
||||
login = sdk.auth.ensure_login(log=config.log)
|
||||
if not login.get('success'):
|
||||
return None, None, f"CRM 登录失败:{login.get('message') or '未知原因'}"
|
||||
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),
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,190 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
||||
|
||||
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
|
||||
|
||||
源(共享盘,只读)
|
||||
1111/TG/2026年11月/11.10/美团11.10.xlsx
|
||||
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
||||
目标(本地副本)
|
||||
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
|
||||
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
|
||||
|
||||
两张表复制到本地后,后续所有处理(明细贴表、报表写值)都只改本地副本。
|
||||
|
||||
要点:
|
||||
|
||||
* **按日期取表**:源文件优先按 ``{关键词}{月}.{日}.xlsx`` 精确匹配;
|
||||
匹配不到再在该日目录里取关键词命中的唯一 xlsx(人工临时改过名的场景);
|
||||
* **跨月自动回退**:1 号的「昨天」在上个月的目录,月份目录按源日期算;
|
||||
* **幂等**:本地目标已存在且非空就跳过,重复运行不会覆盖当天已处理的数据;
|
||||
* **不依赖第三方库**:UNC 路径用标准库只读打开 + 本地写入,缺少凭据时给出提示。
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _parse_day(value):
|
||||
"""``date`` / ``datetime`` / 'YYYY-MM-DD' 统一成 date;无法解析返回 None。"""
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
text = str(value or '').strip()[:10]
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def month_dir(root, day):
|
||||
"""月份目录:``2026年11月``。"""
|
||||
return os.path.join(root, f'{day.year}年{day.month}月')
|
||||
|
||||
|
||||
def day_dir(root, day):
|
||||
"""日期目录:``11.10``(不补零,与共享盘现有命名一致)。"""
|
||||
return os.path.join(month_dir(root, day), f'{day.month}.{day.day}')
|
||||
|
||||
|
||||
def table_name(keyword, day, ext):
|
||||
"""核对表文件名:``美团11.10.xlsx``。"""
|
||||
return f'{keyword}{day.month}.{day.day}{ext}'
|
||||
|
||||
|
||||
def _list_tables(folder, keyword, ext):
|
||||
"""列出目录里关键词 + 后缀命中的 xlsx(排除 Excel 临时文件 ``~$``)。"""
|
||||
try:
|
||||
names = os.listdir(folder)
|
||||
except OSError:
|
||||
return []
|
||||
out = []
|
||||
for name in names:
|
||||
low = name.lower()
|
||||
if name.startswith('~$') or not low.endswith(ext.lower()):
|
||||
continue
|
||||
if keyword and keyword not in name:
|
||||
continue
|
||||
out.append(name)
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def _pick_source(folder, keyword, prev_day, ext):
|
||||
"""在昨天目录里挑源文件:先精确日期,再退化为目录内唯一命中的表。"""
|
||||
exact = os.path.join(folder, table_name(keyword, prev_day, ext))
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = _list_tables(folder, keyword, ext)
|
||||
if len(candidates) == 1:
|
||||
return os.path.join(folder, candidates[0])
|
||||
return ''
|
||||
|
||||
|
||||
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
|
||||
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。
|
||||
|
||||
Args:
|
||||
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
||||
keyword: 文件名关键词(默认 :data:`config.SHARE_TABLE_KEYWORD`,如「美团」)
|
||||
ext: 后缀(默认 :data:`config.SHARE_TABLE_EXT`)
|
||||
day: 目标日期(默认今天)
|
||||
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``,共享盘只读不写入)
|
||||
dry_run: 只检查不复制
|
||||
|
||||
Returns:
|
||||
``{"ok", "message", "src", "dst", "skipped"}``
|
||||
"""
|
||||
root = str(share_root or config.SHARE_CHECK_ROOT).strip().strip('"').rstrip('\\/')
|
||||
kw = str(keyword or config.SHARE_TABLE_KEYWORD).strip()
|
||||
suffix = str(ext or config.SHARE_TABLE_EXT).strip()
|
||||
if suffix and not suffix.startswith('.'):
|
||||
suffix = '.' + suffix
|
||||
target = _parse_day(day) or date.today()
|
||||
prev = target - timedelta(days=1)
|
||||
|
||||
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
|
||||
dst_dir = str(local_dir or os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR))
|
||||
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
|
||||
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
|
||||
|
||||
if not src_path:
|
||||
folder = day_dir(root, prev)
|
||||
found = _list_tables(folder, kw, suffix)
|
||||
result['message'] = (
|
||||
f'共享盘 {folder} 下没有找到 {kw}*{suffix}'
|
||||
+ (f'(现有:{"、".join(found)})' if found else
|
||||
';若共享盘未连接,请先确认当前机器能访问 ' + root))
|
||||
return result
|
||||
|
||||
if os.path.isfile(dst_path) and os.path.getsize(dst_path) > 0:
|
||||
result.update(ok=True, skipped=True,
|
||||
message=f'本地副本已存在,跳过复制:'
|
||||
f'{os.path.basename(dst_path)}')
|
||||
return result
|
||||
|
||||
if dry_run:
|
||||
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → '
|
||||
f'{dst_path}')
|
||||
return result
|
||||
|
||||
try:
|
||||
os.makedirs(dst_dir, exist_ok=True)
|
||||
shutil.copy2(src_path, dst_path)
|
||||
except OSError as e:
|
||||
tip = ''
|
||||
if getattr(e, 'winerror', None) in (53, 67, 64, 1219, 1326):
|
||||
tip = '(共享盘网络路径不可达 / 缺少凭据,请确认本机已能访问该共享)'
|
||||
result['message'] = f'复制失败:{e}{tip}'
|
||||
return result
|
||||
|
||||
if not os.path.isfile(dst_path) or os.path.getsize(dst_path) == 0:
|
||||
result['message'] = f'复制后本地副本缺失或为空:{dst_path}'
|
||||
return result
|
||||
|
||||
result.update(ok=True, message=f'已从共享盘复制 {os.path.basename(src_path)} → '
|
||||
f'本地 {os.path.basename(dst_path)}')
|
||||
return result
|
||||
|
||||
|
||||
def copy_prev_tables(share_root='', day=None, local_dir='', dry_run=False):
|
||||
"""把昨天的核对表 + 马敏团购总表一起拉到本地副本(共享盘只读)。
|
||||
|
||||
源文件在共享盘 ``{share_root}/{年}月/{月}.{日}/``,本地目标在 ``WORK_DIR/_work/``:
|
||||
|
||||
* 核对表:``美团11.10.xlsx`` → 本地 ``美团11.11.xlsx``
|
||||
* 共享总表:``马敏团购总表11.10.xlsx`` → 本地 ``马敏团购总表11.11.xlsx``
|
||||
|
||||
Args:
|
||||
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
||||
day: 目标日期(默认今天;传「核对营业日」时按指定日期)
|
||||
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``)
|
||||
dry_run: 只检查不复制
|
||||
|
||||
Returns:
|
||||
``{"ok", "message", "tables": [...], "copied", "skipped", "failed"}``
|
||||
"""
|
||||
jobs = (
|
||||
('核对表', config.SHARE_TABLE_KEYWORD, config.SHARE_TABLE_EXT),
|
||||
('共享总表', config.LINK_BOOK, config.SHARE_TABLE_EXT),
|
||||
)
|
||||
tables = []
|
||||
for label, keyword, ext in jobs:
|
||||
item = copy_prev_table(share_root=share_root, keyword=keyword, ext=ext,
|
||||
day=day, local_dir=local_dir, dry_run=dry_run)
|
||||
item['label'] = label
|
||||
tables.append(item)
|
||||
|
||||
failed = [t for t in tables if not t.get('ok')]
|
||||
return {
|
||||
'ok': not failed,
|
||||
'message': ';'.join(f'{t["label"]}:{t["message"]}' for t in tables),
|
||||
'tables': tables,
|
||||
'copied': sum(1 for t in tables if t.get('ok') and not t.get('skipped')),
|
||||
'skipped': sum(1 for t in tables if t.get('skipped')),
|
||||
'failed': len(failed),
|
||||
}
|
||||
Reference in New Issue
Block a user