diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/__init__.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/__init__.py new file mode 100644 index 0000000..1cb5d79 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/__init__.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +"""XQ0085 团购数据核对 —— 美团核对 + 抖音核对,两条独立分支。 + +从 XQ0041 抽出核对部分,插件自包含、不开浏览器、不做下载。共享盘全程只读: +先把当天的核对表从共享盘复制到本地 ``WORK_DIR/_work/``,后续所有处理只改本地副本。 + +* ``check_meituan``:复制共享表 → 订单收入明细合并+合计 → 基础信息补维护 + → 报表按值贴入本地马敏总表副本(平台-新美大 + CRM 团购统计); +* ``check_douyin``:复制共享表 → 核销明细 A~BR 重贴 → 四口径预计收入合计校验 + → 基础信息补维护 → 抖音报表 N~Z 按值贴入本地总表副本(平台-抖音)。 +""" +import os +from datetime import date, datetime, timedelta + +from webhost.backend.plugins.base import PLUGINS, ScenePlugin + +from . import config +from .logic import base_info_sync, daily_detail, douyin_daily, paste_to_master, share_copy + +ACTION_CHECK_MEITUAN = 'check_meituan' +ACTION_CHECK_DOUYIN = 'check_douyin' +ACTIONS = (ACTION_CHECK_MEITUAN, ACTION_CHECK_DOUYIN) + + +def _parse_day(s): + for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'): + try: + return datetime.strptime(str(s).strip(), fmt).date() + except (ValueError, TypeError, AttributeError): + continue + return None + + +def _resolve_action(fields): + raw = str(fields.get('action') or '').strip().lower() + if raw in ACTIONS: + return raw + return ACTION_CHECK_MEITUAN + + +def _check_day(fields): + """核对营业日:界面指定优先,否则按收益明细结束日期,再否则今天。""" + day = _parse_day(fields.get('daily_day')) or _parse_day(fields.get('profit_date_to')) + return day or date.today() + + +class Xq0085Plugin(ScenePlugin): + id = 'xq0085' + name = '团购数据核对' + version = '1.0.0' + description = ('团购数据核对(美团 + 抖音两条独立分支,共享盘只读):' + '先把当天的核对表从共享盘复制到本地 _work,再全部在本地副本上处理。' + '美团核对:团购+预订收益明细合并贴入【订单收入明细表】、明细/透视/报表三口径合计校验、' + '报表 #N/A 基础信息补维护、报表按值贴入马敏总表【平台-新美大】与 CRM【团购统计】。' + '抖音核对:导出核销明细 A~BR 重贴【核销明细】、明细/透视/报表/转换四口径预计收入合计校验、' + '报表 O/P 基础信息补维护、报表按值贴入【平台-抖音】。') + platform = '' + uses_month = False + capabilities = ['xq0085'] + permissions = {'platforms': []} + + fields = { + 'action': {'type': 'string', 'title': '核对分支', 'default': ACTION_CHECK_MEITUAN, + 'enum': list(ACTIONS)}, + 'daily_day': {'type': 'string', 'title': '核对营业日', 'default': '', + 'description': 'YYYY-MM-DD;留空=今天'}, + 'save_dir': {'type': 'string', 'title': '本地工作目录', 'default': ''}, + 'share_root': {'type': 'string', 'title': '共享核对表根目录', 'default': ''}, + 'copy_share_table': {'type': 'boolean', 'title': '从共享盘复制当天的表到本地(只读)', + 'default': True}, + 'run_daily_detail': {'type': 'boolean', 'title': '美团-订单收入明细(合并+合计)', + 'default': True}, + 'run_base_info': {'type': 'boolean', 'title': '美团-基础信息补维护(报表 #N/A)', + 'default': True}, + 'run_paste_master': {'type': 'boolean', 'title': '按值贴入马敏总表(只写本地副本)', + 'default': True}, + 'run_douyin_daily': {'type': 'boolean', 'title': '抖音-核销明细重贴+四口径合计', + 'default': True}, + 'run_douyin_base': {'type': 'boolean', 'title': '抖音-基础信息补维护(报表 O/P)', + 'default': True}, + 'use_com_refresh': {'type': 'boolean', + 'title': '用 WPS/Excel COM 刷新透视(推荐)', + 'default': True}, + 'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False}, + 'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False}, + } + + def run(self, fields, ctx): + fields = fields or {} + config.set_log(ctx.log) + config.set_progress(ctx.progress) + config.set_debug(fields.get('debug_mode')) + config.set_work_dir(fields.get('save_dir')) + + action = _resolve_action(fields) + day = _check_day(fields) + dry = bool(fields.get('dry_run')) + use_com = bool(fields.get('use_com_refresh', True)) + share_root = str(fields.get('share_root') or '').strip() + copy_share = bool(fields.get('copy_share_table', True)) + detail = {'action': action, 'day': day.isoformat(), 'share': None, + 'daily': None, 'base_info': None, 'paste': None, + 'douyin': None, 'results': {}} + + config.log(f'== {self.name} {action} 营业日 {day.isoformat()} ' + + ('(只核对不写入)' if dry else '') + ' ==') + ctx.progress(3) + + # ---------- 第 1 步:共享盘只读复制当天表到本地 ---------- + if copy_share: + keywords = ([config.SHARE_TABLE_KEYWORD, config.LINK_BOOK] + if action == ACTION_CHECK_MEITUAN + else [config.DOUYIN_SHARE_KEYWORD, config.LINK_BOOK]) + sc = share_copy.copy_prev_tables(share_root=share_root, day=day, + keywords=keywords, dry_run=dry) + config.log(sc.get('message') or '') + detail['share'] = sc + if not sc.get('ok'): + config.log(f'共享表复制不完整:{sc.get("message")}', 'WARN') + + ctx.progress(20) + + if action == ACTION_CHECK_MEITUAN: + self._run_meituan(fields, day, dry, use_com, detail, ctx) + else: + self._run_douyin(fields, day, dry, use_com, detail, ctx) + + ctx.progress(100) + parts = [f'美团核对' if action == ACTION_CHECK_MEITUAN else '抖音核对'] + if detail['daily'] and detail['daily'].get('ok'): + d = detail['daily'] + parts.append(f'明细{d["detail_rows"]}行 合计{d["total"]:.2f}') + if detail['douyin'] and detail['douyin'].get('ok'): + d = detail['douyin'] + parts.append(f'核销明细{d["detail_rows"]}行 四口径' + f'{d["detail_total"]:.2f}/{d["pivot_total"]:.2f}/' + f'{d["report_total"]:.2f}/{d["convert_total"]:.2f}') + if detail['paste'] and detail['paste'].get('ok'): + p = detail['paste'] + parts.append(f'总表粘贴 新美大{p["meituan_rows"]}/团购{p["group_rows"]}/' + f'抖音{p["douyin_rows"]}行') + config.log('完成:' + ';'.join(parts)) + return {'ok': True, 'message': ';'.join(parts), 'detail': detail} + + def _run_meituan(self, fields, day, dry, use_com, detail, ctx): + if bool(fields.get('run_daily_detail', True)): + ctx.progress(35) + d = daily_detail.run(day=day, dry_run=dry, use_com=use_com) + config.log(d.get('message') or '') + detail['daily'] = d + if not d.get('ok'): + config.log(f'订单收入明细未完成:{d.get("message")}', 'WARN') + if bool(fields.get('run_base_info', True)): + ctx.progress(55) + local = (detail['daily'] or {}).get('path') or '' + bi = base_info_sync.run(local, dry_run=dry) + config.log(bi.get('message') or '') + detail['base_info'] = bi + if bi.get('ok') and (bi.get('new_shops') or bi.get('new_items')): + config.log(f'基础信息需补维护:新增门店 {len(bi["new_shops"])} / ' + f'套餐 {len(bi["new_items"])}', 'WARN') + if bool(fields.get('run_paste_master', True)): + ctx.progress(75) + pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['meituan', 'group']) + config.log(pm.get('message') or '') + detail['paste'] = pm + if not pm.get('ok'): + config.log(f'马敏总表粘贴未完成:{pm.get("message")}', 'WARN') + + def _run_douyin(self, fields, day, dry, use_com, detail, ctx): + if bool(fields.get('run_douyin_daily', True)): + ctx.progress(35) + dy = douyin_daily.run(day=day, dry_run=dry, use_com=use_com) + config.log(dy.get('message') or '') + detail['douyin'] = dy + if not dy.get('ok'): + config.log(f'抖音核对未完成:{dy.get("message")}', 'WARN') + if bool(fields.get('run_douyin_base', True)): + # 基础信息检查已含在 douyin_daily 里;这里只把结果单独记一份 + detail['base_info'] = (detail['douyin'] or {}).get('base_info') + if bool(fields.get('run_paste_master', True)): + ctx.progress(75) + pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['douyin']) + config.log(pm.get('message') or '') + detail['paste'] = pm + if not pm.get('ok'): + config.log(f'平台-抖音粘贴未完成:{pm.get("message")}', 'WARN') + + +PLUGINS.append(Xq0085Plugin) diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/_pack.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/_pack.py new file mode 100644 index 0000000..34ca8b9 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/_pack.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +"""xq0085 团购数据核对 打包脚本:生成 dist-plugin/xq0085_v<版本>.zip。 + +用法:.venv\\Scripts\\python.exe plugins\\XQ0001-0100\\XQ0085 团购数据核对\\_pack.py +""" +import json +import os +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.abspath(os.path.join(HERE, '..', '..', '..')) +OUT = os.path.join(ROOT, 'dist-plugin') + +with open(os.path.join(HERE, 'plugin.json'), encoding='utf-8') as fp: + manifest = json.load(fp) +name = 'xq%s_v%s.zip' % (manifest['id'].replace('xq', ''), manifest['version']) +os.makedirs(OUT, exist_ok=True) +target = os.path.join(OUT, name) + +with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as zf: + for dirpath, _, files in os.walk(HERE): + for f in files: + if f == '_pack.py' or f.endswith('.pyc'): + continue + full = os.path.join(dirpath, f) + zf.write(full, os.path.relpath(full, HERE)) +print(target) diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/config/__init__.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/config/__init__.py new file mode 100644 index 0000000..61191c7 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/config/__init__.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +"""xq0085 团购数据核对 —— 配置常量与全局钩子。 + +从 XQ0041 抽出「美团核对」「抖音核对」两条线,插件自包含: +只依赖标准库 / 第三方库 / 底座注入的 RunContext。 +共享盘全程只读,所有表先复制到本地 ``WORK_DIR/_work/`` 再处理。 +""" +import os +import time + +# ==================== 全局钩子(run() 启动时注入) ==================== +_log = None +_progress = None +_debug = False + + +def set_log(fn): + global _log + _log = fn + + +def set_progress(fn): + global _progress + _progress = fn + + +def set_debug(on): + global _debug + _debug = bool(on) + + +def debug_enabled(): + return _debug + + +def log(msg, level='INFO'): + text = f'[{time.strftime("%H:%M:%S")}] {msg}' + if level == 'DEBUG' and not _debug: + return + if _log: + _log(str(msg), level) + else: + print(f'[{level}] {text}') + + +def progress(pct): + if _progress: + try: + _progress(int(pct)) + except Exception: + pass + + +# ==================== 工作目录 ==================== +DEFAULT_WORK_DIR = r'D:\资料\财务\新美大平台核对' +WORK_DIR = DEFAULT_WORK_DIR + + +def set_work_dir(path=None): + """界面「保存目录」覆盖默认目录;留空回默认。返回实际生效目录。""" + global WORK_DIR + p = str(path or '').strip().strip('"').strip() + WORK_DIR = p or DEFAULT_WORK_DIR + return WORK_DIR + + +# ==================== 共享盘(只读) ==================== +SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG' +SHARE_CHECK_ROOT = SHARE_ROOT +SHARE_TABLE_KEYWORD = '美团' +DOUYIN_SHARE_KEYWORD = '抖音' +SHARE_TABLE_EXT = '.xlsx' +LINK_BOOK = '马敏团购总表' +DAILY_WORK_DIR = '_work' # 共享表拉下来的本地副本目录 + +# ==================== 美团:订单收入明细表 ==================== +PROFIT_HEADER_ROW = 2 +DETAIL_GLOB = '团购收益明细_*.xlsx' +DAILY_SHEET = '订单收入明细表' +DAILY_HEADER_ROW = 3 +DAILY_DATA_START = 4 +DAILY_EXCLUDE_BUSINESS = ('其他',) + +# ==================== 美团:基础信息补维护 ==================== +BASE_SHEET = '基础信息' +REPORT_SHEET = '报表' +REPORT_DATA_START = 5 +BASE_INFO_ROW = 3 +BASE_ITEM_ROW = 2 +BASE_INFO_VLOOKUP_MAX = 1973 +BASE_ITEM_VLOOKUP_MAX = 12924 +BASE_RANGE_WARN_RATIO = 0.9 +STORE_MAP_FILE = '门店映射表.json' + +# ==================== 马敏团购总表:按值粘贴 ==================== +MASTER_SHEET_MEITUAN = '平台-新美大' +MASTER_SHEET_DOUYIN = '平台-抖音' +MASTER_SHEET_GROUP_STATS = '团购统计' +MEITUAN_REPORT_COLS = ('I', 'P') +DOUYIN_REPORT_COLS = ('N', 'Z') +MASTER_DATA_START = 5 +GROUP_STATS_DATA_START = 2 +CRM_EXPORT_DIR = r'D:\资料\财务\CRM数据导出' +CRM_GROUP_PAY_PREFIX = '团购支付数据' +DOUYIN_WORK_DIR = r'D:\资料\财务\抖音平台核对' +DOUYIN_TABLE_PREFIX = '抖音' +DOUYIN_TABLE_EXT = '.xlsx' + +# ==================== 抖音:核销明细 → 四口径 ==================== +DOUYIN_DETAIL_GLOB = '核销明细*.xlsx' +DY_HEADER_ROW = 1 # 导出核销明细的表头行 +DY_DETAIL_DATA_START = 2 # 目标【核销明细】数据起始行 +DY_DETAIL_PASTE_LAST_COL = 'BR' # 源表粘贴列 A~BR +DY_DETAIL_TIME_COL = 'BS' # 目标【核销明细】核销时间列(筛选) +DY_DETAIL_STATUS_COL = 'I' # 核销状态列 +DY_DETAIL_INCOME_COL = 'AF' # 预计收入列(需转数字) +DY_STATUS_VALUE = '已核销' +DY_PIVOT_SHEET = '透视' +DY_PIVOT_INCOME_COL = 'K' +DY_REPORT_INCOME_COL = 'Y' +DY_CONVERT_SHEET = '转换' +DY_CONVERT_TIME_COL = 'BQ' +DY_CONVERT_INCOME_COL = 'AE' +DY_BASE_SHEET = '基础信息' +DY_REPORT_SHOP_COL = 'O' # 报表 O/P 乱码 → 新增门店/项目 +DY_REPORT_ITEM_COL = 'P' +DY_BASE_INFO_ROW = 5 # 基础信息门店映射起始行 +DY_BASE_ITEM_ROW = 5 # 基础信息品项映射起始行 + +# ==================== 运行参数 ==================== +RETRY_MAX = 3 +USE_COM_REFRESH = True # 贴数后用 WPS/Excel COM 真正刷新透视与公式(失败自动回退复算) diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/__init__.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/__init__.py new file mode 100644 index 0000000..b1a5b1b --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/__init__.py @@ -0,0 +1,2 @@ +# -*- coding: utf-8 -*- +"""xq0085 核对逻辑子包。""" diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/base_info_sync.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/base_info_sync.py new file mode 100644 index 0000000..24121c0 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/base_info_sync.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +"""基础信息补维护:检查【报表】里 VLOOKUP 补不到(#N/A)的新增门店/新增套餐。 + +比对【报表】A/B 列与【基础信息】A/E 列,新增项写入本地副本。 +同时检查固定 VLOOKUP 范围上界:到 90% 提示扩范围,超界提示人工改公式(不改表)。 +""" +import glob +import json +import os +from difflib import SequenceMatcher + +import openpyxl + +from .. import config + +COL_BI_A = 1 +COL_BI_B = 2 +COL_BI_E = 5 +COL_BI_F = 6 + + +def _read_report_pairs(ws): + pairs = [] + seen = set() + for r in range(config.REPORT_DATA_START, int(ws.max_row or 0) + 1): + shop = str(ws.cell(r, 1).value or '').strip() + item = str(ws.cell(r, 2).value or '').strip() + if shop and shop != '0' and (shop, item) not in seen: + seen.add((shop, item)) + pairs.append((shop, item)) + return pairs + + +def _column_values(ws, col, start_row): + values = set() + last = start_row - 1 + for r in range(start_row, int(ws.max_row or 0) + 1): + v = str(ws.cell(r, col).value or '').strip() + if v and v != '0': + values.add(v) + last = r + return values, last + + +def _load_shop_map(): + path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE) + try: + with open(path, encoding='utf-8-sig') as fp: + data = json.load(fp) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def _guess_shop(name, existing, shop_map): + for crm, info in shop_map.items(): + if not isinstance(info, dict): + continue + if str(info.get('shop') or info.get('门店') or '').strip() in existing: + if crm and (crm in name or name in crm): + return str(info.get('shop') or info.get('门店')).strip(), \ + str(info.get('brand') or info.get('品牌') or '').strip() + best, score = '', 0.0 + for e in existing: + s = SequenceMatcher(None, name, e).ratio() + if s > score: + best, score = e, s + return (best if score >= 0.45 else ''), '' + + +def _guess_item(name): + if '【' in name and '】' in name: + return name.split('【', 1)[1].split('】', 1)[0].strip() + return '' + + +def run(table_path='', dry_run=False): + src = str(table_path or '').strip() + if not src: + cands = glob.glob(os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, '美团*.xlsx')) + src = cands[0] if cands else '' + result = {'ok': False, 'message': '', 'path': src, + 'new_shops': [], 'new_items': [], 'range_warnings': []} + if not src or not os.path.isfile(src): + result['message'] = '未找到本地美团核对表副本' + return result + + wb = openpyxl.load_workbook(src, data_only=False) + try: + if config.BASE_SHEET not in wb.sheetnames or config.REPORT_SHEET not in wb.sheetnames: + result['message'] = f'{os.path.basename(src)} 缺少【{config.BASE_SHEET}】或【{config.REPORT_SHEET}】' + return result + base = wb[config.BASE_SHEET] + report = wb[config.REPORT_SHEET] + pairs = _read_report_pairs(report) + shops, last_a = _column_values(base, COL_BI_A, config.BASE_INFO_ROW) + items, last_e = _column_values(base, COL_BI_E, config.BASE_ITEM_ROW) + shop_map = _load_shop_map() + + new_shops, new_items = [], [] + for shop, item in pairs: + if shop not in shops: + internal, brand = _guess_shop(shop, shops, shop_map) + new_shops.append({'crm': shop, 'internal': internal, 'brand': brand}) + if item: + internal_item = _guess_item(item) + if internal_item and internal_item not in items: + new_items.append({'crm': item, 'internal': internal_item}) + + warnings = [] + for name, last, limit in ( + ('门店映射(A~B)', last_a, config.BASE_INFO_VLOOKUP_MAX), + ('品项映射(E~F)', last_e, config.BASE_ITEM_VLOOKUP_MAX), + ): + ratio = last / float(limit) if limit else 0.0 + if last > limit: + warnings.append(f'{name}已到第 {last} 行,超出报表公式上界 {limit};' + f'超出部分查不到,需要人工把 VLOOKUP 范围改大') + elif ratio >= config.BASE_RANGE_WARN_RATIO: + warnings.append(f'{name}已到第 {last} 行(上界 {limit},' + f'已用 {ratio:.0%}),建议尽快扩范围') + result['range_warnings'] = warnings + for warning in warnings: + config.log(warning, 'WARN') + + result.update(new_shops=new_shops, new_items=new_items) + if dry_run: + result.update(ok=True, message=f'[演练] 新增门店 {len(new_shops)} / ' + f'套餐 {len(new_items)}') + return result + + changed = 0 + r = last_a + 1 + for entry in new_shops: + internal = entry['internal'] or entry['crm'] + if internal in shops or not entry['crm']: + continue + base.cell(r, COL_BI_A, entry['crm']) + base.cell(r, COL_BI_B, internal) + if entry['brand']: + base.cell(r, 3, entry['brand']) + shops.add(entry['crm']) + r += 1 + changed += 1 + r = last_e + 1 + for entry in new_items: + if entry['internal'] in items: + continue + base.cell(r, COL_BI_E, entry['crm']) + base.cell(r, COL_BI_F, entry['internal']) + items.add(entry['internal']) + r += 1 + changed += 1 + if changed: + wb.save(src) + result.update(ok=True, path=src, + message=f'基础信息补维护:新增门店 {len(new_shops)} / ' + f'套餐 {len(new_items)},写入 {changed} 行到本地副本') + return result + finally: + wb.close() diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/com_refresh.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/com_refresh.py new file mode 100644 index 0000000..09c5d34 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/com_refresh.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +"""用 WPS/Excel COM 真正刷新透视表 + 重算公式缓存(本地副本)。 + +项目里已有成熟模式(XQ0037 / XQ0052):优先 ``Ket.Application``(WPS 表格), +失败退 ``Excel.Application``。只刷新本地 ``_work/`` 副本,不碰共享盘。 + +对外: + refresh(path, sheets=None) -> {"ok", "engine", "message"} + * ``PivotCaches().RefreshAll()`` 刷新所有透视缓存; + * 每个指定 sheet 的 ``PivotTables().RefreshTable()`` 兜底; + * ``CalculateFullRebuild()`` 全量重算(含数组公式),再 ``Save()``。 + available() -> 是否具备 pywin32 + 可用 COM 引擎。 +""" +import os + +_CACHED_PROGID = None + + +def _import_com(): + try: + import pythoncom + import win32com.client + return pythoncom, win32com.client + except ImportError: + return None, None + + +def available(): + """探测本机是否有 WPS 表格 / Excel COM(不发任何写操作)。""" + global _CACHED_PROGID + pythoncom, win32 = _import_com() + if pythoncom is None: + return False, '缺少 pywin32' + if _CACHED_PROGID: + return True, _CACHED_PROGID + for prog, engine in (('Ket.Application', 'WPS'), ('Excel.Application', 'Excel')): + app = None + try: + app = win32.Dispatch(prog) + _CACHED_PROGID = prog + return True, engine + except Exception: + continue + finally: + del app + return False, '未检测到 WPS 表格 / Excel COM' + + +def refresh(path, sheets=None, timeout_note=''): + """刷新指定工作簿的透视缓存与公式,并保存。 + + Args: + path: 本地 xlsx 绝对路径 + sheets: 需要兜底刷新透视表的 sheet 名列表(可选) + timeout_note: 仅用于日志说明(如「大表可能需 1-2 分钟」) + + Returns: + ``{"ok", "engine", "message"}``;COM 不可用时 ok=False 但不抛异常。 + """ + from .. import config + + path = os.path.abspath(path) + if not os.path.isfile(path): + return {'ok': False, 'engine': '', 'message': f'文件不存在:{path}'} + pythoncom, win32 = _import_com() + if pythoncom is None: + return {'ok': False, 'engine': '', 'message': '缺少 pywin32,无法刷新透视表'} + + ok_engine, note = available() + if not ok_engine: + return {'ok': False, 'engine': '', 'message': note} + + pythoncom.CoInitialize() + app = wb = None + engine = '' + try: + try: + app = win32.Dispatch(_CACHED_PROGID or 'Ket.Application') + engine = 'WPS' if 'Ket' in (_CACHED_PROGID or '') else 'Excel' + except Exception: + app = win32.Dispatch('Excel.Application') + engine = 'Excel' + app.DisplayAlerts = False + try: + same = [w for w in app.Workbooks + if os.path.normcase(str(getattr(w, 'FullName', '') or '')) == + os.path.normcase(path)] + wb = same[0] if same else app.Workbooks.Open(path, UpdateLinks=2) + already_open = bool(same) + + refreshed = 0 + try: + for cache in wb.PivotCaches(): + try: + cache.RefreshAll() + refreshed += 1 + except Exception: + pass + except Exception: + pass + for name in (sheets or []): + try: + for pt in wb.Worksheets(name).PivotTables(): + try: + pt.RefreshTable() + refreshed += 1 + except Exception: + pass + except Exception: + pass + try: + wb.Application.CalculateFullRebuild() + except Exception: + wb.Application.CalculateFull() + wb.Save() + config.log(f'COM 刷新完成({engine}{",复用已打开工作簿" if already_open else ""}' + f',刷新透视 {refreshed} 次):{os.path.basename(path)}') + return {'ok': True, 'engine': engine, + 'message': f'{engine} COM 已刷新透视/公式并保存({refreshed} 次)'} + finally: + try: + app.DisplayAlerts = True + except Exception: + pass + if wb is not None: + try: + wb.Close(SaveChanges=False) + except Exception: + pass + except Exception as e: + return {'ok': False, 'engine': engine, + 'message': f'{engine or "COM"} 刷新失败:{e}' + (f'({timeout_note})' if timeout_note else '')} + finally: + if app is not None: + try: + if app.Workbooks.Count == 0: + app.Quit() + except Exception: + pass + try: + pythoncom.CoUninitialize() + except Exception: + pass diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/daily_detail.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/daily_detail.py new file mode 100644 index 0000000..478c82e --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/daily_detail.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +"""美团核对:团购收益明细 + 预订收益明细 → 订单收入明细表,并算三口径当天合计。 + +* 删除团购明细的「订单类型/订单号」;预订明细归一化字段后合并(订单信息→套餐名) +* 每次清空 ``订单收入明细表`` 第 4 行到真实末行的 A~AI,再整体重贴(幂等) +* 公式列 AC/AD/AF/AG/AH/AI 按行下拉;AD=营业日(验券 hour<10 算前一天) +* 明细 P 合计 / 透视 G 复算 / 报表 P 合计三者交叉校验 +""" +import glob +import os +import re +from collections import defaultdict +from datetime import datetime, timedelta + +import openpyxl + +from .. import config +from . import com_refresh, share_copy + +COL_AI = 35 +COL_AD = 30 +# 团购收益明细 31 列(导出表的实际列序) +GROUP_COLS = ( + '订单类型', '订单号', '消费门店名称', 'CRM门店名称', '券号', '核销时间', '验券时间', + '业务类型', '团购类型', '商品名称', '数量', '总收入', '技术服务费', '营销费用', + '结算价', '项目一世', '项目一世数量', '项目一世金额', '技术费(项目一)', '营销费(项目一)', + '项目二世', '项目二世数量', '项目二世金额', '技术费(项目二)', '营销费(项目二)', + '项目三世', '项目三世数量', '项目三世金额', '技术费(项目三)', '营销费(项目三)', '备注' +) +# 目标表 A~AB:团购 31 列去掉 订单类型/订单号/关联买单订单号/券号 +TARGET_COLS = tuple(c for c in GROUP_COLS + if c not in ('订单类型', '订单号', '关联买单订单号/券号')) +G_IDX = {name: i for i, name in enumerate(GROUP_COLS)} + + +def _last_data_row(ws, start): + last = start - 1 + for r in range(start, int(ws.max_row or 0) + 1): + if any(ws.cell(r, c).value is not None for c in range(1, 5)): + last = r + return last + + +def _to_number(value): + if value is None or value == '': + return 0.0 + if isinstance(value, (int, float)): + return float(value) + return float(str(value).replace(',', '').replace('¥', '').strip() or 0) + + +def _as_date(value): + if isinstance(value, datetime): + return value.date() + if hasattr(value, 'year') and hasattr(value, 'month') and hasattr(value, 'day'): + 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 _prev_month_last_day(day): + first = day.replace(day=1) + return first - timedelta(days=1) + + +def business_day(value, prev_month_last_day): + """复刻 Excel AD:验券 hour<10 算前一天;1 号凌晨算上月最后一天。""" + d = _as_date(value) + if not d: + return None + hour = value.hour if isinstance(value, datetime) else 0 + if hour < 10: + if d.day == 1: + return prev_month_last_day + return d - timedelta(days=1) + return d + + +def _sum_cached(ws, income_col, target=None): + """读缓存列求和。target 给定时按 AD 营业日(30) 与 C 业务类型(3) 筛选。""" + total = 0.0 + for r in range(config.DAILY_DATA_START, int(ws.max_row or 0) + 1): + if target is not None: + day_val = ws.cell(r, 30).value # AD 营业日(日号) + if day_val is None or int(day_val) != target.day: + continue + if str(ws.cell(r, 3).value or '').strip() in config.DAILY_EXCLUDE_BUSINESS: + continue + v = ws.cell(r, income_col).value + if isinstance(v, (int, float)): + total += float(v) + return round(total, 2) + + +def _write_formulas(ws, row): + ws.cell(row, 29).value = f'=IF(OR(O{row}="",O{row}=0),0,O{row})' + ws.cell(row, 30).value = ( + f'=IF(HOUR(G{row})<10,IF(DAY(INT(G{row}))=1,$AE$2,DAY(INT(G{row}))-1),' + f'DAY(INT(G{row})))') + ws.cell(row, 32).value = f'=IF(J{row}="其他","否","是")' + ws.cell(row, 33).value = f'=VLOOKUP(C{row},基础信息!$A$3:$B$1973,2,0)' + ws.cell(row, 34).value = f'=VLOOKUP(D{row},基础信息!$E$2:$F$12924,2,0)' + ws.cell(row, 35).value = f'=IF(AC{row}=0,0,ROUND(O{row}/AC{row},2))' + + +def _read_rows(path, header_row): + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + try: + ws = wb[wb.sheetnames[0]] + rows = list(ws.iter_rows(min_row=header_row + 1, values_only=True)) + return [list(r) for r in rows if any(v is not None for v in r)] + finally: + wb.close() + + +def _normalize_booking(row): + """预订明细按列名映射到团购 31 列;订单信息 → 套餐名。""" + out = [''] * len(GROUP_COLS) + aliases = { + '消费门店名称': ('消费门店名称', '门店', '消费门店'), + 'CRM门店名称': ('CRM门店名称', 'CRM门店'), + '券号': ('券号', '券码', '核销码'), + '验券时间': ('验券时间', '核销时间', '使用时间'), + '核销时间': ('核销时间', '验券时间'), + '业务类型': ('业务类型',), + '团购类型': ('团购类型', '订单类型'), + '商品名称': ('套餐名', '商品名称', '商品名', '订单信息', '项目名称'), + '数量': ('数量', '核销数量'), + '总收入': ('总收入', '收入', '到账金额'), + '技术服务费': ('技术服务费', '服务费'), + '营销费用': ('营销费用', '营销费'), + '结算价': ('结算价', '预计收入', '商家实收'), + } + for target, names in aliases.items(): + for name in names: + if name in row: + out[G_IDX[target]] = row[name] + break + return out + + +def run(table_path='', day=None, dry_run=False, use_com=None): + work = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR) + target = _as_date(day) or _prev_month_last_day(datetime.now().date() + timedelta(days=1)) + prev_last = _prev_month_last_day(target) + + result = {'ok': False, 'message': '', 'path': '', 'total': 0.0, + 'pivot_total': 0.0, 'report_total': 0.0, 'consistent': False, + 'detail_rows': 0, 'groups': 0} + src = str(table_path or '').strip() + if not src: + pairs = glob.glob(os.path.join(work, share_copy.table_name( + config.SHARE_TABLE_KEYWORD, target, config.SHARE_TABLE_EXT))) + src = pairs[0] if pairs else '' + if not src or not os.path.isfile(src): + result['message'] = f'未找到本地美团核对表副本:{src or work}(请先从共享盘复制)' + return result + + wb = openpyxl.load_workbook(src, data_only=False) + try: + if config.DAILY_SHEET not in wb.sheetnames: + result['message'] = f'{os.path.basename(src)} 缺少【{config.DAILY_SHEET}】' + return result + ws = wb[config.DAILY_SHEET] + last = _last_data_row(ws, config.DAILY_DATA_START) + if last >= config.DAILY_DATA_START: + for r in range(config.DAILY_DATA_START, last + 1): + for c in range(1, COL_AI + 1): + ws.cell(r, c).value = None + start = config.DAILY_DATA_START + + detail = [] + for p in sorted(glob.glob(os.path.join(work, config.DETAIL_GLOB))): + if os.path.basename(p).startswith('金色湖畔_'): + continue + detail.extend(_read_rows(p, config.PROFIT_HEADER_ROW)) + for p in sorted(glob.glob(os.path.join(work, '预订收益明细_*.xlsx'))): + raw = _read_rows(p, config.PROFIT_HEADER_ROW) + if not raw: + continue + header = raw[0] + for r in raw[1:]: + detail.append(_normalize_booking(dict(zip(header, r)))) + + picked = [] + for row in detail: + if max(G_IDX.get('总收入', 0), G_IDX.get('结算价', 0)) >= len(row): + continue + if _to_number(row[G_IDX['总收入']]) <= 0: + continue + if str(row[G_IDX['业务类型']] or '').strip() in config.DAILY_EXCLUDE_BUSINESS: + continue + if business_day(row[G_IDX['验券时间']], prev_last) != target: + continue + picked.append(row) + + groups = defaultdict(float) + for i, row in enumerate(picked): + r = start + i + for c, name in enumerate(TARGET_COLS, start=1): + ws.cell(r, c).value = row[G_IDX[name]] + _write_formulas(ws, r) + key = (str(row[G_IDX['消费门店名称']] or '').strip(), + str(row[G_IDX['商品名称']] or '').strip()) + groups[key] += _to_number(row[G_IDX['结算价']]) + result['detail_rows'] = len(picked) + result['groups'] = len(groups) + + detail_total = round(sum(_to_number(r[G_IDX['结算价']]) for r in picked), 2) + pivot_total = round(sum(groups.values()), 2) + report_total = pivot_total + consistent = abs(pivot_total - detail_total) < 0.01 + + result.update(total=detail_total, pivot_total=pivot_total, + report_total=report_total, consistent=consistent) + + if dry_run: + result.update(ok=True, message=f'[演练] 将贴 {len(picked)} 行;三口径合计 ' + f'{detail_total:.2f}') + return result + + wb.close() + + # 保存后真正刷新透视缓存 + 公式,再读三口径(读不到则保留上面的复算值) + 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 + 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: + config.log(f'COM 刷新后读合计失败,沿用复算值:{e}', 'WARN') + elif do_com: + config.log(f'透视未刷新({refresh.get("message")}),三口径为按明细复算值', 'WARN') + + consistent = max(detail_total, pivot_total, report_total) - \ + min(detail_total, pivot_total, report_total) < 0.01 + result.update(ok=True, path=src, total=detail_total, pivot_total=pivot_total, + report_total=report_total, consistent=consistent, + message=f'已贴 {len(picked)} 行到【{config.DAILY_SHEET}】;' + f'明细/透视/报表合计 {detail_total:.2f}/' + f'{pivot_total:.2f}/{report_total:.2f}' + + ('' if consistent else '(不一致!)')) + if not consistent: + config.log('三口径合计不一致,请检查报表公式与透视缓存', 'WARN') + return result + finally: + try: + wb.close() + except Exception: + pass diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/douyin_daily.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/douyin_daily.py new file mode 100644 index 0000000..049dcab --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/douyin_daily.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +"""抖音核对:核销明细 → 四口径预计收入合计 + 报表 O/P 基础信息补维护。 + +步骤(对应需求): + +1. 本地副本 ``抖音M.D.xlsx``(由 share_copy 从共享盘只读复制而来); +2. 导出的「核销明细」A~BR 按值贴进【核销明细】,旧数据区清空重贴; +3. 筛 BS(核销时间)=营业日、I(核销状态)=已核销,AF(预计收入转数字) 合计 → 明细口径; +4. 【透视】K 列、【报表】Y 列、【转换】(BQ=营业日 & I=已核销) AE 列合计 → 另三口径; +5. 四个合计需一致(不等则 WARN,不擅自改公式/透视缓存); +6. 【报表】O/P 列乱码 → 新增门店/项目补进【基础信息】(只加检查与写入本地副本)。 + +与美团侧一致:openpyxl 读值、zip+XML 写值(保留透视/公式),共享盘全程只读。 +""" +import glob +import os +import re +from datetime import date, datetime, timedelta + +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 com_refresh, share_copy + + +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 _to_number(value): + if value is None or value == '': + return 0.0 + if isinstance(value, (int, float)): + return float(value) + return float(str(value).replace(',', '').replace('¥', '').replace('%', '').strip() or 0) + + +def _col(s): + return col(str(s).strip().upper()) + + +def _read_export_detail(path): + """导出核销明细:表头第 DY_HEADER_ROW 行,取 A~BR 列,全量数据。""" + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + try: + ws = wb[wb.sheetnames[0]] + hi = _col(config.DY_DETAIL_PASTE_LAST_COL) + rows = [list(r) for r in ws.iter_rows(min_row=config.DY_HEADER_ROW + 1, + min_col=1, max_col=hi, values_only=True)] + while rows and all(v is None for v in rows[-1]): + rows.pop() + return rows + finally: + wb.close() + + +def _detail_file(work_dir): + files = sorted(glob.glob(os.path.join(work_dir, config.DOUYIN_DETAIL_GLOB))) + return files[-1] if files else '' + + +def _local_table(day): + return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, + share_copy.table_name(config.DOUYIN_SHARE_KEYWORD, day, + config.SHARE_TABLE_EXT)) + + +def _sum_filtered(ws, time_col, status_col, income_col, target): + """按 时间=营业日 & 状态=已核销 过滤,累计预计收入(转数字)。""" + t, s, i = _col(time_col), _col(status_col), _col(income_col) + total = 0.0 + count = 0 + for r in range(config.DY_DETAIL_DATA_START, int(ws.max_row or 0) + 1): + if _as_date(ws.cell(r, t).value) != target: + continue + if str(ws.cell(r, s).value or '').strip() != config.DY_STATUS_VALUE: + continue + total += _to_number(ws.cell(r, i).value) + count += 1 + return round(total, 2), count + + +def _sum_column(ws, income_col, start_row=2): + i = _col(income_col) + total = 0.0 + for r in range(start_row, int(ws.max_row or 0) + 1): + total += _to_number(ws.cell(r, i).value) + return round(total, 2) + + +def _sheet_visible_rows(ws, col_letter, start_row=2): + """透视类 sheet:按指定列非空统计(不真正刷新缓存,只复算可见行)。""" + c = _col(col_letter) + return [r for r in range(start_row, int(ws.max_row or 0) + 1) + if ws.cell(r, c).value is not None] + + +def _write_detail_values(table_path, rows): + """按值重贴【核销明细】A~BR(zip+XML),返回写入函数供复用。""" + from .paste_to_master import _sheet_xml_path, _patch_sheet_xml, _write_master + # 直接复用 paste_to_master 的写盘入口(单 sheet、起始行 2) + return _write_master(table_path, + [('核销明细', rows, 1, config.DY_DETAIL_DATA_START)]) + + +def _base_info_check(workbook, dry_run=False): + """【报表】O/P 门店/项目与【基础信息】比对,新增项写回本地副本。""" + if config.REPORT_SHEET not in workbook.sheetnames or \ + config.DY_BASE_SHEET not in workbook.sheetnames: + return {'ok': False, 'message': '缺少【报表】或【基础信息】', + 'new_shops': [], 'new_items': []} + report = workbook[config.REPORT_SHEET] + base = workbook[config.DY_BASE_SHEET] + shop_col = _col(config.DY_REPORT_SHOP_COL) + item_col = _col(config.DY_REPORT_ITEM_COL) + pairs = [] + for r in range(config.REPORT_DATA_START, int(report.max_row or 0) + 1): + shop = str(report.cell(r, shop_col).value or '').strip() + item = str(report.cell(r, item_col).value or '').strip() + if shop and shop != '0' and (shop, item) not in pairs: + pairs.append((shop, item)) + known = set() + for r in range(config.DY_BASE_INFO_ROW, int(base.max_row or 0) + 1): + v = str(base.cell(r, 1).value or '').strip() + if v and v != '0': + known.add(v) + new_shops = [s for s, _ in pairs if s and s not in known] + new_items = [] + for _, item in pairs: + if '【' in item and '】' in item: + name = item.split('【', 1)[1].split('】', 1)[0].strip() + if name and name not in known: + new_items.append(name) + changed = 0 + if not dry_run: + r = max(int(base.max_row or 0) + 1, config.DY_BASE_INFO_ROW) + for name in dict.fromkeys(new_shops + new_items): + if name in known: + continue + base.cell(r, 1, name) + known.add(name) + r += 1 + changed += 1 + return {'ok': True, 'new_shops': new_shops, 'new_items': new_items, + 'written': changed, + 'message': f'基础信息检查:新增门店 {len(new_shops)} / 项目 {len(new_items)}' + + ('' if dry_run else f',写入 {changed} 行')} + + +def run(day=None, dry_run=False, use_com=None): + target = _as_date(day) or date.today() + result = {'ok': False, 'message': '', 'path': '', 'day': target.isoformat(), + 'detail_rows': 0, 'detail_total': 0.0, 'pivot_total': 0.0, + 'report_total': 0.0, 'convert_total': 0.0, 'consistent': False, + 'base_info': None} + table = _local_table(target) + if not os.path.isfile(table): + result['message'] = f'未找到本地抖音核对表副本:{table}(请先从共享盘复制)' + return result + + export = _detail_file(config.WORK_DIR) + if not export: + result['message'] = f'未找到导出的核销明细({config.DOUYIN_DETAIL_GLOB})' + return result + + rows = _read_export_detail(export) + if not rows: + result['message'] = f'核销明细导出为空:{export}' + return result + + wb = openpyxl.load_workbook(table, data_only=True) + try: + if '核销明细' not in wb.sheetnames: + result['message'] = f'{os.path.basename(table)} 缺少【核销明细】' + return result + detail_ws = wb['核销明细'] + detail_total, detail_count = _sum_filtered( + detail_ws, config.DY_DETAIL_TIME_COL, config.DY_DETAIL_STATUS_COL, + config.DY_DETAIL_INCOME_COL, target) + + pivot_total = 0.0 + if config.DY_PIVOT_SHEET in wb.sheetnames: + pivot_total = _sum_column(wb[config.DY_PIVOT_SHEET], config.DY_PIVOT_INCOME_COL) + report_total = 0.0 + if config.REPORT_SHEET in wb.sheetnames: + report_total = _sum_column(wb[config.REPORT_SHEET], config.DY_REPORT_INCOME_COL) + convert_total = 0.0 + if config.DY_CONVERT_SHEET in wb.sheetnames: + convert_total, _ = _sum_filtered( + wb[config.DY_CONVERT_SHEET], config.DY_CONVERT_TIME_COL, + config.DY_DETAIL_STATUS_COL, config.DY_CONVERT_INCOME_COL, target) + + totals = (detail_total, pivot_total, report_total, convert_total) + consistent = max(totals) - min(totals) < 0.01 + result.update(detail_rows=len(rows), detail_total=detail_total, + pivot_total=pivot_total, report_total=report_total, + convert_total=convert_total, consistent=consistent) + + base_info = _base_info_check(wb, dry_run=True) + result['base_info'] = base_info + + if dry_run: + result.update(ok=True, + message=f'[演练] 核销明细 {len(rows)} 行;四口径 ' + f'{detail_total}/{pivot_total}/{report_total}/{convert_total}' + + ('' if consistent else '(不一致)')) + return result + + _write_detail_values(table, rows) + # 基础信息写入需要可保存的 workbook;zip+XML 不影响,单独用 openpyxl 追加 + if base_info.get('ok') and (base_info['new_shops'] or base_info['new_items']): + wb2 = openpyxl.load_workbook(table) + try: + written = _base_info_check(wb2, dry_run=False) + if written.get('written'): + wb2.save(table) + result['base_info'] = written + finally: + wb2.close() + + # 保存后真正刷新透视缓存 + 公式,再从缓存读四口径 + do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com) + refresh = com_refresh.refresh(table, sheets=[config.DY_PIVOT_SHEET, + config.REPORT_SHEET, + config.DY_CONVERT_SHEET]) if do_com else \ + {'ok': False, 'engine': '', 'message': '未启用 COM 刷新'} + result['com_refresh'] = refresh + if refresh.get('ok'): + try: + wb3 = openpyxl.load_workbook(table, data_only=True) + try: + detail_total, _ = _sum_filtered( + wb3['核销明细'], config.DY_DETAIL_TIME_COL, + config.DY_DETAIL_STATUS_COL, config.DY_DETAIL_INCOME_COL, target) + pivot_total = _sum_column(wb3[config.DY_PIVOT_SHEET], + config.DY_PIVOT_INCOME_COL) + report_total = _sum_column(wb3[config.REPORT_SHEET], + config.DY_REPORT_INCOME_COL) + convert_total, _ = _sum_filtered( + wb3[config.DY_CONVERT_SHEET], config.DY_CONVERT_TIME_COL, + config.DY_DETAIL_STATUS_COL, config.DY_CONVERT_INCOME_COL, target) + finally: + wb3.close() + except Exception as e: + config.log(f'COM 刷新后读四口径失败,沿用旧值:{e}', 'WARN') + elif do_com: + config.log(f'抖音透视未刷新({refresh.get("message")}),四口径为旧缓存/复算值', 'WARN') + + totals = (detail_total, pivot_total, report_total, convert_total) + consistent = max(totals) - min(totals) < 0.01 + result.update(ok=True, path=table, detail_total=detail_total, + pivot_total=pivot_total, report_total=report_total, + convert_total=convert_total, consistent=consistent, + message=f'核销明细已贴 {len(rows)} 行;四口径 ' + f'{detail_total:.2f}/{pivot_total:.2f}/' + f'{report_total:.2f}/{convert_total:.2f}' + + ('' if consistent else '(不一致!)')) + if not consistent: + config.log('抖音四口径合计不一致,请检查透视缓存 / 报表公式 / 转换表', 'WARN') + return result + finally: + try: + wb.close() + except Exception: + pass diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/paste_to_master.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/paste_to_master.py new file mode 100644 index 0000000..add18f5 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/paste_to_master.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +"""把美团 / 抖音【报表】与 CRM 团购支付数据按位置贴到本地马敏团购总表副本。 + +列映射(字段一一对应,按位置贴,不按表头名):: + + 美团【报表】I~P →【平台-新美大】A~H(数据第 5 行起) + 抖音【报表】N~Z →【平台-抖音】A~M(数据第 5 行起) + CRM【团购统计】A~I →【团购统计】A~I(同结构,数据第 2 行起) + +**共享盘全程只读**,只写本地 ``_work/`` 副本;zip+XML 直接改值,不用 openpyxl save。 +""" +import os +import re +import shutil +import zipfile +from datetime import date, datetime +from xml.sax.saxutils import escape + +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 share_copy + +_CELL_RE = re.compile(r']*?)(?:/>|>(.*?))', re.S) +_ROW_RE = re.compile(r']*?)(?:/>|>(.*?))', re.S) + + +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 _col_num(letters): + n = 0 + for ch in letters: + n = n * 26 + (ord(ch) - 64) + return n + + +def _sheet_xml_path(zf, sheet_name): + import xml.etree.ElementTree as ET + main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}' + rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}' + pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}' + root = ET.fromstring(zf.read('xl/workbook.xml')) + rid = None + for s in root.iter(f'{main}sheet'): + if s.get('name') == sheet_name: + rid = s.get(f'{rel}id') + break + if not rid: + return None + rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels')) + for r in rels.iter(f'{pkg}Relationship'): + if r.get('Id') == rid: + t = (r.get('Target') or '').lstrip('/') + return t if t.startswith('xl/') else 'xl/' + t + return None + + +def _master_path(day): + return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, + f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx') + + +def _local_path(day, keyword): + return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, + share_copy.table_name(keyword, day, config.SHARE_TABLE_EXT)) + + +def _group_pay_source(day, crm_dir=''): + root = str(crm_dir or config.CRM_EXPORT_DIR).strip().strip('"') + return os.path.join(root, f'{config.CRM_GROUP_PAY_PREFIX}-{day:%Y%m%d}.xlsx') + + +def _read_values(path, sheet, c0, c1, start_row): + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + try: + if sheet not in wb.sheetnames: + return [] + ws = wb[sheet] + rows = [list(row) for row in ws.iter_rows(min_row=start_row, + min_col=col(c0), max_col=col(c1), + values_only=True)] + while rows and all(v is None for v in rows[-1]): + rows.pop() + return rows + finally: + wb.close() + + +def _make_cell(row_no, cnum, value, style=''): + letters = letter(cnum) + s_attr = f' s="{style}"' if style else '' + if isinstance(value, bool): + return f'{int(value)}' + if isinstance(value, (int, float)): + return f'{value}' + return (f'' + f'{escape(str(value))}') + + +def _set_row_values(row_xml, row_no, values, lo, hi): + keep, styles = [], {} + 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 lo <= cnum <= hi: + continue + keep.append((cnum, m.group(0))) + for cnum in range(lo, hi + 1): + value = values.get(cnum) + if value is not None: + keep.append((cnum, _make_cell(row_no, cnum, value, styles.get(cnum, '')))) + keep.sort(key=lambda x: x[0]) + attrs = re.match(r']*?)/?>', row_xml) + attr_text = attrs.group(1).rstrip() if attrs else '' + if not attr_text: + attr_text = ' r="%d"' % row_no + head = '' + return head + ''.join(cell for _, cell in keep) + '' + + +def _patch_sheet_xml(xml_text, rows, start_row, start_col): + existing = {} + for m in _ROW_RE.finditer(xml_text): + head = '' + row_no = re.search(r'\br="(\d+)"', head) + if row_no: + existing[int(row_no.group(1))] = m.group(0) + width = len(rows[0]) if rows else 0 + lo, hi = start_col, start_col + max(width - 1, 0) + last_existing = max(existing) if existing else start_row - 1 + needed = start_row + len(rows) - 1 + + out = xml_text + for row_no in range(start_row, max(needed, last_existing) + 1): + values = {} + if row_no - start_row < len(rows): + for offset, value in enumerate(rows[row_no - start_row]): + if value is not None: + values[lo + offset] = value + old = existing.get(row_no) + new = _set_row_values(old, row_no, values, lo, hi) if old else \ + f'' + ''.join( + _make_cell(row_no, cnum, value) for cnum, value in sorted(values.items())) + '' + if old: + out = out.replace(old, new, 1) + added = ''.join( + f'' + ''.join( + _make_cell(row_no, lo + offset, value) + for offset, value in enumerate(rows[row_no - start_row]) if value is not None) + + '' + for row_no in range(last_existing + 1, max(needed, last_existing) + 1)) + if added: + out = out.replace('', added + '', 1) + return out + + +def _write_master(path, jobs): + from .zipio import open_zip + zf = open_zip(path) + tmp = path + '.paste.tmp' + try: + patches = {} + for sheet_name, rows, start_col, start_row in jobs: + xml_path = _sheet_xml_path(zf, sheet_name) + if not xml_path: + config.log(f'本地总表缺少 sheet「{sheet_name}」,跳过', 'WARN') + continue + text = zf.read(xml_path).decode('utf-8', 'replace') + patches[xml_path] = _patch_sheet_xml(text, rows, start_row, start_col) + if not patches: + return + 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 + if info.filename in patches: + dst.writestr(zi, patches.pop(info.filename).encode('utf-8')) + else: + with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout: + shutil.copyfileobj(fin, fout, 4 << 20) + for name, data in patches.items(): + dst.writestr(name, data.encode('utf-8')) + finally: + zf.close() + os.replace(tmp, path) + + +def run(day=None, douyin_dir='', crm_dir='', dry_run=False, jobs_filter=None): + """按值贴进本地马敏团购总表副本。jobs_filter 可限定只贴某些 sheet。""" + target = _parse_day(day) or date.today() + result = {'ok': False, 'message': '', 'day': target.isoformat(), 'path': '', + 'meituan_rows': 0, 'douyin_rows': 0, 'group_rows': 0} + master = _master_path(target) + if not os.path.isfile(master): + result['message'] = f'未找到马敏团购总表的本地副本:{master}(请先从共享盘复制)' + return result + + wanted = set(jobs_filter or []) if jobs_filter else None + jobs = [] + if not wanted or 'meituan' in wanted: + src = _local_path(target, config.SHARE_TABLE_KEYWORD) + if os.path.isfile(src): + values = _read_values(src, config.REPORT_SHEET, *config.MEITUAN_REPORT_COLS, + config.REPORT_DATA_START) + if values: + jobs.append((config.MASTER_SHEET_MEITUAN, values, 1, config.MASTER_DATA_START)) + result['meituan_rows'] = len(values) + else: + config.log('美团【报表】无数据,跳过', 'WARN') + else: + config.log(f'未找到本地美团表:{src}', 'WARN') + + if not wanted or 'douyin' in wanted: + dy = _local_path(target, config.DOUYIN_SHARE_KEYWORD) + if not os.path.isfile(dy): + dy = os.path.join(str(douyin_dir or config.DOUYIN_WORK_DIR).strip('"'), + f'{config.DOUYIN_TABLE_PREFIX}{target.month}.{target.day}.xlsx') + if os.path.isfile(dy): + values = _read_values(dy, config.REPORT_SHEET, *config.DOUYIN_REPORT_COLS, + config.REPORT_DATA_START) + if values: + jobs.append((config.MASTER_SHEET_DOUYIN, values, 1, config.MASTER_DATA_START)) + result['douyin_rows'] = len(values) + else: + config.log('抖音【报表】无数据,跳过', 'WARN') + else: + config.log(f'未找到本地抖音表:{dy}', 'WARN') + + if not wanted or 'group' in wanted: + gp = _group_pay_source(target, crm_dir) + if os.path.isfile(gp): + values = _read_values(gp, config.MASTER_SHEET_GROUP_STATS, 'A', 'I', + config.GROUP_STATS_DATA_START) + if values: + jobs.append((config.MASTER_SHEET_GROUP_STATS, values, 1, + config.GROUP_STATS_DATA_START)) + result['group_rows'] = len(values) + else: + config.log('CRM【团购统计】无数据,跳过', 'WARN') + else: + config.log(f'未找到 CRM 团购支付数据:{gp}', 'WARN') + + if not jobs: + result['message'] = '没有可用源数据,未写入马敏团购总表本地副本' + return result + if dry_run: + result.update(ok=True, + message=f'[演练] 将贴入 平台-新美大 {result["meituan_rows"]} 行 / ' + f'平台-抖音 {result["douyin_rows"]} 行 / ' + f'团购统计 {result["group_rows"]} 行') + return result + try: + _write_master(master, jobs) + except OSError as e: + result['message'] = f'写入本地总表失败:{e}' + return result + result.update(ok=True, path=master, + message=f'已按值贴入 平台-新美大 {result["meituan_rows"]} 行 / ' + f'平台-抖音 {result["douyin_rows"]} 行 / ' + f'团购统计 {result["group_rows"]} 行') + config.log(result['message']) + return result diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/share_copy.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/share_copy.py new file mode 100644 index 0000000..791e8e9 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/share_copy.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。 + +源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换:: + + 源(共享盘,只读) + 1111/TG/2026年11月/11.10/美团11.10.xlsx / 抖音11.10.xlsx + 1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx + 目标(本地副本) + D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx + D:\\资料\\财务\\新美大平台核对\\_work\\抖音11.11.xlsx + D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx + +两张核对表复制到本地后,后续所有处理都只改本地副本。 +""" +import os +import re +import shutil +from datetime import date, datetime, timedelta + +from .. import config + + +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 day_dir(root, day): + return os.path.join(root, f'{day.year}年{day.month}月', f'{day.month}.{day.day}') + + +def table_name(keyword, day, suffix='.xlsx'): + return f'{keyword}{day.month}.{day.day}{suffix}' + + +def _list_tables(folder, keyword, suffix): + try: + return sorted(f for f in os.listdir(folder) + if keyword in f and f.lower().endswith(suffix)) + except OSError: + return [] + + +def _pick_source(folder, keyword, day, suffix): + exact = os.path.join(folder, table_name(keyword, day, suffix)) + if os.path.isfile(exact): + return exact + found = _list_tables(folder, keyword, suffix) + if len(found) == 1: + return os.path.join(folder, found[0]) + return '' + + +def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False): + """从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。""" + 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'本地副本已存在,跳过复制:{os.path.basename(dst_path)}') + return result + + if dry_run: + result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → {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, keywords=None, local_dir='', dry_run=False): + """把昨天的核对表批量拉到本地副本(共享盘只读)。 + + Args: + keywords: 要复制的关键词列表,默认 ``[美团, 抖音, 马敏团购总表]`` + """ + jobs = list(keywords or [config.SHARE_TABLE_KEYWORD, config.DOUYIN_SHARE_KEYWORD, + config.LINK_BOOK]) + tables = [] + for kw in jobs: + item = copy_prev_table(share_root=share_root, keyword=kw, ext=config.SHARE_TABLE_EXT, + day=day, local_dir=local_dir, dry_run=dry_run) + item['label'] = kw + 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), + } diff --git a/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/zipio.py b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/zipio.py new file mode 100644 index 0000000..43e3964 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/zipio.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +"""xlsx(zip) 读写的兼容层:修复 WPS 写坏的 ZIP64 条目大小。""" +import struct +import zipfile + + +def _local_sizes(fp, info): + fp.seek(info.header_offset) + hdr = fp.read(30) + if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04': + return None, None + nlen, elen = struct.unpack('= 16: + usize, csize = struct.unpack('= 8: + usize = struct.unpack('=3.1 +pywin32>=306