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