# -*- coding: utf-8 -*- """门店归属:把美团收益明细的「消费门店」翻译成内部门店 + 品牌。 两步走,都不依赖字符串模糊匹配: 1. **券号 join**(主):``crm_store`` 拉到的「券号 → CRM 门店」与收益明细的券号对齐, 命中即得到内部门店(订单级唯一,实测 100%); 2. **映射表复用**(补):历史命中过的「美团门店名 → 内部门店」落盘累积, 本期虽然没取到券号(跨月补单 / CRM 未同步)也能直接翻译。 产物 ``门店核对_起_止.xlsx``(与台账同目录,不改动台账本身): * ``门店映射``:美团门店名 → 内部门店 / 品牌 / CRM 门店ID / 命中单数 * ``门店汇总``:按内部门店汇总订单数与金额(财务按店核对用) * ``未匹配``:券号与映射表都没对上的订单,人工确认一次后可写回映射表 映射表冲突(同一美团门店名对到多个内部门店,常见于通兑券跨店核销)按票数取众数, 并在「门店映射」的备注列标出,便于人工复核。 """ import glob import json import os from collections import defaultdict from datetime import datetime import openpyxl from openpyxl.styles import Alignment, Font, PatternFill from openpyxl.utils import get_column_letter from .. import config from ..data import crm_store # 收益明细里用到的列(按表头关键词定位,不写死列号) COL_TICKET = '券号' COL_SHOP = '消费门店' COL_TIME = '验券/退款/调整时间' COL_GROSS = '总收入(元)' COL_NET = '结算价' COL_FEE = '平台技术服务费(元)' COL_MARKETING = '商家营销费用(元)' COL_CHANNEL = '渠道佣金(元)' _HEADER_FILL = PatternFill('solid', fgColor='DDEBF7') _WARN_FILL = PatternFill('solid', fgColor='FCE4D6') def _find_col(header, keyword, *, exact=True): """按表头关键词定位列下标(0 起);``exact=False`` 时用前缀/包含。""" for idx, name in enumerate(header): text = str(name or '').strip() if (text == keyword) if exact else (keyword in text): return idx return -1 def _latest_detail(): """月份/修改时间最新的团购收益明细(金色湖畔前缀的文件天然不匹配)。""" paths = glob.glob(os.path.join(config.WORK_DIR, config.DETAIL_GLOB)) paths = [p for p in paths if '_备份' not in p and not os.path.basename(p).startswith('~$')] if not paths: return '' paths.sort(key=os.path.getmtime, reverse=True) return paths[0] def _to_float(value): """金额转 float;'--'/空/异常一律 0(明细里退款行的负数要保留)。""" if value is None or value == '': return 0.0 try: return float(str(value).replace(',', '').strip()) except (TypeError, ValueError): return 0.0 def _load_map(): """读累积映射表;损坏/缺失时返回空表(不阻断)。""" path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE) if not os.path.exists(path): return {'shops': {}} try: with open(path, encoding='utf-8') as fp: data = json.load(fp) except (OSError, ValueError) as e: config.log(f'门店映射表读取失败,按空表处理:{e}', 'WARN') return {'shops': {}} if not isinstance(data, dict) or not isinstance(data.get('shops'), dict): return {'shops': {}} return data def _save_map(data): path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE) tmp = f'{path}.tmp' with open(tmp, 'w', encoding='utf-8') as fp: json.dump(data, fp, ensure_ascii=False, indent=2) os.replace(tmp, path) return path def _read_detail(path): """读收益明细:返回 (表头, 数据行列表, 列下标字典)。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: ws = wb[wb.sheetnames[0]] header = list(next(ws.iter_rows(min_row=config.HEADER_ROW, max_row=config.HEADER_ROW, max_col=ws.max_column, values_only=True))) cols = { 'ticket': _find_col(header, COL_TICKET), 'shop': _find_col(header, COL_SHOP), 'time': _find_col(header, COL_TIME), 'gross': _find_col(header, COL_GROSS), 'net': _find_col(header, COL_NET, exact=False), 'fee': _find_col(header, COL_FEE), 'marketing': _find_col(header, COL_MARKETING), 'channel': _find_col(header, COL_CHANNEL), } missing = [k for k in ('ticket', 'shop', 'time') if cols[k] < 0] if missing: raise RuntimeError(f'收益明细缺少必需列:{missing}(表头第 {config.HEADER_ROW} 行)') rows = [] for row in ws.iter_rows(min_row=config.DATA_START_ROW, max_col=len(header), values_only=True): if not any(v not in (None, '') for v in row): continue rows.append(row) return header, rows, cols finally: wb.close() def _day_of(value): return crm_store._to_date(value) def _write_output(path, mapped_names, summary, unmatched): """写门店核对 xlsx(新建文件,不动台账)。""" wb = openpyxl.Workbook() head_font = Font(bold=True) # ---------- sheet1 门店映射 ---------- ws = wb.active ws.title = '门店映射' head = ['美团门店名', '内部门店', '品牌', 'CRM门店ID', '累计命中单数', '备注'] ws.append(head) for idx, (name, info) in enumerate(sorted(mapped_names.items()), 1): votes = info.get('votes') or {} note = '' if len(votes) > 1: others = {k: v for k, v in votes.items() if k != info.get('shop')} if others: note = '另有 ' + '、'.join(f'{k}({v})' for k, v in others.items()) + ' 单(跨店核销)' ws.append([name, info.get('shop', ''), info.get('brand', ''), info.get('shop_id', ''), sum(votes.values()) or info.get('hits', 0), note]) if note: for cell in ws[idx + 1]: cell.fill = _WARN_FILL # ---------- sheet2 门店汇总 ---------- ws2 = wb.create_sheet('门店汇总') ws2.append(['内部门店', '品牌', '订单数', '总收入', '结算价', '平台技术服务费', '商家营销费用', '渠道佣金']) total = [0, 0.0, 0.0, 0.0, 0.0, 0.0] for shop in sorted(summary, key=lambda s: (summary[s]['brand'], s)): item = summary[shop] ws2.append([shop, item['brand'], item['count'], round(item['gross'], 2), round(item['net'], 2), round(item['fee'], 2), round(item['marketing'], 2), round(item['channel'], 2)]) total[0] += item['count'] total[1] += item['gross'] total[2] += item['net'] total[3] += item['fee'] total[4] += item['marketing'] total[5] += item['channel'] ws2.append(['合计', '', total[0]] + [round(x, 2) for x in total[1:]]) # ---------- sheet3 未匹配 ---------- ws3 = wb.create_sheet('未匹配') ws3.append(['券号', '美团门店', '验券时间', '总收入', '说明']) for row in unmatched: ws3.append(row) for sheet in (ws, ws2, ws3): for cell in sheet[1]: cell.font = head_font cell.fill = _HEADER_FILL cell.alignment = Alignment(horizontal='center') sheet.freeze_panes = 'A2' for col in range(1, sheet.max_column + 1): width = max((len(str(sheet.cell(r, col).value or '')) for r in range(1, min(sheet.max_row, 200) + 1)), default=8) sheet.column_dimensions[get_column_letter(col)].width = min(46, max(10, width + 6)) wb.save(path) return path def run(detail_path='', dry_run=False, progress_from=78, progress_to=88): """执行门店归属核对。 Args: detail_path: 指定收益明细;空则取目录内最新一份 dry_run: 只统计不写文件(映射表也不落盘) progress_from / progress_to: 拉 CRM 时的进度区间(0~100) Returns: ``{"ok", "message", "path", "mapped", "unmapped", "stores", "conflicts"}`` """ if not crm_store.available(): return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0, 'conflicts': [], 'message': '未挂载 crm_sdk,跳过门店归属(需插件声明 requires.sdks)'} path = detail_path or _latest_detail() if not path or not os.path.exists(path): return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0, 'conflicts': [], 'message': '未找到团购收益明细,无法做门店归属'} config.log(f'门店归属:读收益明细 {os.path.basename(path)}') header, rows, cols = _read_detail(path) # 1) 收集日期 → 拉 CRM 券号表 days = {d for d in (_day_of(r[cols['time']]) for r in rows if cols['time'] < len(r)) if d} if not days: return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0, 'conflicts': [], 'message': '收益明细的「验券/退款/调整时间」全为空,跳过门店归属'} config.log(f'门店归属:明细 {len(rows)} 行,验券日期 {min(days)}~{max(days)}({len(days)} 天)') crm = crm_store.load(days, progress_from=progress_from, progress_to=progress_to) if not crm.get('ok'): return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0, 'conflicts': [], 'message': crm.get('message') or 'CRM 券号取数为空'} config.log(crm.get('message') or '') tickets = crm['tickets'] # 2) 券号 join,累积映射表 store = _load_map() shops = store['shops'] summary = defaultdict(lambda: {'brand': '', 'count': 0, 'gross': 0.0, 'net': 0.0, 'fee': 0.0, 'marketing': 0.0, 'channel': 0.0}) unmatched = [] mapped_cnt = unmapped_cnt = 0 conflicts = [] for row in rows: def cell(key): idx = cols[key] return row[idx] if 0 <= idx < len(row) else None name = str(cell('shop') or '').strip() code = str(cell('ticket') or '').strip() if not name: continue hit = tickets.get(code) info = shops.get(name) or {} shop = (hit or {}).get('shop') or info.get('shop') or '' if not shop: unmapped_cnt += 1 unmatched.append([code, name, str(cell('time') or '')[:19], round(_to_float(cell('gross')), 2), 'CRM 与映射表均未命中']) continue mapped_cnt += 1 # 命中结果回写映射表(票数累计,冲突交给备注列提示) votes = info.get('votes') or {} if hit: votes[shop] = int(votes.get(shop, 0)) + 1 entry = shops.setdefault(name, {}) entry['votes'] = votes entry['shop'] = max(votes, key=votes.get) if votes else shop entry['shop_id'] = (hit or {}).get('shop_id') or info.get('shop_id', '') entry['brand'] = (hit or {}).get('brand') or info.get('brand', '') entry['updated'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') item = summary[shop] item['brand'] = entry['brand'] or item['brand'] item['count'] += 1 item['gross'] += _to_float(cell('gross')) item['net'] += _to_float(cell('net')) item['fee'] += _to_float(cell('fee')) item['marketing'] += _to_float(cell('marketing')) item['channel'] += _to_float(cell('channel')) conflicts = [f'{k} → {v["shop"]}' for k, v in shops.items() if len(v.get('votes') or {}) > 1] out_from, out_to = min(days).isoformat(), max(days).isoformat() out_name = f'{config.STORE_OUT_PREFIX}_{out_from.replace("-", "")}_{out_to.replace("-", "")}.xlsx' out_path = os.path.join(config.WORK_DIR, out_name) if dry_run: message = (f'[演练] 门店归属 {mapped_cnt}/{mapped_cnt + unmapped_cnt} 行,' f'覆盖 {len(summary)} 家内部门店,未匹配 {unmapped_cnt} 行;不写文件') config.log(message) return {'ok': True, 'path': '', 'mapped': mapped_cnt, 'unmapped': unmapped_cnt, 'stores': len(summary), 'conflicts': conflicts, 'message': message} _write_output(out_path, shops, summary, unmatched) saved_map = _save_map(store) message = (f'门店归属完成:{mapped_cnt}/{mapped_cnt + unmapped_cnt} 行已归属,' f'{len(summary)} 家内部门店;未匹配 {unmapped_cnt} 行;' f'结果 {os.path.basename(out_path)},映射表 {os.path.basename(saved_map)}') if conflicts: message += f';{len(conflicts)} 家门店存在跨店核销(见备注列)' config.log(message) return {'ok': True, 'path': out_path, 'mapped': mapped_cnt, 'unmapped': unmapped_cnt, 'stores': len(summary), 'conflicts': conflicts, 'message': message}