Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/logic/daily_detail.py
T
puddy e4be289835 feat(xq0041): 美团/抖音核对迁出至 XQ0085,保留导表与到账统计核对(v1.3.13)
download=只导打款/团购/预订收益明细;check_settlement=到账统计核对(并台账/门店归属/更新核对统计);金色印象与金色湖畔独立浏览器档案;新增 CRM 门店映射、基础信息同步与贴总表逻辑。
2026-11-26 09:28:32 +08:00

306 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""订单收入明细:团购 + 预订合并后贴进「订单收入明细表」,算当天结算价合计。
流程(对应财务人工操作)::
1. 团购收益明细:删掉 E 订单类型、F 订单号 两列;
2. 预订收益明细:转成与团购相同的 31 列(订单信息→套餐名,团购独有列留空);
3. 两张表合并(团购在前、预订在后);
4. 从第 4 行开始贴进「订单收入明细表」的 A~AB(第 28 项账单周期直接贴 AB,
明细里的「关联买单订单号/券号」目标表没有该列,丢弃);
5. AC/AD/AF/AG/AH/AI 六列按行下拉公式(与共享表模板一致);
6. 筛 AD(营业日)= 目标日、C(业务类型)≠「其他」→ 汇总 P 列结算价。
营业日口径(照抄共享表公式,别改)::
AD = IF(HOUR(验券时间)<10, IF(DAY=1, 上月最后一天, DAY-1), DAY)
即:凌晨 10 点前核销算前一天;1 号凌晨算上月最后一天。
**共享盘只读**:表拉到本地 `_work/` 副本上处理,结果不回写共享盘。
"""
import os
import shutil
from datetime import date, datetime, timedelta
import openpyxl
from .. import config
# 团购收益明细的 31 列表头(第 2 行);预订表按名字映射到这套
GROUP_COLS = [
'账户名称', '线上场景/线下场景', '收益类型', '业务类型', '订单类型', '订单号',
'券号', '下单时间', '验券/退款/调整时间', '团购ID/通兑券ID', '套餐名',
'消费门店Id', '消费门店', '特殊账期业务', '入账日期', '打款状态', '打款单号',
'结算价', '总收入(元)', '技术服务费费率', '平台技术服务费(元)',
'商家营销费用(元)', '其他调整(元)', '自配打包费(元)', '自配送费(元)',
'渠道佣金(元)', '渠道标签', '备注', '关联纠纷单号', '关联买单订单号/券号',
'账单周期',
]
# 贴到目标表的顺序(A~AB 共 28 列):去掉订单类型/订单号,且不含「关联买单订单号/券号」
TARGET_COLS = [c for c in GROUP_COLS if c not in ('订单类型', '订单号', '关联买单订单号/券号')]
#: 列名 → 在「团购 31 列」里的下标(取值用这个,写入位置用 TARGET_COLS)
G_IDX = {name: i for i, name in enumerate(GROUP_COLS)}
# 公式列(1 起列号):AC/AD/AE/AF/AG/AH/AI
COL_AC, COL_AD, COL_AE, COL_AF, COL_AG, COL_AH, COL_AI = 29, 30, 31, 32, 33, 34, 35
COL_P = TARGET_COLS.index('结算价') + 1
COL_C = TARGET_COLS.index('业务类型') + 1
COL_G = TARGET_COLS.index('验券/退款/调整时间') + 1
def _key(name):
"""表头归一键:去括号内说明、去空格换行('结算价(总收入-...)' → '结算价')。"""
text = str(name or '').strip()
for mark in ('(', '('):
if mark in text:
text = text.split(mark, 1)[0]
return text.replace(' ', '').replace('\u3000', '').replace('\n', '')
def _read_table(path, header_row):
"""读一张美团导出的明细:返回 ``(表头, 行列表)``(行是 list)。"""
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
try:
ws = wb[wb.sheetnames[0]]
header = list(next(ws.iter_rows(min_row=header_row, max_row=header_row,
max_col=ws.max_column, values_only=True)))
rows = []
for row in ws.iter_rows(min_row=header_row + 1, max_col=len(header),
values_only=True):
if any(v not in (None, '') for v in row):
rows.append(list(row))
return header, rows
finally:
wb.close()
def _to_group_rows(header, rows, *, booking=False):
"""把明细行转成团购 31 列顺序;预订表缺的列补 None。"""
index = {}
for i, name in enumerate(header):
index.setdefault(_key(name), i)
# 预订的「订单信息」等同于团购的「套餐名」
if booking and '套餐名' not in index and '订单信息' in index:
index['套餐名'] = index['订单信息']
out = []
for row in rows:
out.append([row[index[_key(col)]] if _key(col) in index and index[_key(col)] < len(row)
else None
for col in GROUP_COLS])
return out
def _pick(pattern):
"""目录里最新的匹配文件。"""
import glob
paths = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
if '_备份' not in p and not os.path.basename(p).startswith('~$')]
if not paths:
return ''
paths.sort(key=os.path.getmtime, reverse=True)
return paths[0]
def business_day(value, prev_month_last_day):
"""营业日:凌晨 10 点前算前一天;1 号凌晨算上月最后一天。返回 ``date``。"""
if isinstance(value, datetime):
dt = value
elif isinstance(value, date):
dt = datetime(value.year, value.month, value.day)
else:
dt = None
text = str(value or '').strip()[:19]
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
try:
dt = datetime.strptime(text, fmt)
break
except ValueError:
continue
if dt is None:
return None
if dt.hour < 10:
if dt.day == 1:
return prev_month_last_day
return dt.date() - timedelta(days=1)
return dt.date()
def _prev_month_last_day(day):
first = day.replace(day=1)
return first - timedelta(days=1)
def _last_data_row(ws, start_row, col=5):
"""真实数据末行(E 券号有值的最后一行);无数据返回 ``start_row - 1``。"""
last = start_row - 1
for r in range(start_row, int(ws.max_row) + 1):
if ws.cell(r, col).value not in (None, ''):
last = r
return last
def _write_formulas(ws, row):
"""按行下拉公式(与共享表模板逐字符一致,不能简化)。"""
ws.cell(row, COL_AC).value = f'=IF(P{row}>0,1,-1)'
ws.cell(row, COL_AD).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, COL_AF).value = f'=_xlfn.XLOOKUP(I{row},基础信息!E:E,基础信息!F:F)'
ws.cell(row, COL_AG).value = f'=F{row}*1'
ws.cell(row, COL_AH).value = (
f'=IF(AND(AG{row}>$AG$1,OR(AF{row}="龙手足道",AF{row}="印象贵足")),0.6%,3%)')
ws.cell(row, COL_AI).value = f'=IF(AH{row}=U{row + 1},"正常","异常")'
def run(table_path='', day=None, dry_run=False):
"""合并团购 + 预订明细,贴进订单收入明细表并算当天结算价合计。
Args:
table_path: 共享表的本地副本;空则把共享盘今天的表拉到 ``_work/`` 再处理
day: 目标营业日(默认今天)
dry_run: 只统计不写表
Returns:
``{"ok", "message", "rows", "total", "day", "path", "unmatched"}``
"""
target = day if isinstance(day, date) else (date.today() if day is None else
datetime.strptime(str(day)[:10], '%Y-%m-%d').date())
result = {'ok': False, 'message': '', 'rows': 0, 'matched': 0, 'total': 0.0,
'pivot_total': 0.0, 'pivot_groups': 0, 'pivot_diff': 0.0,
'day': target.isoformat(), 'path': ''}
# 1) 明细:团购 + 预订
group_path = _pick('团购收益明细_*.xlsx')
if not group_path:
result['message'] = '未找到团购收益明细(团购收益明细_*.xlsx),请先导出'
return result
group_header, group_rows = _read_table(group_path, config.PROFIT_HEADER_ROW)
merged = _to_group_rows(group_header, group_rows)
booking_path = _pick('预订收益明细_*.xlsx')
if booking_path:
b_header, b_rows = _read_table(booking_path, config.PROFIT_HEADER_ROW)
merged += _to_group_rows(b_header, b_rows, booking=True)
config.log(f'合并明细:团购 {len(group_rows)} 行 + 预订 {len(b_rows)} 行')
else:
config.log(f'合并明细:团购 {len(group_rows)} 行(未找到预订收益明细)')
if not merged:
result['message'] = '收益明细没有数据行'
return result
# 2) 共享表副本(只读共享盘;不回写)
if not table_path:
table_path = _local_copy(target)
if not table_path:
result['message'] = '未取到共享盘的订单收入明细表(共享盘不可达或今天的新表未创建)'
return result
result['path'] = table_path
# 3) 写表 + 公式下拉
wb = openpyxl.load_workbook(table_path)
try:
if config.DAILY_SHEET not in wb.sheetnames:
result['message'] = f'{os.path.basename(table_path)} 缺少 sheet「{config.DAILY_SHEET}」'
return result
ws = wb[config.DAILY_SHEET]
# 每天的流程是「清空 → 重新粘贴」:先把第 4 行到真实末行整段清掉(值+公式),
# 不留昨天的数据,保证重复运行结果一致(幂等)。
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
config.log(f'已清空目标表原有数据:第 {config.DAILY_DATA_START}~{last} 行'
f'({last - config.DAILY_DATA_START + 1} 行)')
start = config.DAILY_DATA_START
i_time = G_IDX['验券/退款/调整时间']
i_biz = G_IDX['业务类型']
i_net = G_IDX['结算价']
i_shop = G_IDX['消费门店']
i_item = G_IDX['套餐名']
i_gross = G_IDX['总收入(元)']
i_fee = G_IDX['平台技术服务费(元)']
i_mkt = G_IDX['商家营销费用(元)']
prev_last = _prev_month_last_day(target)
matched = total = 0
groups = {}
for offset, row in enumerate(merged):
r = start + offset
for col, name in enumerate(TARGET_COLS, 1):
ws.cell(r, col).value = row[G_IDX[name]]
_write_formulas(ws, r)
bday = business_day(row[i_time], prev_last)
biz = str(row[i_biz] or '').strip()
if bday == target and biz not in config.DAILY_EXCLUDE_BUSINESS:
matched += 1
total += _num(row[i_net])
# 透视口径:按「消费门店 × 套餐名」分组(与【透视】表行列一致)
key = (str(row[i_shop] or '').strip(), str(row[i_item] or '').strip())
g = groups.setdefault(key, [0, 0.0, 0.0, 0.0, 0.0])
g[0] += 1
g[1] += _num(row[i_gross])
g[2] += _num(row[i_fee])
g[3] += _num(row[i_mkt])
g[4] += _num(row[i_net])
if not dry_run:
wb.save(table_path)
finally:
wb.close()
# 第 4/5 步:三处合计本是同一条链——明细 P → 透视 G(=IF(P>0,1,-1) 那批行的汇总)
# → 报表 P(=+G+0,另外 VLOOKUP 基础信息 补品牌/内部门店)。这里全部复算出来并交叉校验。
pivot_total = round(sum(g[4] for g in groups.values()), 2)
detail_total = round(total, 2)
report_total = pivot_total # 报表 P 列公式为 +G+0,与透视 G 等价
diff = round(pivot_total - detail_total, 2)
consistent = abs(diff) < 0.01
result.update(ok=True, rows=len(merged), total=detail_total, matched=matched,
pivot_total=pivot_total, pivot_groups=len(groups), pivot_diff=diff,
report_total=report_total, consistent=consistent,
message=(f'{target.month}.{target.day} 营业日:明细 {len(merged)} 行,'
f'命中 {matched} 行(C 列剔除「其他」);'
f'明细 P / 透视 G / 报表 P 三处合计 '
f'{detail_total:,.2f} / {pivot_total:,.2f} / {report_total:,.2f} 元'
f'({len(groups)} 个门店×套餐组合)'
+ (',三口径一致' if consistent else f',差异 {diff:,.2f} 需排查')))
if not consistent:
config.log(result['message'], 'WARN')
else:
config.log(result['message'])
return result
def _num(value):
"""金额转 float('-'/空 → 0)。"""
if value is None or value == '':
return 0.0
try:
return float(str(value).replace(',', '').strip())
except (TypeError, ValueError):
return 0.0
def _local_copy(day):
"""取当天的本地副本——由 share_copy 从共享盘昨天目录复制而来(共享盘只读)。"""
from ..data import share_copy
work = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR)
name = share_copy.table_name(config.SHARE_TABLE_KEYWORD, day, config.SHARE_TABLE_EXT)
dst = os.path.join(work, name)
if os.path.isfile(dst) and os.path.getsize(dst) > 0:
config.log(f'使用本地副本:{dst}')
return dst
# 兼容:本地还没有时,从共享盘当天目录只读拉一份
src = os.path.join(share_copy.day_dir(config.SHARE_CHECK_ROOT, day), name)
if not os.path.isfile(src):
return ''
os.makedirs(work, exist_ok=True)
shutil.copy2(src, dst)
config.log(f'已从共享盘只读拉到本地副本:{dst}')
return dst