feat(xq0085): 团购核对支持对比表与门店归属(v1.1.0)

This commit is contained in:
2026-11-27 17:18:36 +08:00
parent 764188caa5
commit 26842c3ed3
34 changed files with 7091 additions and 424 deletions
@@ -1,58 +1,44 @@
# -*- coding: utf-8 -*-
"""美团核对:团购收益明细 + 预订收益明细 → 订单收入明细表,并算三口径当天合计。
"""美团核对:团购收益明细 → 订单收入明细表(2026-11 新版 31 列模板)。
* 删除团购明细的「订单类型/订单号」;预订明细归一化字段后合并(订单信息→套餐名)
* 每次清空 ``订单收入明细表`` 第 4 行到真实末行的 A~AI,再整体重贴(幂等)
* 公式列 AC/AD/AF/AG/AH/AI 按行下拉;AD=营业日(验券 hour<10 算前一天)
* 明细 P 合计 / 透视 G 复算 / 报表 P 合计三者交叉校验
* 按导出表头取值,映射到目标表 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
from collections import defaultdict
from datetime import datetime, timedelta
import zipfile
from datetime import date, datetime, timedelta
import openpyxl
from .. import config
from . import com_refresh, share_copy
from . import com_refresh, share_copy, sheet_xml
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)}
_REF_RE = re.compile(r'(\$?)([A-Z]{1,3})(\$?)(\d+)')
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)
# 预订明细按表头名映射到目标列(目标没有的列忽略)
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 hasattr(value, 'year') and hasattr(value, 'month') and hasattr(value, 'day'):
if isinstance(value, date):
return value
text = str(value or '').strip()
m = re.match(r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})', text)
@@ -64,201 +50,275 @@ def _as_date(value):
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:
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
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
return day - timedelta(days=1) if hour < 10 else day
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 _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 _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 _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 _read_rows(path, header_row):
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]]
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)]
_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 _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 _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 = 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)
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, 'groups': 0}
'detail_rows': 0, 'skipped_day': 0, 'replaced': 0}
src = str(table_path or '').strip()
if not src:
pairs = glob.glob(os.path.join(work, share_copy.table_name(
cands = 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 ''
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, data_only=False)
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
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
finally:
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')
# 先确认导出明细齐全,再动表(缺文件时一张表都不清)
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
finally:
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:
wb.close()
except Exception:
pass
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