# -*- coding: utf-8 -*- """马敏团购总表「对比」sheet 日滚动 + 清空(核对流程第一步)。 每天的总表副本是从**昨天的表**复制来的,所以副本里的「今日遗留」其实是昨天的数据: 先滚到「昨日遗留」,再把「今日遗留」清空等当天重算。两张 sheet 各处理一次: * 美团分支 → 「新美大对比 (2)」 * 抖音分支 → 「抖音对比(2)」 数据行 :data:`config.COMPARE_DATA_START`(第 5 行)到该 sheet 末行: 1. I/J/K 三列清空(上日核对结果); 2. Q「昨日遗留」= R「今日遗留」当前值 - S「漏核销」(R 是昨天填的),按值写入; 3. R「今日遗留」按【团购统计】「未消费项目个数」逐行回填(见 :mod:`compare_groups`); 4. 按 X 列(无表头的备注列)过滤昨日遗留:X 为空、或备注是「某某前消费」这类说明 → 昨日遗留保留;其它备注内容 → 昨日遗留清空; 5. 「漏核销」列清空(按标题定位,找不到只告警跳过); 6. 写盘后用 WPS/Excel COM 重算一次,再按 **E 门店 + F 项目分组**核 W 列「验证」: 组内求和为 0 才算平(``-`` / 空不参与),不平只出明细、不判失败。 幂等保护:若当前 R 列已等于按【团购统计】算出的回填值,说明今天已经填过/滚过,直接跳过—— 避免重复运行把「昨日遗留」也抹掉(``force=True`` 可强制重跑)。 写盘用 zip+XML 直接改单元格(保留透视、共享公式、外部链接),不走 openpyxl save。 """ import os import re import shutil import zipfile from datetime import date, datetime import openpyxl from openpyxl.utils import column_index_from_string as col from openpyxl.utils import get_column_letter as letter from .. import config from . import compare_groups, com_refresh, share_copy from .paste_to_master import (_CELL_RE, _ROW_RE, _col_num, _make_cell, _sheet_xml_path) from .zipio import open_zip class CompareError(RuntimeError): """对比表处理失败(sheet 缺失 / 列标题找不到 / 写盘失败)。""" def _norm(text): """表名/标题归一化:去空白,全角括号与星号转半角(表名两种写法都能对上)。""" s = str(text or '').strip() return re.sub(r'\s+', '', s).replace('(', '(').replace(')', ')').replace('*', '*') def _find_sheet(sheetnames, wanted): """按归一化名精确匹配,再退化为包含匹配;找不到返回空串。""" key = _norm(wanted) for name in sheetnames: if _norm(name) == key: return name for name in sheetnames: if key and key in _norm(name): return name return '' def _parse_day(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 master_path(day): return os.path.join(config.WORK_DIR, f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx') def _locate_columns(ws, max_col): """在前几行表头里定位「漏核销 / 昨日遗留 / 今日遗留」列号(1 起)。 Returns: ``(header_row, {'miss': 列号, 'yesterday': 列号, 'today': 列号})``,缺失的键不出现。 """ titles = {'miss': config.COMPARE_MISS_TITLE, 'yesterday': config.COMPARE_YESTERDAY_TITLE, 'today': config.COMPARE_TODAY_TITLE} best = (0, {}) for r in range(1, min(config.COMPARE_HEADER_SCAN_ROWS, int(ws.max_row or 0)) + 1): row = [ws.cell(r, c).value for c in range(1, max_col + 1)] found = {} for c, v in enumerate(row, 1): t = _norm(v) if not t: continue for key, title in titles.items(): if key not in found and _norm(title) in t: found[key] = c if len(found) > len(best[1]): best = (r, found) return best def _read_cells(path, sheet, max_col): """读数据区(第 5 行起)每行在需要的列上的值,返回 (值行列表, 末行号)。 只读一次、区间取列,避免 read_only 模式下逐格访问巨慢。 """ wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: ws = wb[sheet] rows = [] for row in ws.iter_rows(min_row=config.COMPARE_DATA_START, max_col=max_col, values_only=True): rows.append(list(row)) while rows and all(v is None for v in rows[-1]): rows.pop() last = config.COMPARE_DATA_START + len(rows) - 1 return rows, last finally: wb.close() def _to_number(value): """数值/数字文本 → float;#DIV/0!、空、异常返回 None。""" 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 _cell_value(row, cnum): """取数据行第 cnum 列(1 起)的值,越界返回 None。""" idx = int(cnum) - 1 return row[idx] if 0 <= idx < len(row) else None def _same_number(left, right): """判重用的相等判断:None 与 None 相同,数值按容差比较。""" a, b = compare_groups.to_number(left), compare_groups.to_number(right) if a is None or b is None: return a is None and b is None return abs(a - b) <= config.COMPARE_VERIFY_TOL def _locate_group_cols(ws, header_row, max_col): """找表头行里的门店/核销项目名称列:返回 (A/B 原始列, E/F 分组列)。 A/B 是透视原始名(回填今日遗留用它查团购统计),E/F 是分组用列 (F 带归并公式)。任一处找不到第 2 次出现时,E/F 回退配置的兜底列。 """ titles = config.COMPARE_GROUP_HEADERS found = {t: [] for t in titles} for c in range(1, max_col + 1): text = _norm(ws.cell(header_row, c).value) if not text: continue for title in titles: if text == _norm(title): found[title].append(c) raw, grp = [], [] for title, fallback in zip(titles, config.COMPARE_GROUP_FALLBACK_COLS): hits = found[title] raw.append(hits[0] if hits else col(fallback)) grp.append(hits[1] if len(hits) > 1 else col(fallback)) missing = [t for t in titles if len(found[t]) < 2] if missing: config.log(f'表头第 {header_row} 行没找到第 2 个「{"、".join(missing)}」,' f'分组列回退 {"、".join(config.COMPARE_GROUP_FALLBACK_COLS)}', 'WARN') return raw[0], raw[1], grp[0], grp[1] def _locate_title_col(ws, max_col, title, fallback_letter): """在前几行表头里找标题包含 title 的列;找不到回退 fallback_letter。""" for r in range(1, min(config.COMPARE_HEADER_SCAN_ROWS, int(ws.max_row or 0)) + 1): row = [ws.cell(r, c).value for c in range(1, max_col + 1)] for c, value in enumerate(row, 1): if value is not None and title in _norm(value): return c config.log(f'没找到「{title}」表头,回退 {fallback_letter} 列', 'WARN') return col(fallback_letter) def _rebuild_row(row_xml, row_no, edits): """按 ``{列号: 值或 None}`` 重建一行:指定列替换/清空(清空保留原样式),其余原样。""" cells, styles = {}, {} if row_xml: for m in _CELL_RE.finditer(row_xml): cnum = _col_num(m.group(1)) sm = re.search(r'\bs="(\d+)"', m.group(3) or '') if sm: styles[cnum] = sm.group(1) if cnum not in edits: cells[cnum] = m.group(0) for cnum, value in edits.items(): if value is None: s = f' s="{styles[cnum]}"' if cnum in styles else '' cells[cnum] = f'' else: cells[cnum] = _make_cell(row_no, cnum, value, styles.get(cnum, '')) return '{}'.format( row_no, ''.join(cell for _, cell in sorted(cells.items()))) def _patch_sheet(xml_text, edits_by_row): """把 ``{行号: {列号: 值}}`` 应用到 sheet XML(单次扫描 + 一次拼接,避免 O(n²))。""" pieces, handled, pos = [], set(), 0 for m in _ROW_RE.finditer(xml_text): mm = re.search(r'\br="(\d+)"', '') if not mm: continue row_no = int(mm.group(1)) if row_no not in edits_by_row: continue pieces.append(xml_text[pos:m.start()]) pieces.append(_rebuild_row(m.group(0), row_no, edits_by_row[row_no])) pos = m.end() handled.add(row_no) pieces.append(xml_text[pos:]) out = ''.join(pieces) missing = [r for r in sorted(edits_by_row) if r not in handled] if missing: extra = ''.join(_rebuild_row(None, r, edits_by_row[r]) for r in missing) out = out.replace('', extra + '', 1) return out def _write_sheet(path, sheet, edits_by_row): """zip+XML 写一个 sheet(其余部件原样搬运,保留透视/外部链接)。""" zf = open_zip(path) tmp = path + '.cmp.tmp' try: xml_path = _sheet_xml_path(zf, sheet) if not xml_path: raise CompareError(f'工作簿里找不到 sheet「{sheet}」的 XML') text = zf.read(xml_path).decode('utf-8', 'replace') patched = _patch_sheet(text, edits_by_row) with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst: for info in zf.infolist(): if info.is_dir(): continue zi = zipfile.ZipInfo(info.filename, date_time=info.date_time) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = info.external_attr data = patched.encode('utf-8') if info.filename == xml_path else zf.read(info) dst.writestr(zi, data) finally: zf.close() os.replace(tmp, path) def _plan_sheet(path, sheet, action, force, day): """为一张对比 sheet 生成 edits 计划(含今日遗留回填、退款冲减与判重)。""" wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: if sheet not in wb.sheetnames: raise CompareError(f'工作簿缺少 sheet「{sheet}」') probe = wb[sheet] max_col = max(int(probe.max_column or 1), max(col(c) for c in config.COMPARE_CLEAR_COLS), col(config.COMPARE_REMARK_COL)) header_row, cols = _locate_columns(probe, max_col) raw_store, raw_item, group_store, group_item = _locate_group_cols( probe, header_row, max_col) cols.update(store=group_store, item=group_item, verify=_locate_title_col(probe, max_col, config.COMPARE_VERIFY_TITLE, config.COMPARE_VERIFY_COL), platform_error=_locate_title_col( probe, max_col, config.COMPARE_PLATFORM_ERROR_TITLE, config.COMPARE_PLATFORM_ERROR_COL)) finally: wb.close() if 'today' not in cols: raise CompareError(f'「{sheet}」前 {config.COMPARE_HEADER_SCAN_ROWS} 行没找到' f'「{config.COMPARE_TODAY_TITLE}」列标题') if 'yesterday' not in cols: raise CompareError(f'「{sheet}」没找到「{config.COMPARE_YESTERDAY_TITLE}」列标题') rows, last = _read_cells(path, sheet, max([max_col] + list(cols.values()))) base = {'sheet': sheet, 'header_row': header_row, 'cols': cols, 'path': path} # 今日遗留回填计划:按 A 门店 + B 原始项目名,取【团购统计】「未消费项目个数」 types = config.COMPARE_STATS_TYPES.get(str(action or '').strip(), ()) stats = compare_groups.load_unused(path, types) # 退款/撤销核销:从本地美团 / 抖音表计数,同门店同项目从今日遗留扣掉 store_pool = sorted({str(_cell_value(row, cols['store']) or '').strip() for row in rows} - {''}) refund_plan = config.COMPARE_REFUND_GROUPS.get(str(action or '').strip()) refund = {'ok': False, 'counts': {}, 'rows': 0, 'unmatched': [], 'message': ''} if refund_plan: local = os.path.join(config.WORK_DIR, share_copy.table_name( refund_plan.get('book') or '', day, config.SHARE_TABLE_EXT)) refund = compare_groups.load_refunds(local, refund_plan, store_pool, day) fill = compare_groups.build_fill_edits(rows, stats['stats'], raw_store, raw_item, refunds=refund['counts']) base.update(fill=fill, stats=stats, refund=refund) if fill.get('skipped'): # 【团购统计】没有该平台数据时不动表:既不能回填今日遗留,滚动 Q 也无法判重 return dict(base, last=last, edits={}, kept=0, cleared=0, bad_num=0, prev_today_filled=0, miss_filled=0, skipped='', error=fill['skipped']) t_col, y_col = cols['today'], cols['yesterday'] # 判重:当前 R 已等于今天的回填值 → 判定今天已填过/滚过,不再重复滚动 already = bool(fill['edits']) and all( _same_number(_cell_value(row, t_col), fill['edits'].get(config.COMPARE_DATA_START + i)) for i, row in enumerate(rows)) if already and not force: return dict(base, last=last, edits={}, kept=0, cleared=0, bad_num=0, prev_today_filled=0, miss_filled=0, skipped='今日遗留已按团购统计回填过(与当前值一致)') if last < config.COMPARE_DATA_START: return dict(base, last=0, edits={}, kept=0, cleared=0, bad_num=0, prev_today_filled=0, miss_filled=0, skipped='无数据行') clear_cols = [col(c) for c in config.COMPARE_CLEAR_COLS] miss_col = cols.get('miss') x_col = col(config.COMPARE_REMARK_COL) keep_re = re.compile(config.COMPARE_KEEP_REMARK_RE) prev_today_filled = sum(1 for row in rows if _cell_value(row, t_col) not in (None, '')) miss_filled = sum(1 for row in rows if miss_col and _cell_value(row, miss_col) not in (None, '')) edits = {} kept = cleared = bad_num = 0 for offset, row in enumerate(rows): row_no = config.COMPARE_DATA_START + offset # X 列(无表头备注):空 或「某某前消费」→ 昨日遗留保留;其它备注 → 清空 remark = _cell_value(row, x_col) text = str(remark).strip() if remark is not None else '' keep = (not text) or bool(keep_re.search(text)) if keep: kept += 1 else: cleared += 1 prev_today = _cell_value(row, t_col) miss_val = _cell_value(row, miss_col) if miss_col else None today_num = _to_number(prev_today) miss_num = _to_number(miss_val) if (prev_today not in (None, '') and today_num is None) or \ (miss_val not in (None, '') and miss_num is None): bad_num += 1 # 非数字(错误值/文本)当 0 处理,单独计数提示 row_edits = {c: None for c in clear_cols} if miss_col: row_edits[miss_col] = None # 漏核销清空 # 昨日遗留 = 昨天的今日遗留 - 漏核销(缺哪边按 0 算);两边都空则清空 if keep and (prev_today not in (None, '') or miss_val not in (None, '')): q = (today_num or 0.0) - (miss_num or 0.0) row_edits[y_col] = int(q) if float(q).is_integer() else round(q, 2) else: row_edits[y_col] = None # 按备注清空 / 无值 if fill['edits']: row_edits[t_col] = fill['edits'].get(row_no) # 今日遗留 = 未消费 edits[row_no] = row_edits return dict(base, last=last, edits=edits, kept=kept, cleared=cleared, bad_num=bad_num, prev_today_filled=prev_today_filled, miss_filled=miss_filled, skipped='') def _verify_sheet(path, sheet, plan): """写盘/重算后重新读行,按 E/F 分组核 W 列。""" cols = plan['cols'] rows, _ = _read_cells(path, sheet, max(int(v) for v in cols.values())) return compare_groups.verify(rows, cols) def _fill_verify(result, verify): # groups 是明细用的中间结构(几千项),不塞进运行结果 result['verify'] = {k: v for k, v in verify.items() if k != 'groups'} result['groups_total'] = verify['total_groups'] result['groups_ok'] = verify['ok_groups'] result['unbalanced'] = verify['unbalanced'] result['unbalanced_count'] = verify['unbalanced_count'] result['verified'] = verify['ok'] def _log_stats(plan, sheet, target): stats = plan.get('stats') or {} if not stats.get('ok'): config.log(f'「{sheet}」团购统计不可用:{stats.get("message") or "未知原因"}', 'WARN') return config.log(stats.get('message') or '') day = stats.get('date') or '' if stats.get('stats') and day and day != target.isoformat(): config.log(f'【{config.COMPARE_STATS_SHEET}】消费日期 {day} 与营业日 ' f'{target.isoformat()} 不一致,可能未贴当天数据,回填结果需复核', 'WARN') def _log_refund(plan, sheet): """记录退款/撤销核销的取数与冲减结果。""" refund = plan.get('refund') or {} fill = plan.get('fill') or {} if not refund.get('ok'): if refund.get('message'): config.log(f'「{sheet}」退款冲减跳过:{refund["message"]}', 'WARN') return config.log(refund.get('message') or '') applied = fill.get('refund_applied') or [] if applied: heads = ';'.join(f'{a["store"]}/{a["item"]} -{a["count"]}' for a in applied[:6]) config.log(f'「{sheet}」退款/撤销核销冲减:{len(applied)} 个门店项目,' f'共 {sum(a["count"] for a in applied)} 笔:{heads}') leftover = fill.get('refund_unmatched') or [] if leftover: heads = ';'.join(f'{u["store"]}/{u["item"]} {u["count"]}笔' for u in leftover[:6]) config.log(f'「{sheet}」{len(leftover)} 个退款门店项目在对比表里没有对应行,未冲减:' f'{heads}', 'WARN') def run(day=None, action='check_meituan', dry_run=False, use_com=True, force=False, progress_from=0, progress_to=0): """执行对比 sheet 日滚动 + 今日遗留回填 + 分组验证。 Args: day: 营业日(决定总表副本文件名),默认今天。 action: ``check_meituan`` / ``check_douyin``,决定处理哪张 sheet 与取数类型。 dry_run: 只报告计划,不写文件。 use_com: 写盘后用 WPS/Excel COM 重算,让 W 列按新数据得出结果。 force: 忽略「今天已回填/滚动过」的判重。 progress_from / progress_to: 进度区间(0~100)。 Returns: dict(ok, message, path, sheet, rows, kept, cleared, skipped, stats_date, groups_total, groups_ok, unbalanced, unbalanced_count, verified, verify) """ target = _parse_day(day) or date.today() path = master_path(target) wanted = (config.COMPARE_SHEET_DOUYIN if str(action or '').strip() == config.ACTION_DOUYIN else config.COMPARE_SHEET_MEITUAN) result = {'ok': False, 'message': '', 'path': path, 'sheet': wanted, 'rows': 0, 'kept': 0, 'cleared': 0, 'skipped': '', 'com': None, 'stats_date': '', 'groups_total': 0, 'groups_ok': 0, 'unbalanced': [], 'unbalanced_count': 0, 'verified': False, 'meal_adjust': [], 'meal_skipped': [], 'refund_rows': 0, 'refund_applied': [], 'refund_unmatched': []} if not os.path.isfile(path): result['message'] = f'未找到马敏团购总表副本:{path}(请先从共享盘复制)' return result wb = openpyxl.load_workbook(path, read_only=True, data_only=True) try: sheet = _find_sheet(wb.sheetnames, wanted) finally: wb.close() if not sheet: result['message'] = f'总表里没有「{wanted}」sheet' return result result['sheet'] = sheet if progress_from or progress_to: config.progress(int(progress_from)) plan = _plan_sheet(path, sheet, action, force, target) cols = plan['cols'] fill = plan.get('fill') or {} result['rows'] = len(plan['edits']) result['fill_rows'] = fill.get('filled', 0) result['kept'] = plan.get('kept', 0) result['cleared'] = plan.get('cleared', 0) result['stats_date'] = (plan.get('stats') or {}).get('date') or '' _log_stats(plan, sheet, target) _log_refund(plan, sheet) result['refund_rows'] = (plan.get('refund') or {}).get('rows', 0) result['refund_applied'] = fill.get('refund_applied') or [] result['refund_unmatched'] = fill.get('refund_unmatched') or [] if plan.get('error'): result['message'] = f'「{sheet}」中止:{plan["error"]}' config.log(result['message'], 'WARN') return result if plan['skipped']: verify = _verify_sheet(path, sheet, plan) _fill_verify(result, verify) result.update(ok=True, skipped=plan['skipped'], message=f'「{sheet}」跳过:{plan["skipped"]};分组 {verify["total_groups"]} 组,' f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}') config.log(result['message']) return result config.log(f'「{sheet}」表头第 {plan["header_row"]} 行:分组列 ' f'{letter(cols["store"])}/{letter(cols["item"])},验证列 {letter(cols["verify"])},' f'昨日遗留 {letter(cols["yesterday"])}、今日遗留 {letter(cols["today"])}' + (f'、漏核销 {letter(cols["miss"])}' if cols.get('miss') else f'(未找到「{config.COMPARE_MISS_TITLE}」列,跳过该列)')) config.log(f'「{sheet}」今日遗留回填:{fill.get("filled", 0)} 行非零' + ('(来源【%s】)' % config.COMPARE_STATS_SHEET if fill.get('edits') else '(%s)' % (fill.get('skipped') or '无数据'))) if fill.get('unmatched'): # 常见于面值券别名(如「1240代1500随心兑」)在团购统计里没有对应核销项目名, # 回填为 0;只作提示,真正影响结果的行会在分组明细里体现。 config.log(f'「{sheet}」{len(fill["unmatched"])} 个项目在团购统计里没有记录,今日遗留留空:' + '、'.join(fill['unmatched'][:10])) config.log(f'「{sheet}」数据行 {config.COMPARE_DATA_START}~{plan["last"]}:' f'清空 {"".join(config.COMPARE_CLEAR_COLS)}' + ('/漏核销' if cols.get('miss') else '') + f',昨日遗留 = 表内原今日遗留({plan.get("prev_today_filled", 0)} 个非空)' + (f' - 漏核销({plan.get("miss_filled", 0)} 个非空)' if cols.get('miss') else ' - 0(无漏核销列)')) if plan.get('bad_num'): config.log(f'「{sheet}」{plan["bad_num"]} 行的今日遗留/漏核销不是数字,已按 0 参与计算,' f'请人工复核这些行', 'WARN') config.log(f'「{sheet}」{config.COMPARE_REMARK_COL} 列备注过滤:昨日遗留保留 {plan.get("kept", 0)} 行' f'(备注为空或含「前消费」),清空 {plan.get("cleared", 0)} 行(其它备注内容)') if dry_run: verify = _verify_sheet(path, sheet, plan) _fill_verify(result, verify) preview, _, _ = compare_groups.build_meal_edits(verify.get('groups') or {}) config.log(f'[演练]「{sheet}」分组验证(未重算,读旧缓存):{verify["total_groups"]} 组,' f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}' + (f';{len(preview)} 行将写平台结错' if preview else '')) result.update(ok=True, message=f'[演练]「{sheet}」将处理 {len(plan["edits"])} 行、' f'回填今日遗留 {fill.get("filled", 0)} 行(不写文件)') return result try: _write_sheet(path, sheet, plan['edits']) except (OSError, CompareError, zipfile.BadZipFile) as e: result['message'] = f'「{sheet}」写盘失败:{e}' config.log(result['message'], 'WARN') return result if progress_to: config.progress(int(progress_to)) # 写盘后重算一次,让 W 列「验证」公式按新数据得出结果 if use_com: result['com_after'] = com_refresh.refresh(path, sheets=[sheet]) if not result['com_after'].get('ok'): config.log(f'滚动后重算失败(W 列读的是旧缓存值):' f'{result["com_after"].get("message")}', 'WARN') else: config.log(f'「{sheet}」未启用 COM 重算,分组验证读的是旧缓存 W,结果仅供参考', 'WARN') verify = _verify_sheet(path, sheet, plan) # 前面步骤跑完仍不平、且是双人餐/三人餐的配对 → 在【平台结错】补 1 / -2(-3) meal_edits, meal_detail, meal_skipped = compare_groups.build_meal_edits( verify.get('groups') or {}) if meal_skipped: config.log(f'「{sheet}」{len(meal_skipped)} 对双人餐/三人餐未修正(基础行不为正):' + ';'.join(f'{d["store"]}/{d["item"]} 基础{d["sum"]:+g}' for d in meal_skipped[:5]), 'WARN') if meal_edits: heads = ';'.join(f'{d["store"]}/{d["item"]} N={d["times"]} ' f'餐行J={d["meal_j"]} 基础行J={d["base_j"]}' for d in meal_detail[:6]) config.log(f'「{sheet}」{len(meal_detail)} 对双人餐/三人餐仍不平,' f'写【{config.COMPARE_PLATFORM_ERROR_TITLE}】:{heads}') j_col = cols['platform_error'] try: _write_sheet(path, sheet, {row: {j_col: value} for row, value in meal_edits.items()}) except (OSError, CompareError, zipfile.BadZipFile) as e: config.log(f'「{sheet}」平台结错写入失败:{e}', 'WARN') else: if use_com: result['com_meal'] = com_refresh.refresh(path, sheets=[sheet]) if not result['com_meal'].get('ok'): config.log(f'平台结错后重算失败(验证读旧缓存):' f'{result["com_meal"].get("message")}', 'WARN') else: config.log(f'「{sheet}」未启用 COM 重算,平台结错后的验证读旧缓存', 'WARN') verify = _verify_sheet(path, sheet, plan) result['meal_adjust'] = meal_detail result['meal_skipped'] = meal_skipped _fill_verify(result, verify) if verify['ok']: config.log(f'「{sheet}」分组验证通过:{verify["total_groups"]} 组全部为 0') else: heads = ';'.join(f'{g["store"]}/{g["item"]} {g["diff"]:+g}' for g in verify['unbalanced'][:10]) config.log(f'「{sheet}」分组验证不平:{verify["unbalanced_count"]}/' f'{verify["total_groups"]} 组不为 0,前几组:{heads}', 'WARN') result.update(ok=True, message=f'「{sheet}」完成:处理 {len(plan["edits"])} 行,' f'今日遗留回填 {fill.get("filled", 0)} 行' + (f',平台结错修正 {len(meal_detail)} 对' if meal_detail else '') + f';分组 {verify["total_groups"]} 组,' f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}') config.log(result['message']) return result