feat(xq0041): 迁出美团/抖音核对,导表支持断点续传(v1.3.17)
This commit is contained in:
@@ -1,207 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础信息补维护:报表里出现新的消费门店 / 新的套餐(项目)时,补进【基础信息】。
|
||||
|
||||
背景(共享表里的公式链)::
|
||||
|
||||
报表 J = IF(B=0,"",VLOOKUP(A,基础信息!$A$3:$B$1973,2,0)) # 美团门店名 → 内部门店
|
||||
报表 K = IF(B=0,"",VLOOKUP(B,基础信息!$E$2:$F$12924,2,0)) # 套餐名 → 品项名称
|
||||
|
||||
VLOOKUP 查不到就显示 #N/A(人工看到的是"乱码")。所以每天要检查报表里有没有
|
||||
新的门店名 / 新的套餐名,补进【基础信息】的 A~C(门店映射)与 E~F(品项映射)。
|
||||
|
||||
自动补的来源:
|
||||
|
||||
* **内部门店 / 品牌**:优先用 ``门店映射表.json``(CRM 券号 join 出来的,最准);
|
||||
没有则按名称相似度给候选,标「待确认」;
|
||||
* **品项名称**:套餐名里的 ``【...】`` 就是品项(如「【龙手足道】80分钟…」→ 龙手足道);
|
||||
提取不到再给空值待人工。
|
||||
|
||||
写入只在**本地副本**上做(共享盘只读),人工确认后自行同步回共享盘。
|
||||
"""
|
||||
import difflib
|
||||
import json
|
||||
import os
|
||||
|
||||
import openpyxl
|
||||
|
||||
from .. import config
|
||||
|
||||
COL_BI_A, COL_BI_B, COL_BI_C = 1, 2, 3 # 基础信息:消费门店名称 / 门店 / 品牌
|
||||
COL_BI_E, COL_BI_F = 5, 6 # 基础信息:套餐名 / 品项名称
|
||||
ITEM_MARK = ('【', '】')
|
||||
|
||||
|
||||
def _norm(name):
|
||||
return str(name or '').strip()
|
||||
|
||||
|
||||
def _is_blank(value):
|
||||
"""报表里透视多出来的 0 行:A/B 为 '0' 或空,不算真实门店/套餐。"""
|
||||
text = str(value if value is not None else '').strip()
|
||||
return text in ('', '0', 'None')
|
||||
|
||||
|
||||
def _read_report_pairs(ws):
|
||||
"""读【报表】A(消费门店名)/ B(套餐名),返回去重后的 (门店名集合, 套餐名集合)。"""
|
||||
shops, items = [], []
|
||||
seen_shop, seen_item = set(), set()
|
||||
last = 0
|
||||
for r in range(config.REPORT_DATA_START, int(ws.max_row) + 1):
|
||||
shop = ws.cell(r, 1).value
|
||||
item = ws.cell(r, 2).value
|
||||
if not _is_blank(shop) or not _is_blank(item):
|
||||
last = r
|
||||
for r in range(config.REPORT_DATA_START, last + 1):
|
||||
shop = _norm(ws.cell(r, 1).value)
|
||||
item = _norm(ws.cell(r, 2).value)
|
||||
if not _is_blank(shop) and shop not in seen_shop:
|
||||
seen_shop.add(shop)
|
||||
shops.append(shop)
|
||||
if not _is_blank(item) and item not in seen_item:
|
||||
seen_item.add(item)
|
||||
items.append(item)
|
||||
return shops, items
|
||||
|
||||
|
||||
def _column_values(ws, col, start_row):
|
||||
"""取某列从 start_row 起的非空值(去首尾空白)与真实末行。"""
|
||||
values = set()
|
||||
last = start_row - 1
|
||||
for r in range(start_row, int(ws.max_row) + 1):
|
||||
value = ws.cell(r, col).value
|
||||
if value not in (None, ''):
|
||||
last = r
|
||||
values.add(_norm(value))
|
||||
return values, last
|
||||
|
||||
|
||||
def _load_shop_map():
|
||||
"""读门店映射表(CRM 券号 join 的产物):美团门店名 → {shop, brand, shop_id}。"""
|
||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fp:
|
||||
data = json.load(fp)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
shops = data.get('shops') if isinstance(data, dict) else None
|
||||
return shops if isinstance(shops, dict) else {}
|
||||
|
||||
|
||||
def _guess_shop(shop_name, known, mapping):
|
||||
"""新门店 → 内部门店:先查 CRM 映射表,再按名称相似度给候选。"""
|
||||
hit = mapping.get(shop_name)
|
||||
if hit and hit.get('shop'):
|
||||
return hit['shop'], hit.get('brand', ''), 'CRM券号映射'
|
||||
best = difflib.get_close_matches(shop_name, list(known), n=1, cutoff=0.5)
|
||||
if best:
|
||||
return best[0], '', '名称相近(待确认)'
|
||||
return '', '', '待确认'
|
||||
|
||||
|
||||
def _guess_item(item_name):
|
||||
"""套餐名 → 品项名称:取 ``【...】`` 里的词(共享表的人工口径就是这个)。"""
|
||||
text = str(item_name or '')
|
||||
start = text.find(ITEM_MARK[0])
|
||||
end = text.find(ITEM_MARK[1], start + 1)
|
||||
if start >= 0 and end > start:
|
||||
return text[start + 1:end].strip(), '套餐名【】提取'
|
||||
return '', '待人工'
|
||||
|
||||
|
||||
def run(table_path='', dry_run=False):
|
||||
"""检查【报表】里有、而【基础信息】里没有的门店/套餐,并补进本地副本。
|
||||
|
||||
Args:
|
||||
table_path: 共享表的本地副本路径(必填,共享盘只读)
|
||||
dry_run: 只检测不写
|
||||
|
||||
Returns:
|
||||
``{"ok", "message", "new_shops": [...], "new_items": [...], "path"}``
|
||||
"""
|
||||
result = {'ok': False, 'message': '', 'new_shops': [], 'new_items': [],
|
||||
'path': table_path or ''}
|
||||
if not table_path or not os.path.exists(table_path):
|
||||
result['message'] = '没有可用的本地副本(共享盘只读,需先拉一份到本地)'
|
||||
return result
|
||||
|
||||
wb = openpyxl.load_workbook(table_path)
|
||||
try:
|
||||
if config.BASE_SHEET not in wb.sheetnames:
|
||||
result['message'] = f'{os.path.basename(table_path)} 缺少「{config.BASE_SHEET}」sheet'
|
||||
return result
|
||||
|
||||
report = wb[config.REPORT_SHEET] if config.REPORT_SHEET in wb.sheetnames else None
|
||||
if report is None:
|
||||
result['message'] = f'缺少「{config.REPORT_SHEET}」sheet,跳过基础信息校验'
|
||||
return result
|
||||
|
||||
shops, items = _read_report_pairs(report)
|
||||
base = wb[config.BASE_SHEET]
|
||||
known_shops, last_a = _column_values(base, COL_BI_A, config.BASE_INFO_ROW)
|
||||
known_items, last_e = _column_values(base, COL_BI_E, config.BASE_ITEM_ROW)
|
||||
|
||||
# 只检查不修改:VLOOKUP 范围是写死的行号,末尾逼近上界时提醒人工扩范围
|
||||
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')
|
||||
|
||||
new_shops = [s for s in shops if s not in known_shops]
|
||||
new_items = [i for i in items if i not in known_items]
|
||||
result['new_shops'] = new_shops
|
||||
result['new_items'] = new_items
|
||||
|
||||
if not new_shops and not new_items:
|
||||
result.update(ok=True, message=f'基础信息已覆盖报表里的 {len(shops)} 家门店 / '
|
||||
f'{len(items)} 个套餐,无需补维护')
|
||||
return result
|
||||
|
||||
mapping = _load_shop_map()
|
||||
shop_rows = []
|
||||
for name in new_shops:
|
||||
shop, brand, source = _guess_shop(name, known_shops, mapping)
|
||||
shop_rows.append({'name': name, 'shop': shop, 'brand': brand, 'source': source})
|
||||
item_rows = []
|
||||
for name in new_items:
|
||||
item, source = _guess_item(name)
|
||||
item_rows.append({'name': name, 'item': item, 'source': source})
|
||||
|
||||
if not dry_run:
|
||||
row = last_a + 1
|
||||
for info in shop_rows:
|
||||
base.cell(row, COL_BI_A).value = info['name']
|
||||
base.cell(row, COL_BI_B).value = info['shop']
|
||||
base.cell(row, COL_BI_C).value = info['brand']
|
||||
row += 1
|
||||
row = last_e + 1
|
||||
for info in item_rows:
|
||||
base.cell(row, COL_BI_E).value = info['name']
|
||||
base.cell(row, COL_BI_F).value = info['item']
|
||||
row += 1
|
||||
wb.save(table_path)
|
||||
|
||||
auto_shop = sum(1 for x in shop_rows if x['source'] == 'CRM券号映射')
|
||||
auto_item = sum(1 for x in item_rows if x['source'] == '套餐名【】提取')
|
||||
result.update(ok=True, shop_rows=shop_rows, item_rows=item_rows,
|
||||
message=(f'{"[演练] " if dry_run else ""}基础信息待补:'
|
||||
f'新增门店 {len(shop_rows)} 个(自动补 {auto_shop},其余待确认)、'
|
||||
f'新增套餐 {len(item_rows)} 个(自动提取品项 {auto_item});'
|
||||
+ ('已写入本地副本,确认后同步回共享盘' if not dry_run
|
||||
else '未写入')))
|
||||
config.log(result['message'])
|
||||
return result
|
||||
finally:
|
||||
wb.close()
|
||||
@@ -1,305 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,319 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把美团 / 抖音【报表】与 CRM 团购支付数据按位置贴到马敏团购总表(粘贴为数值)。
|
||||
|
||||
列映射(源列与目标列字段一一对应,按位置贴,不按表头名)::
|
||||
|
||||
美团【报表】I~P(品牌/门店/商品名称/数量/总收入/技术服务费/营销费用/结算价)
|
||||
→ 【平台-新美大】A~H(数据从第 5 行起)
|
||||
抖音【报表】N~Z(品牌/门店/商品名称/数量/商家货款补贴/…/团长服务费)
|
||||
→ 【平台-抖音】A~M(数据从第 5 行起)
|
||||
CRM【团购统计】A~I(团购类型/消费日期/门店/核销项目名称/…/已消费项目个数)
|
||||
→ 【团购统计】A~I(同结构,数据从第 2 行起)
|
||||
|
||||
每个目标 sheet 每次先清空数据区(只清源列覆盖的列),再按位置写入,
|
||||
避免昨天残留;其它列(加上日/减本日/调整后等)原样保留。
|
||||
|
||||
目标马敏团购总表是从共享盘复制到本地 ``_work/`` 的副本——**共享盘全程只读**,
|
||||
所有写值只落本地副本。写入用 zip + XML 直接改单元格值(inlineStr 存文本、<v> 存数字),
|
||||
不走 openpyxl save,避免十几 MB 总表里的透视 / 公式 / 格式被重写丢失。
|
||||
"""
|
||||
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
|
||||
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
_ROW_RE = re.compile(r'<row([^>]*?)(?:/>|>(.*?)</row>)', 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):
|
||||
"""马敏团购总表的本地副本(由 share_copy 从共享盘拉来,不回写共享盘)。"""
|
||||
return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR,
|
||||
f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx')
|
||||
|
||||
|
||||
def _meituan_source(day):
|
||||
"""优先用 daily_detail 处理过的本地副本,否则取共享盘当天表。"""
|
||||
name = f'美团{day.month}.{day.day}.xlsx'
|
||||
local = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, name)
|
||||
if os.path.isfile(local):
|
||||
return local
|
||||
from ..data import share_copy
|
||||
return os.path.join(share_copy.day_dir(config.SHARE_CHECK_ROOT, day), name)
|
||||
|
||||
|
||||
def _douyin_source(day, douyin_dir=''):
|
||||
root = str(douyin_dir or config.DOUYIN_WORK_DIR).strip().strip('"')
|
||||
return os.path.join(root, f'{config.DOUYIN_TABLE_PREFIX}{day.month}.{day.day}'
|
||||
f'{config.DOUYIN_TABLE_EXT}')
|
||||
|
||||
|
||||
def _group_pay_source(day, crm_dir=''):
|
||||
"""CRM 导出的团购支付数据:团购支付数据-YYYYMMDD.xlsx(日期即营业日)。"""
|
||||
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'<c r="{letters}{row_no}"{s_attr} t="b"><v>{int(value)}</v></c>'
|
||||
if isinstance(value, (int, float)):
|
||||
return f'<c r="{letters}{row_no}"{s_attr}><v>{value}</v></c>'
|
||||
return (f'<c r="{letters}{row_no}"{s_attr} t="inlineStr">'
|
||||
f'<is><t>{escape(str(value))}</t></is></c>')
|
||||
|
||||
|
||||
def _set_row_values(row_xml, row_no, values, lo, hi):
|
||||
"""只替换 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([^>]*?)/?>', row_xml)
|
||||
attr_text = attrs.group(1).rstrip() if attrs else ''
|
||||
if not attr_text:
|
||||
attr_text = ' r="%d"' % row_no
|
||||
head = '<row' + attr_text + '>'
|
||||
return head + ''.join(cell for _, cell in keep) + '</row>'
|
||||
|
||||
|
||||
def _patch_sheet_xml(xml_text, rows, start_row, start_col):
|
||||
"""清空目标 sheet 的数据区(仅源列范围)后写入新值,返回新 XML。"""
|
||||
existing = {}
|
||||
for m in _ROW_RE.finditer(xml_text):
|
||||
head = '<row' + m.group(1) + '>'
|
||||
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'<row r="{row_no}">' + ''.join(
|
||||
_make_cell(row_no, cnum, value) for cnum, value in sorted(values.items())) + '</row>'
|
||||
if old:
|
||||
out = out.replace(old, new, 1)
|
||||
|
||||
added = ''.join(
|
||||
f'<row r="{row_no}">' + ''.join(
|
||||
_make_cell(row_no, lo + offset, value)
|
||||
for offset, value in enumerate(rows[row_no - start_row]) if value is not None)
|
||||
+ '</row>'
|
||||
for row_no in range(last_existing + 1, max(needed, last_existing) + 1)
|
||||
)
|
||||
if added:
|
||||
out = out.replace('</sheetData>', added + '</sheetData>', 1)
|
||||
return out
|
||||
|
||||
|
||||
def _write_master(path, jobs):
|
||||
"""按 sheet 批量替换单元格值,其余 zip 条目原样流式复制。"""
|
||||
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()
|
||||
# Windows 上必须等源 zip 关闭后才能替换
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def run(day=None, douyin_dir='', crm_dir='', dry_run=False):
|
||||
"""把美团 / 抖音报表与 CRM 团购支付数据贴进本地总表副本(只写值)。
|
||||
|
||||
Args:
|
||||
day: 核对日期(默认今天)
|
||||
douyin_dir: 抖音表目录(默认 config.DOUYIN_WORK_DIR)
|
||||
crm_dir: CRM 导出目录(默认 config.CRM_EXPORT_DIR)
|
||||
dry_run: 只读源表、不写总表
|
||||
|
||||
Returns:
|
||||
``{"ok", "message", "day", "path", "meituan_rows", "douyin_rows", "group_rows"}``
|
||||
"""
|
||||
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
|
||||
|
||||
jobs = []
|
||||
mt = _meituan_source(target)
|
||||
if os.path.isfile(mt):
|
||||
values = _read_values(mt, 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(f'{os.path.basename(mt)}【报表】无数据,跳过新美大粘贴', 'WARN')
|
||||
else:
|
||||
config.log(f'未找到美团表:{mt},跳过新美大粘贴', 'WARN')
|
||||
|
||||
dy = _douyin_source(target, douyin_dir)
|
||||
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(f'{os.path.basename(dy)}【报表】无数据,跳过抖音粘贴', 'WARN')
|
||||
else:
|
||||
config.log(f'未找到抖音表:{dy},跳过抖音粘贴', 'WARN')
|
||||
|
||||
# CRM 团购支付数据 → 【团购统计】A~I(同结构,表头第 1 行、数据第 2 行起)
|
||||
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(f'{os.path.basename(gp)}【团购统计】无数据,跳过', '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:
|
||||
tip = '(网络路径不可达或无写权限)' if getattr(e, 'winerror', None) in (5, 53, 67, 64) else ''
|
||||
result['message'] = f'写入马敏团购总表失败:{e}{tip}'
|
||||
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
|
||||
@@ -1,305 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""门店归属:把美团收益明细的「消费门店」翻译成内部门店 + 品牌。
|
||||
|
||||
两步走,都不依赖字符串模糊匹配:
|
||||
|
||||
1. **券号 join**(主):``crm_store`` 拉到的「券号 → CRM 门店」与收益明细的券号对齐,
|
||||
命中即得到内部门店(订单级唯一,实测 100%);
|
||||
2. **映射表复用**(补):历史命中过的「美团门店名 → 内部门店」落盘累积,
|
||||
本期虽然没取到券号(跨月补单 / CRM 未同步)也能直接翻译。
|
||||
|
||||
产物 ``门店核对_起_止.xlsx``(与台账同目录,不改动台账本身):
|
||||
|
||||
* ``门店映射``:美团门店名 → 内部门店 / 品牌 / CRM 门店ID / 命中单数
|
||||
* ``门店汇总``:按内部门店汇总订单数与金额(财务按店核对用)
|
||||
* ``未匹配``:券号与映射表都没对上的订单,人工确认一次后可写回映射表
|
||||
|
||||
映射表冲突(同一美团门店名对到多个内部门店,常见于通兑券跨店核销)按票数取众数,
|
||||
并在「门店映射」的备注列标出,便于人工复核。
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from .. import config
|
||||
from ..data import crm_store
|
||||
|
||||
# 收益明细里用到的列(按表头关键词定位,不写死列号)
|
||||
COL_TICKET = '券号'
|
||||
COL_SHOP = '消费门店'
|
||||
COL_TIME = '验券/退款/调整时间'
|
||||
COL_GROSS = '总收入(元)'
|
||||
COL_NET = '结算价'
|
||||
COL_FEE = '平台技术服务费(元)'
|
||||
COL_MARKETING = '商家营销费用(元)'
|
||||
COL_CHANNEL = '渠道佣金(元)'
|
||||
|
||||
_HEADER_FILL = PatternFill('solid', fgColor='DDEBF7')
|
||||
_WARN_FILL = PatternFill('solid', fgColor='FCE4D6')
|
||||
|
||||
|
||||
def _find_col(header, keyword, *, exact=True):
|
||||
"""按表头关键词定位列下标(0 起);``exact=False`` 时用前缀/包含。"""
|
||||
for idx, name in enumerate(header):
|
||||
text = str(name or '').strip()
|
||||
if (text == keyword) if exact else (keyword in text):
|
||||
return idx
|
||||
return -1
|
||||
|
||||
|
||||
def _latest_detail():
|
||||
"""月份/修改时间最新的团购收益明细(金色湖畔前缀的文件天然不匹配)。"""
|
||||
paths = glob.glob(os.path.join(config.WORK_DIR, config.DETAIL_GLOB))
|
||||
paths = [p for p in paths 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 _to_float(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 _load_map():
|
||||
"""读累积映射表;损坏/缺失时返回空表(不阻断)。"""
|
||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
||||
if not os.path.exists(path):
|
||||
return {'shops': {}}
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fp:
|
||||
data = json.load(fp)
|
||||
except (OSError, ValueError) as e:
|
||||
config.log(f'门店映射表读取失败,按空表处理:{e}', 'WARN')
|
||||
return {'shops': {}}
|
||||
if not isinstance(data, dict) or not isinstance(data.get('shops'), dict):
|
||||
return {'shops': {}}
|
||||
return data
|
||||
|
||||
|
||||
def _save_map(data):
|
||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as fp:
|
||||
json.dump(data, fp, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, path)
|
||||
return path
|
||||
|
||||
|
||||
def _read_detail(path):
|
||||
"""读收益明细:返回 (表头, 数据行列表, 列下标字典)。"""
|
||||
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=config.HEADER_ROW, max_row=config.HEADER_ROW,
|
||||
max_col=ws.max_column, values_only=True)))
|
||||
cols = {
|
||||
'ticket': _find_col(header, COL_TICKET),
|
||||
'shop': _find_col(header, COL_SHOP),
|
||||
'time': _find_col(header, COL_TIME),
|
||||
'gross': _find_col(header, COL_GROSS),
|
||||
'net': _find_col(header, COL_NET, exact=False),
|
||||
'fee': _find_col(header, COL_FEE),
|
||||
'marketing': _find_col(header, COL_MARKETING),
|
||||
'channel': _find_col(header, COL_CHANNEL),
|
||||
}
|
||||
missing = [k for k in ('ticket', 'shop', 'time') if cols[k] < 0]
|
||||
if missing:
|
||||
raise RuntimeError(f'收益明细缺少必需列:{missing}(表头第 {config.HEADER_ROW} 行)')
|
||||
rows = []
|
||||
for row in ws.iter_rows(min_row=config.DATA_START_ROW, max_col=len(header),
|
||||
values_only=True):
|
||||
if not any(v not in (None, '') for v in row):
|
||||
continue
|
||||
rows.append(row)
|
||||
return header, rows, cols
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _day_of(value):
|
||||
return crm_store._to_date(value)
|
||||
|
||||
|
||||
def _write_output(path, mapped_names, summary, unmatched):
|
||||
"""写门店核对 xlsx(新建文件,不动台账)。"""
|
||||
wb = openpyxl.Workbook()
|
||||
head_font = Font(bold=True)
|
||||
|
||||
# ---------- sheet1 门店映射 ----------
|
||||
ws = wb.active
|
||||
ws.title = '门店映射'
|
||||
head = ['美团门店名', '内部门店', '品牌', 'CRM门店ID', '累计命中单数', '备注']
|
||||
ws.append(head)
|
||||
for idx, (name, info) in enumerate(sorted(mapped_names.items()), 1):
|
||||
votes = info.get('votes') or {}
|
||||
note = ''
|
||||
if len(votes) > 1:
|
||||
others = {k: v for k, v in votes.items() if k != info.get('shop')}
|
||||
if others:
|
||||
note = '另有 ' + '、'.join(f'{k}({v})' for k, v in others.items()) + ' 单(跨店核销)'
|
||||
ws.append([name, info.get('shop', ''), info.get('brand', ''), info.get('shop_id', ''),
|
||||
sum(votes.values()) or info.get('hits', 0), note])
|
||||
if note:
|
||||
for cell in ws[idx + 1]:
|
||||
cell.fill = _WARN_FILL
|
||||
|
||||
# ---------- sheet2 门店汇总 ----------
|
||||
ws2 = wb.create_sheet('门店汇总')
|
||||
ws2.append(['内部门店', '品牌', '订单数', '总收入', '结算价', '平台技术服务费',
|
||||
'商家营销费用', '渠道佣金'])
|
||||
total = [0, 0.0, 0.0, 0.0, 0.0, 0.0]
|
||||
for shop in sorted(summary, key=lambda s: (summary[s]['brand'], s)):
|
||||
item = summary[shop]
|
||||
ws2.append([shop, item['brand'], item['count'], round(item['gross'], 2),
|
||||
round(item['net'], 2), round(item['fee'], 2),
|
||||
round(item['marketing'], 2), round(item['channel'], 2)])
|
||||
total[0] += item['count']
|
||||
total[1] += item['gross']
|
||||
total[2] += item['net']
|
||||
total[3] += item['fee']
|
||||
total[4] += item['marketing']
|
||||
total[5] += item['channel']
|
||||
ws2.append(['合计', '', total[0]] + [round(x, 2) for x in total[1:]])
|
||||
|
||||
# ---------- sheet3 未匹配 ----------
|
||||
ws3 = wb.create_sheet('未匹配')
|
||||
ws3.append(['券号', '美团门店', '验券时间', '总收入', '说明'])
|
||||
for row in unmatched:
|
||||
ws3.append(row)
|
||||
|
||||
for sheet in (ws, ws2, ws3):
|
||||
for cell in sheet[1]:
|
||||
cell.font = head_font
|
||||
cell.fill = _HEADER_FILL
|
||||
cell.alignment = Alignment(horizontal='center')
|
||||
sheet.freeze_panes = 'A2'
|
||||
for col in range(1, sheet.max_column + 1):
|
||||
width = max((len(str(sheet.cell(r, col).value or ''))
|
||||
for r in range(1, min(sheet.max_row, 200) + 1)), default=8)
|
||||
sheet.column_dimensions[get_column_letter(col)].width = min(46, max(10, width + 6))
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
def run(detail_path='', dry_run=False, progress_from=78, progress_to=88):
|
||||
"""执行门店归属核对。
|
||||
|
||||
Args:
|
||||
detail_path: 指定收益明细;空则取目录内最新一份
|
||||
dry_run: 只统计不写文件(映射表也不落盘)
|
||||
progress_from / progress_to: 拉 CRM 时的进度区间(0~100)
|
||||
|
||||
Returns:
|
||||
``{"ok", "message", "path", "mapped", "unmapped", "stores", "conflicts"}``
|
||||
"""
|
||||
if not crm_store.available():
|
||||
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||
'conflicts': [], 'message': '未挂载 crm_sdk,跳过门店归属(需插件声明 requires.sdks)'}
|
||||
|
||||
path = detail_path or _latest_detail()
|
||||
if not path or not os.path.exists(path):
|
||||
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||
'conflicts': [], 'message': '未找到团购收益明细,无法做门店归属'}
|
||||
|
||||
config.log(f'门店归属:读收益明细 {os.path.basename(path)}')
|
||||
header, rows, cols = _read_detail(path)
|
||||
|
||||
# 1) 收集日期 → 拉 CRM 券号表
|
||||
days = {d for d in (_day_of(r[cols['time']]) for r in rows if cols['time'] < len(r)) if d}
|
||||
if not days:
|
||||
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||
'conflicts': [], 'message': '收益明细的「验券/退款/调整时间」全为空,跳过门店归属'}
|
||||
config.log(f'门店归属:明细 {len(rows)} 行,验券日期 {min(days)}~{max(days)}({len(days)} 天)')
|
||||
crm = crm_store.load(days, progress_from=progress_from, progress_to=progress_to)
|
||||
if not crm.get('ok'):
|
||||
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||
'conflicts': [], 'message': crm.get('message') or 'CRM 券号取数为空'}
|
||||
config.log(crm.get('message') or '')
|
||||
tickets = crm['tickets']
|
||||
|
||||
# 2) 券号 join,累积映射表
|
||||
store = _load_map()
|
||||
shops = store['shops']
|
||||
summary = defaultdict(lambda: {'brand': '', 'count': 0, 'gross': 0.0, 'net': 0.0,
|
||||
'fee': 0.0, 'marketing': 0.0, 'channel': 0.0})
|
||||
unmatched = []
|
||||
mapped_cnt = unmapped_cnt = 0
|
||||
conflicts = []
|
||||
|
||||
for row in rows:
|
||||
def cell(key):
|
||||
idx = cols[key]
|
||||
return row[idx] if 0 <= idx < len(row) else None
|
||||
|
||||
name = str(cell('shop') or '').strip()
|
||||
code = str(cell('ticket') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
hit = tickets.get(code)
|
||||
info = shops.get(name) or {}
|
||||
shop = (hit or {}).get('shop') or info.get('shop') or ''
|
||||
if not shop:
|
||||
unmapped_cnt += 1
|
||||
unmatched.append([code, name, str(cell('time') or '')[:19],
|
||||
round(_to_float(cell('gross')), 2), 'CRM 与映射表均未命中'])
|
||||
continue
|
||||
mapped_cnt += 1
|
||||
|
||||
# 命中结果回写映射表(票数累计,冲突交给备注列提示)
|
||||
votes = info.get('votes') or {}
|
||||
if hit:
|
||||
votes[shop] = int(votes.get(shop, 0)) + 1
|
||||
entry = shops.setdefault(name, {})
|
||||
entry['votes'] = votes
|
||||
entry['shop'] = max(votes, key=votes.get) if votes else shop
|
||||
entry['shop_id'] = (hit or {}).get('shop_id') or info.get('shop_id', '')
|
||||
entry['brand'] = (hit or {}).get('brand') or info.get('brand', '')
|
||||
entry['updated'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
item = summary[shop]
|
||||
item['brand'] = entry['brand'] or item['brand']
|
||||
item['count'] += 1
|
||||
item['gross'] += _to_float(cell('gross'))
|
||||
item['net'] += _to_float(cell('net'))
|
||||
item['fee'] += _to_float(cell('fee'))
|
||||
item['marketing'] += _to_float(cell('marketing'))
|
||||
item['channel'] += _to_float(cell('channel'))
|
||||
|
||||
conflicts = [f'{k} → {v["shop"]}' for k, v in shops.items()
|
||||
if len(v.get('votes') or {}) > 1]
|
||||
|
||||
out_from, out_to = min(days).isoformat(), max(days).isoformat()
|
||||
out_name = f'{config.STORE_OUT_PREFIX}_{out_from.replace("-", "")}_{out_to.replace("-", "")}.xlsx'
|
||||
out_path = os.path.join(config.WORK_DIR, out_name)
|
||||
|
||||
if dry_run:
|
||||
message = (f'[演练] 门店归属 {mapped_cnt}/{mapped_cnt + unmapped_cnt} 行,'
|
||||
f'覆盖 {len(summary)} 家内部门店,未匹配 {unmapped_cnt} 行;不写文件')
|
||||
config.log(message)
|
||||
return {'ok': True, 'path': '', 'mapped': mapped_cnt, 'unmapped': unmapped_cnt,
|
||||
'stores': len(summary), 'conflicts': conflicts, 'message': message}
|
||||
|
||||
_write_output(out_path, shops, summary, unmatched)
|
||||
saved_map = _save_map(store)
|
||||
message = (f'门店归属完成:{mapped_cnt}/{mapped_cnt + unmapped_cnt} 行已归属,'
|
||||
f'{len(summary)} 家内部门店;未匹配 {unmapped_cnt} 行;'
|
||||
f'结果 {os.path.basename(out_path)},映射表 {os.path.basename(saved_map)}')
|
||||
if conflicts:
|
||||
message += f';{len(conflicts)} 家门店存在跨店核销(见备注列)'
|
||||
config.log(message)
|
||||
return {'ok': True, 'path': out_path, 'mapped': mapped_cnt, 'unmapped': unmapped_cnt,
|
||||
'stores': len(summary), 'conflicts': conflicts, 'message': message}
|
||||
Reference in New Issue
Block a user