# -*- coding: utf-8 -*- """对比 sheet:今日遗留回填 + 按门店/项目分组验证(美团 / 抖音共用)。 2026-11-27 业务口径: * **今日遗留(R)不再人工填**:取总表【团购统计】「未消费项目个数」(G), 按「门店 + 核销项目名称」汇总后逐行回填(美团取 类型 ∈ {美团, 点评},抖音取 抖音); * **验证改为分组**:按 E 列门店 + F 列项目分组,组内 W 求和为 0 才算平; W 为 ``-`` / 空的行不参与(见 :data:`config.COMPARE_VERIFY_SKIP`); * ``二选一`` / ``四选一`` 自身也是项目名,与其成员同组统计 (见 :data:`config.COMPARE_GROUP_MEMBERS`)。 本模块只读表、只算数;写盘仍由 :mod:`compare_sheets` 用 zip+XML 完成,避免循环依赖。 """ import os import re from collections import defaultdict from datetime import date, datetime, timedelta from difflib import SequenceMatcher import openpyxl from openpyxl.utils import column_index_from_string from .. import config def _cell(row, cnum): """取一行里第 cnum 列(1 起)的值,越界返回 None。""" idx = int(cnum) - 1 if idx < 0 or idx >= len(row): return None return row[idx] def _text(row, cnum): value = _cell(row, cnum) return '' if value is None else str(value).strip() def to_number(value): """转 float;None/空/非数值返回 None(0 是有效值,不能和「空」混)。""" if value is None or isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) text = str(value).strip().replace(',', '') if not text: return None try: return float(text) except ValueError: return None def _clean(value): """回填用:0 / 空 → None(表里留空),其它保留整数形态。""" num = to_number(value) if num is None or abs(num) < 1e-9: return None return int(num) if float(num).is_integer() else round(num, 2) def _as_date(value): 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 norm_item(text): """项目名归并:命中组成员的返回组名(二选一 / 四选一),否则原样返回。""" key = str(text or '').strip() if not key: return '' for group, members in config.COMPARE_GROUP_MEMBERS.items(): if key in members: return group return key def load_unused(path, types): """读【团购统计】里指定团购类型的「未消费项目个数」,按 (门店, 项目) 汇总。 Args: path: 本地马敏团购总表副本 types: 参与汇总的团购类型,如 ``('美团', '点评')`` Returns: ``{'ok','stats','date','rows','message'}``; ``stats`` = ``{(门店, 项目): 未消费个数}``,``date`` 为数据里的最大消费日期。 """ wanted = {str(t).strip() for t in (types or ()) if str(t).strip()} out = {'ok': False, 'stats': {}, 'date': '', 'rows': 0, 'message': ''} if not path or not os.path.isfile(path): out['message'] = f'未找到总表副本:{path}' return out sheet = config.COMPARE_STATS_SHEET i_type = column_index_from_string(config.COMPARE_STATS_TYPE_COL) i_date = column_index_from_string(config.COMPARE_STATS_DATE_COL) i_store = column_index_from_string(config.COMPARE_STATS_STORE_COL) i_item = column_index_from_string(config.COMPARE_STATS_ITEM_COL) i_unused = column_index_from_string(config.COMPARE_STATS_UNUSED_COL) width = max(i_type, i_date, i_store, i_item, i_unused) wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: if sheet not in wb.sheetnames: out['message'] = f'总表缺少 sheet「{sheet}」' return out stats = defaultdict(float) latest = None used = 0 for row in wb[sheet].iter_rows(min_row=config.COMPARE_STATS_DATA_START, max_col=width, values_only=True): cells = list(row) + [None] * (width - len(row)) kind = str(cells[i_type - 1] or '').strip() if wanted and kind not in wanted: continue store = str(cells[i_store - 1] or '').strip() item = str(cells[i_item - 1] or '').strip() if not store or not item: continue stats[(store, item)] += to_number(cells[i_unused - 1]) or 0.0 used += 1 day = _as_date(cells[i_date - 1]) if day and (latest is None or day > latest): latest = day finally: wb.close() out.update(ok=True, stats=dict(stats), rows=used, date=latest.isoformat() if latest else '') if not stats: out['message'] = f'【{sheet}】没有 {"、".join(sorted(wanted)) or "任何"} 类型的核销记录' else: out['message'] = (f'【{sheet}】{len(stats)} 个门店/项目组合,' f'消费日期 {out["date"] or "空"}') return out def build_fill_edits(rows, stats, store_col, item_col, refunds=None, start_row=None): """按 A 列门店 + B 列原始项目名,从团购统计取「未消费项目个数」回填今日遗留。 若给了 ``refunds``({(门店, 项目): 笔数}),再同门店同项目从今日遗留里扣掉; 精确项目名找得到就扣在那一行,否则按归并组(二选一/四选一)扣在组内第一行。 ``stats`` 为空(未贴当天团购统计)时不产计划,保持原值。 Returns: ``{'edits': {行号: 值或 None}, 'filled': n, 'unmatched': [...], 'refund_applied': [...], 'refund_unmatched': [...], 'skipped': ''}`` """ start = config.COMPARE_DATA_START if start_row is None else int(start_row) out = {'edits': {}, 'filled': 0, 'unmatched': [], 'skipped': '', 'refund_applied': [], 'refund_unmatched': []} if not stats: out['skipped'] = '团购统计无该平台数据,今日遗留保持原样' return out values = {} unmatched = set() for offset, row in enumerate(rows): row_no = start + offset store = _text(row, store_col) item = _text(row, item_col) key = (store, item) values[row_no] = _clean(stats.get(key)) if store else None if item and key not in stats: unmatched.add(item) if refunds: row_index, group_index = {}, {} for offset, row in enumerate(rows): row_no = start + offset store = _text(row, store_col) item = _text(row, item_col) row_index.setdefault((store, item), row_no) group_index.setdefault((store, norm_item(item)), row_no) for (store, item), count in sorted(refunds.items()): row_no = row_index.get((store, item)) if row_no is None: row_no = group_index.get((store, norm_item(item))) if row_no is None: out['refund_unmatched'].append({'store': store, 'item': item, 'count': count}) continue values[row_no] = (values.get(row_no) or 0.0) - float(count) out['refund_applied'].append({'store': store, 'item': item, 'row': row_no, 'count': count, 'value': _clean(values[row_no])}) out['edits'] = {row_no: _clean(value) for row_no, value in values.items()} out['filled'] = sum(1 for value in out['edits'].values() if value is not None) out['unmatched'] = sorted(unmatched) return out def _alias(name): """取平台门店名最后一个括号里的店名并去掉末尾「店」。""" hits = re.findall(r'[((]([^(())]+)[))]', str(name or '')) if not hits: return '' return re.sub(r'店$', '', hits[-1].strip()) def _match_store(name, base_stores, pool): """平台门店名 → 内部门店名:先查基础信息 A→B,再按括号店名匹配总表门店。 Returns: ``(内部门店, 匹配方式)``;匹配不到返回 ``('', 原因)``。 """ key = str(name or '').strip() if not key: return '', '门店为空' hit = base_stores.get(key) if hit: return hit, '基础信息' alias = _alias(key) or key exact = [s for s in pool if s == alias] if len(exact) == 1: return exact[0], '同名' pref = [s for s in pool if s.startswith(alias)] if len(pref) == 1: return pref[0], '前缀' if len(pref) > 1: return '', '多候选:' + '/'.join(pref[:3]) rev = [s for s in pool if alias.startswith(s)] if len(rev) == 1: return rev[0], '反向' if not pool: return '', '总表门店为空' best = max(pool, key=lambda s: SequenceMatcher(None, alias, s).ratio()) if SequenceMatcher(None, alias, best).ratio() >= config.COMPARE_REFUND_STORE_MIN_RATIO: return best, '相似' return '', '无匹配:' + alias def _biz_day(value): """营业日:hour < 10 算前一天(与明细表 AD 列同一口径)。""" if isinstance(value, datetime): day, hour = value.date(), value.hour elif isinstance(value, date): day, hour = value, 0 else: text = str(value or '').strip() m = re.match(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})[ T](\d{1,2}):', text) if m: batch = [int(x) for x in m.groups()] day, hour = date(*batch[:3]), batch[3] else: day, hour = _as_date(text), 0 if day is None: return None return day - timedelta(days=1) if hour < 10 else day def _reset_if_needed(ws): """平台导出/模板的 dimension 经常不准:1×1 会读不到,写成百万行又会白扫。""" rows = ws.max_row or 1 cols = ws.max_column or 1 if rows <= 1 or cols <= 1 or rows > 100000 or cols > 1000: ws.reset_dimensions() def _read_base_info(wb): """读【基础信息】:返回 ({平台商品名: 内部项目}, {平台门店: 内部门店})。""" sheet = config.COMPARE_BASE_INFO_SHEET if sheet not in wb.sheetnames: return {}, {} a, b, e, f = (column_index_from_string(c) for c in config.COMPARE_BASE_INFO_COLS) width = max(a, b, e, f) items, stores = {}, {} ws = wb[sheet] _reset_if_needed(ws) for row in ws.iter_rows(min_row=1, max_col=width, values_only=True): cells = list(row) + [None] * (width - len(row)) product = str(cells[e - 1] or '').strip() item = str(cells[f - 1] or '').strip() if product and item: items.setdefault(product, item) platform_store = str(cells[a - 1] or '').strip() store = str(cells[b - 1] or '').strip() if platform_store and store: stores.setdefault(platform_store, store) return items, stores def load_refunds(path, plan, store_pool, day=None): """统计本地表里退款/撤销核销的笔数(按 门店+项目,默认只算营业日当天)。 Args: path: 本地美团 / 抖音表(同一本工作簿里有【基础信息】和明细 sheet) plan: :data:`config.COMPARE_REFUND_GROUPS` 里的一项 store_pool: 总表里出现的门店名(用于括号店名匹配) day: 营业日;给了就按 plan['date_col'] 过滤(导出常跨好几天) Returns: ``{'ok','counts','rows','items','unmatched','message'}``; ``counts`` = ``{(内部门店, 内部项目): 笔数}``。 """ out = {'ok': False, 'counts': {}, 'rows': 0, 'items': {}, 'unmatched': [], 'message': ''} if not path or not os.path.isfile(path): out['message'] = f'未找到本地表:{path}' return out sheet = plan.get('sheet') or '' wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: if sheet not in wb.sheetnames: out['message'] = f'缺少 sheet「{sheet}」:{os.path.basename(path)}' return out base_items, base_stores = _read_base_info(wb) statuses = {str(s).strip() for s in (plan.get('statuses') or ())} i_status = column_index_from_string(plan['status_col']) i_store = column_index_from_string(plan['store_col']) i_item = column_index_from_string(plan['item_col']) fallback = plan.get('item_fallback_col') or '' i_fallback = column_index_from_string(fallback) if fallback else 0 date_col = plan.get('date_col') or '' i_date = column_index_from_string(date_col) if date_col else 0 width = max(i_status, i_store, i_item, i_fallback, i_date) ws = wb[sheet] _reset_if_needed(ws) counts = defaultdict(int) unmatched = [] rows = 0 skipped_day = 0 for row in ws.iter_rows(min_row=int(plan.get('data_start') or 1), max_col=width, values_only=True): cells = list(row) + [None] * (width - len(row)) status = str(cells[i_status - 1] or '').strip() if status not in statuses: continue if day is not None and i_date: if _biz_day(cells[i_date - 1]) != day: skipped_day += 1 continue rows += 1 raw_store = str(cells[i_store - 1] or '').strip() raw_item = str(cells[i_item - 1] or '').strip() store, how = _match_store(raw_store, base_stores, store_pool) item = base_items.get(raw_item, '') if not item and i_fallback: item = str(cells[i_fallback - 1] or '').strip() if not store or not item: unmatched.append({'status': status, 'store': raw_store, 'item': raw_item, 'reason': how if not store else '项目未映射'}) continue counts[(store, item)] += 1 finally: wb.close() out.update(ok=True, counts=dict(counts), rows=rows, items=base_items, unmatched=unmatched, skipped_day=skipped_day) if not rows: out['message'] = (f'【{sheet}】营业日没有退款/撤销核销行' + (f'(另有 {skipped_day} 行是其它日期,已跳过)' if skipped_day else '')) elif unmatched: out['message'] = (f'【{sheet}】{rows} 行退款/撤销,' f'{sum(counts.values())} 行已归位,{len(unmatched)} 行未匹配') else: out['message'] = (f'【{sheet}】{rows} 行退款/撤销,全部已归到 ' f'{len(counts)} 个门店项目') return out def verify(rows, cols, start_row=None, limit=None): """按 (E 门店, F 项目归并后) 分组,组内 W 求和为 0 判平。 Args: rows: ``compare_sheets._read_cells()`` 读出的数据行(第 5 行起) cols: 列号字典,需含 ``store`` / ``item`` / ``verify`` start_row: 数据起始行,默认 :data:`config.COMPARE_DATA_START` limit: 返回的不平组上限,默认 :data:`config.COMPARE_UNBALANCED_LIMIT` Returns: ``ok / total_groups / ok_groups / unbalanced / unbalanced_count / skipped_rows / checked_rows / bad_rows``;``unbalanced`` 每项含 ``store / item / diff / rows / bad``。 """ start = config.COMPARE_DATA_START if start_row is None else int(start_row) limit = config.COMPARE_UNBALANCED_LIMIT if limit is None else int(limit) groups = {} skipped_rows = checked_rows = bad_rows = 0 for offset, row in enumerate(rows): row_no = start + offset store = _text(row, cols['store']) item = norm_item(_text(row, cols['item'])) group = groups.setdefault((store, item), {'sum': 0.0, 'count': 0, 'skipped': 0, 'bad': [], 'row_ids': []}) raw = _cell(row, cols['verify']) text = '' if raw is None else str(raw).strip() if raw is None or text in config.COMPARE_VERIFY_SKIP: group['skipped'] += 1 skipped_rows += 1 continue num = to_number(raw) if num is None: group['bad'].append([row_no, text]) bad_rows += 1 continue group['sum'] += num group['count'] += 1 group['row_ids'].append(row_no) checked_rows += 1 total = ok = 0 unbalanced = [] for (store, item), group in groups.items(): if not group['count'] and not group['bad']: continue # 整组都是「-」/空,不参与 total += 1 diff = round(group['sum'], 2) if not group['bad'] and abs(diff) <= config.COMPARE_VERIFY_TOL: ok += 1 continue unbalanced.append({'store': store, 'item': item, 'diff': diff, 'rows': group['count'], 'bad': group['bad'][:5]}) unbalanced.sort(key=lambda x: (-abs(x['diff']), x['store'], x['item'])) return {'ok': not unbalanced, 'total_groups': total, 'ok_groups': ok, 'unbalanced': unbalanced[:limit], 'unbalanced_count': len(unbalanced), 'skipped_rows': skipped_rows, 'checked_rows': checked_rows, 'bad_rows': bad_rows, 'groups': groups} def build_meal_edits(groups): """对仍不平的「双人餐 / 三人餐」配对生成【平台结错】列调整。 触发:餐行(双人餐/三人餐)自身不平,同门店存在基础项目行,且基础行为正数 (基础行为负时再减只会扩大差额,跳过并列入 skipped 由人工看)。 倍数:``N`` = 餐行的差额(正数),餐行 J = N,基础行 J = -人数 × N (双人餐 -2N、三人餐 -3N);同一基础行遇到多餐时累加。 Args: groups: :func:`verify` 返回的 ``groups``(键 ``(门店, 项目)``) Returns: ``(edits, detail, skipped)``;``edits`` = ``{行号: J 值}``,``detail`` 每项含 ``store / item / base / meal_row / base_row / times / meal_j / base_j``, ``skipped`` 每项含 ``store / item / base / sum / reason``。 """ suffixes = config.COMPARE_MEAL_SUFFIXES edits, detail, skipped = {}, [], [] for (store, item), info in sorted(groups.items()): suffix = next((s for s in suffixes if item.endswith(s) and item != s), '') if not suffix: continue if abs(info['sum']) <= config.COMPARE_VERIFY_TOL and not info['bad']: continue # 餐行自己平,不需要修正 base = item[:-len(suffix)] base_info = groups.get((store, base)) if not base_info: continue # 没有基础项目行,无法配对 if base_info['sum'] <= config.COMPARE_VERIFY_TOL: skipped.append({'store': store, 'item': item, 'base': base, 'sum': round(base_info['sum'], 2), 'reason': '基础行不为正,写负数会扩大差额'}) continue meal_rows = info['row_ids'] or [row for row, _ in info['bad']] base_rows = base_info['row_ids'] or [row for row, _ in base_info['bad']] if not meal_rows or not base_rows: continue # 倍数 = 餐行差额(如餐行 -3 → 写 3 和 -2×3) times = int(round(-info['sum'])) if info['sum'] < 0 else config.COMPARE_MEAL_ADJUST times = max(1, times) meal_row, base_row = meal_rows[0], base_rows[0] headcount = suffixes[suffix] meal_j = times base_j = -headcount * times edits[meal_row] = edits.get(meal_row, 0) + meal_j edits[base_row] = edits.get(base_row, 0) + base_j detail.append({'store': store, 'item': item, 'base': base, 'meal_row': meal_row, 'base_row': base_row, 'times': times, 'meal_j': meal_j, 'base_j': base_j}) return edits, detail, skipped