feat(xq0085): 新增团购数据核对插件(v1.0.0)
美团/抖音两条独立分支共享盘只读取数并本地副本处理:团购明细贴总表、明细/透视/报表多口径合计校验、报表基础信息补维护、按值贴入平台总表。
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user