# -*- coding: utf-8 -*- """美团核对:团购收益明细 → 订单收入明细表(2026-11 新版 31 列模板)。 * 按导出表头取值,映射到目标表 A~AB(映射见 :data:`config.DAILY_EXPORT_TO_TARGET`); 新版导出把「收益类型 / 业务类型」两个名字对调,映射里已按 11.24 真实数据校正; * 取数条件:``验券/退款/调整时间`` 的**日期等于营业日**(不做 10 点切日偏移), 全量保留(含总收入为负的退款/撤销行); * AC~AI 是模板自带的辅助公式(计数 / 验券时间 / 品项名称 / 下单时间 / 验证 / 佣金检测), 按目标表第 4 行下拉,行号相对引用随之平移; * 写盘用 zip+XML 只替换目标 sheet(表内有 8 个透视 + 6 个外部链接,openpyxl 保存会丢); * 明细/透视/报表 三口径合计交叉校验。 """ import glob import os import re import zipfile from datetime import date, datetime, timedelta import openpyxl from .. import config from . import com_refresh, share_copy, sheet_xml _REF_RE = re.compile(r'(\$?)([A-Z]{1,3})(\$?)(\d+)') # 预订明细按表头名映射到目标列(目标没有的列忽略) BOOKING_TARGET = { '消费门店': 11, '消费门店名称': 11, '门店': 11, '券号': 5, '券码': 5, '核销码': 5, '验券时间': 7, '核销时间': 7, '使用时间': 7, '套餐名': 9, '商品名称': 9, '商品名': 9, '订单信息': 9, '项目名称': 9, '总收入': 17, '收入': 17, '到账金额': 17, '结算价': 16, '预计收入': 16, '商家实收': 16, '业务类型': 3, '订单类型': 4, '下单时间': 6, } def _as_date(value): if isinstance(value, datetime): return value.date() if isinstance(value, date): return value text = str(value or '').strip() m = re.match(r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})', text) if m: try: return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date() except ValueError: pass return None def _business_day(value): """营业日:验券 hour < 10 算前一天(与明细表 AD 列公式同一口径)。""" d = value if isinstance(d, datetime): day, hour = d.date(), d.hour elif isinstance(d, date): day, hour = d, 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 _to_number(value): if value is None or isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) text = str(value).strip().replace(',', '').replace('¥', '') if not text: return None try: return float(text) except ValueError: return None def _reset_if_needed(ws): """导出的 dimension 常写成 1×1 或百万行,read_only 下会读不到/白扫。""" rows, cols = ws.max_row or 1, ws.max_column or 1 if rows <= 1 or cols <= 1 or rows > 100000 or cols > 1000: ws.reset_dimensions() def _shift_formula(formula, delta): """把模板公式的相对行号整体平移 delta($ 绝对引用不动)。""" if not formula or delta == 0: return formula def repl(m): col_abs, col, row_abs, row = m.groups() if row_abs: return m.group(0) return f'{col_abs}{col}{row_abs}{int(row) + delta}' return _REF_RE.sub(repl, formula) def _read_export(path): """读团购收益明细导出:返回数据行(list),表头行取 config.PROFIT_HEADER_ROW。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: ws = wb[wb.sheetnames[0]] _reset_if_needed(ws) header = next(ws.iter_rows(min_row=config.PROFIT_HEADER_ROW, max_row=config.PROFIT_HEADER_ROW, values_only=True), ()) width = len(header) or 1 rows = [] for row in ws.iter_rows(min_row=config.PROFIT_HEADER_ROW + 1, max_col=width, values_only=True): if row and row[0] is not None: rows.append(list(row)) return rows finally: wb.close() def _read_booking(path, target): """预订收益明细:按表头名映射到目标列,返回目标列顺序的行(28 列)。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: ws = wb[wb.sheetnames[0]] _reset_if_needed(ws) header = next(ws.iter_rows(min_row=config.PROFIT_HEADER_ROW, max_row=config.PROFIT_HEADER_ROW, values_only=True), ()) names = [str(h or '').strip() for h in header] width = len(names) or 1 out = [] for row in ws.iter_rows(min_row=config.PROFIT_HEADER_ROW + 1, max_col=width, values_only=True): if not row or row[0] is None: continue values = [None] * 28 for name, value in zip(names, row): col = BOOKING_TARGET.get(name) if col: values[col - 1] = value if _business_day(values[6]) != target: continue out.append(values) return out finally: wb.close() def _template_formulas(path, sheet): """读目标表第 4 行 AC~AI 的公式,作为下拉模板。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=False) try: ws = wb[sheet] _reset_if_needed(ws) row = next(ws.iter_rows(min_row=config.DAILY_DATA_START, max_row=config.DAILY_DATA_START, min_col=config.DAILY_HELPER_FIRST, max_col=config.DAILY_HELPER_LAST, values_only=True), ()) return [c if isinstance(c, str) and c.startswith('=') else None for c in row] finally: wb.close() def _last_data_row(path, sheet): """目标表现有数据末行(A 列非空)。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: ws = wb[sheet] _reset_if_needed(ws) last = config.DAILY_DATA_START - 1 for offset, row in enumerate(ws.iter_rows(min_row=config.DAILY_DATA_START, max_col=1, values_only=True)): if row and row[0] not in (None, ''): last = config.DAILY_DATA_START + offset return last finally: wb.close() def _sum_cached(ws, income_col, target=None): """读缓存列求和;target 给定时按 AD 验券时间(30) 与 C 业务类型(3) 筛选。""" total = 0.0 width = max(income_col, 30, 3) for row in ws.iter_rows(min_row=config.DAILY_DATA_START, max_col=width, values_only=True): cells = list(row) + [None] * (width - len(row)) if target is not None: day_val = cells[29] if day_val is None or int(day_val) != target.day: continue if str(cells[2] or '').strip() in config.DAILY_EXCLUDE_BUSINESS: continue value = cells[income_col - 1] if isinstance(value, (int, float)): total += float(value) return round(total, 2) def run(table_path='', day=None, dry_run=False, use_com=None): work = config.WORK_DIR target = _as_date(day) or date.today() result = {'ok': False, 'message': '', 'path': '', 'total': 0.0, 'pivot_total': 0.0, 'report_total': 0.0, 'consistent': False, 'detail_rows': 0, 'skipped_day': 0, 'replaced': 0} src = str(table_path or '').strip() if not src: cands = glob.glob(os.path.join(work, share_copy.table_name( config.SHARE_TABLE_KEYWORD, target, config.SHARE_TABLE_EXT))) src = cands[0] if cands else '' if not src or not os.path.isfile(src): result['message'] = f'未找到本地美团核对表副本:{src or work}(请先从共享盘复制)' return result wb = openpyxl.load_workbook(src, read_only=True, data_only=True) try: if config.DAILY_SHEET not in wb.sheetnames: result['message'] = f'{os.path.basename(src)} 缺少【{config.DAILY_SHEET}】' return result finally: wb.close() # 先确认导出明细齐全,再动表(缺文件时一张表都不清) sources = [p for p in config.glob_files(config.DETAIL_GLOB) if not os.path.basename(p).startswith('金色湖畔_')] if not sources: result['message'] = (f'未找到团购收益明细({config.DETAIL_GLOB}),' f'已跳过且未改动【{config.DAILY_SHEET}】;搜索目录:' + ';'.join(config.search_dirs())) return result rows = [] skipped = 0 exclude = tuple(str(x).strip() for x in config.DAILY_EXCLUDE_BUSINESS) for path in sources: for raw in _read_export(path): if _business_day(raw[config.DAILY_TIME_COL - 1]) != target: skipped += 1 continue # 目标 B(收益类型)取导出 4(业务类型:团购/其他) if exclude and str(raw[3] or '').strip() in exclude: continue rows.append([raw[src_i - 1] if src_i - 1 < len(raw) else None for src_i, _tgt in config.DAILY_EXPORT_TO_TARGET]) booking_files = config.glob_files('预订收益明细_*.xlsx') for path in booking_files: rows.extend(_read_booking(path, target)) if booking_files: config.log(f'预订收益明细 {len(booking_files)} 份已并入') result.update(detail_rows=len(rows), skipped_day=skipped) if not rows: result['message'] = (f'【{config.DAILY_SHEET}】营业日 {target} 没有可贴的明细' f'(导出里其它日期 {skipped} 行),未改动表') return result start = config.DAILY_DATA_START values = {start + i: row for i, row in enumerate(rows)} template = _template_formulas(src, config.DAILY_SHEET) formulas = {start + i: [_shift_formula(f, i) if f else None for f in template] for i in range(len(rows))} last_old = _last_data_row(src, config.DAILY_SHEET) result['replaced'] = max(0, last_old - start + 1) detail_total = round(sum(_to_number(row[15]) or 0.0 for row in rows), 2) result.update(total=detail_total, pivot_total=detail_total, report_total=detail_total, consistent=True) if dry_run: result.update(ok=True, message=f'[演练] 将贴 {len(rows)} 行到【{config.DAILY_SHEET}】' f'(替换原 {result["replaced"]} 行);明细合计 {detail_total:.2f}') return result try: sheet_xml.write_rows(src, config.DAILY_SHEET, values, formulas, start_row=start, last_row=last_old) except (OSError, RuntimeError, zipfile.BadZipFile) as e: result['message'] = f'写入【{config.DAILY_SHEET}】失败:{e}' config.log(result['message'], 'WARN') return result result['path'] = src do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com) refresh = com_refresh.refresh(src, sheets=['透视', config.DAILY_SHEET, config.REPORT_SHEET]) if do_com else \ {'ok': False, 'engine': '', 'message': '未启用 COM 刷新'} result['com_refresh'] = refresh pivot_total, report_total = detail_total, detail_total if refresh.get('ok'): try: wb2 = openpyxl.load_workbook(src, read_only=True, data_only=True) try: pivot_total = _sum_cached(wb2['透视'], 7) report_total = _sum_cached(wb2[config.REPORT_SHEET], 16) finally: wb2.close() except Exception as e: # noqa: BLE001 - 读不到就沿用复算值 config.log(f'COM 刷新后读合计失败,沿用复算值:{e}', 'WARN') elif do_com: config.log(f'透视未刷新({refresh.get("message")}),三口径为明细复算值', 'WARN') consistent = abs(pivot_total - report_total) < 0.01 note = '' if abs(detail_total - pivot_total) >= 0.01: note = (f';明细含 10 点前验券行,比透视多 ' f'{detail_total - pivot_total:.2f}(透视按 10 点切日归属前一天)') result.update(ok=True, total=detail_total, pivot_total=pivot_total, report_total=report_total, consistent=consistent, message=f'已贴 {len(rows)} 行到【{config.DAILY_SHEET}】' f'(原 {result["replaced"]} 行);明细 {detail_total:.2f}、' f'透视 {pivot_total:.2f}、报表 {report_total:.2f}' + note + ('' if consistent else '(透视与报表不一致!)')) if not consistent: config.log('透视与报表合计不一致,请检查报表公式引用范围', 'WARN') return result