feat(xq0085): 团购核对支持对比表与门店归属(v1.1.0)
This commit is contained in:
@@ -1,49 +1,106 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础信息补维护:检查【报表】里 VLOOKUP 补不到(#N/A)的新增门店/新增套餐。
|
||||
|
||||
比对【报表】A/B 列与【基础信息】A/E 列,新增项写入本地副本。
|
||||
同时检查固定 VLOOKUP 范围上界:到 90% 提示扩范围,超界提示人工改公式(不改表)。
|
||||
比对【报表】A/B 列(平台门店名 / 平台套餐名)与【基础信息】A/E 列,新增项写入本地副本:
|
||||
门店写 A(平台名)+ B(内部名,猜不到则同名)+ C(品牌);套餐写 E(平台名)+ F(项目名)。
|
||||
|
||||
美团与抖音两套表结构一致(A/B 门店、E/F 品项),只有 sheet 名、起始行和 VLOOKUP 上界不同,
|
||||
差异集中在 :func:`layout`;扫描一律读 ``data_only`` 的值,写入再用可保存的工作簿,避免读到公式。
|
||||
同时检查固定 VLOOKUP 范围上界:到 90% 提示扩范围,超界提示人工改公式(不改公式)。
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
import openpyxl
|
||||
|
||||
from .. import config
|
||||
from . import sheet_xml
|
||||
|
||||
COL_BI_A = 1
|
||||
COL_BI_B = 2
|
||||
COL_BI_C = 3
|
||||
COL_BI_E = 5
|
||||
COL_BI_F = 6
|
||||
|
||||
LAYOUT_MEITUAN = 'meituan'
|
||||
LAYOUT_DOUYIN = 'douyin'
|
||||
|
||||
def _read_report_pairs(ws):
|
||||
|
||||
def layout(name=LAYOUT_MEITUAN):
|
||||
"""返回一套基础信息布局:sheet 名、数据起始行、VLOOKUP 上界。"""
|
||||
if name == LAYOUT_DOUYIN:
|
||||
return {'label': '抖音',
|
||||
'base_sheet': config.DY_BASE_SHEET,
|
||||
'report_sheet': config.REPORT_SHEET,
|
||||
'report_start': config.REPORT_DATA_START,
|
||||
'shop_row': config.DY_BASE_INFO_ROW,
|
||||
'item_row': config.DY_BASE_ITEM_ROW,
|
||||
'shop_limit': config.DY_BASE_INFO_VLOOKUP_MAX,
|
||||
'item_limit': config.DY_BASE_ITEM_VLOOKUP_MAX}
|
||||
return {'label': '美团',
|
||||
'base_sheet': config.BASE_SHEET,
|
||||
'report_sheet': config.REPORT_SHEET,
|
||||
'report_start': config.REPORT_DATA_START,
|
||||
'shop_row': config.BASE_INFO_ROW,
|
||||
'item_row': config.BASE_ITEM_ROW,
|
||||
'shop_limit': config.BASE_INFO_VLOOKUP_MAX,
|
||||
'item_limit': config.BASE_ITEM_VLOOKUP_MAX}
|
||||
|
||||
|
||||
def _reset_if_needed(ws):
|
||||
"""模板/导出的 dimension 常写成 1×1 或百万行。"""
|
||||
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_report_pairs(ws, start_row=None):
|
||||
pairs = []
|
||||
seen = set()
|
||||
for r in range(config.REPORT_DATA_START, int(ws.max_row or 0) + 1):
|
||||
shop = str(ws.cell(r, 1).value or '').strip()
|
||||
item = str(ws.cell(r, 2).value or '').strip()
|
||||
start = config.REPORT_DATA_START if start_row is None else start_row
|
||||
skipped = 0
|
||||
for row in ws.iter_rows(min_row=start, max_col=2, values_only=True):
|
||||
shop = str(row[0] or '').strip() if len(row) > 0 else ''
|
||||
item = str(row[1] or '').strip() if len(row) > 1 else ''
|
||||
if shop.startswith('=') or item.startswith('='):
|
||||
# 用非 data_only 打开时会读到公式文本,绝不能当门店/套餐名写进基础信息
|
||||
skipped += 1
|
||||
continue
|
||||
if shop and shop != '0' and (shop, item) not in seen:
|
||||
seen.add((shop, item))
|
||||
pairs.append((shop, item))
|
||||
if skipped:
|
||||
config.log(f'报表 A/B 读到 {skipped} 行公式文本(应 data_only 打开),已跳过', 'WARN')
|
||||
return pairs
|
||||
|
||||
|
||||
def _key(text):
|
||||
"""判重键:VLOOKUP 大小写不敏感,判重也必须归一,否则 HiFi/HIFI 会被当成新门店。"""
|
||||
return str(text or '').strip().casefold()
|
||||
|
||||
|
||||
def _column_values(ws, col, start_row):
|
||||
values = set()
|
||||
"""返回 (归一化判重键集合, 末行号, 原始值列表去重保序)。"""
|
||||
keys = set()
|
||||
raw = []
|
||||
last = start_row - 1
|
||||
for r in range(start_row, int(ws.max_row or 0) + 1):
|
||||
v = str(ws.cell(r, col).value or '').strip()
|
||||
for offset, row in enumerate(ws.iter_rows(min_row=start_row, max_col=col,
|
||||
values_only=True)):
|
||||
v = str(row[col - 1] or '').strip() if len(row) >= col else ''
|
||||
if v and v != '0':
|
||||
values.add(v)
|
||||
last = r
|
||||
return values, last
|
||||
k = _key(v)
|
||||
if k not in keys:
|
||||
keys.add(k)
|
||||
raw.append(v)
|
||||
last = start_row + offset
|
||||
return keys, last, raw
|
||||
|
||||
|
||||
def _load_shop_map():
|
||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
||||
path = os.path.join(config.OUT_DIR, config.STORE_MAP_FILE)
|
||||
try:
|
||||
with open(path, encoding='utf-8-sig') as fp:
|
||||
data = json.load(fp)
|
||||
@@ -53,109 +110,235 @@ def _load_shop_map():
|
||||
|
||||
|
||||
def _guess_shop(name, existing, shop_map):
|
||||
"""猜内部门店名:先查门店映射表(CRM 名 ↔ 内部名),再按相似度兜底。"""
|
||||
name_key = _key(name)
|
||||
pool = [(e, _key(e)) for e in existing]
|
||||
known = {k for _, k in pool}
|
||||
for crm, info in shop_map.items():
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
if str(info.get('shop') or info.get('门店') or '').strip() in existing:
|
||||
if crm and (crm in name or name in crm):
|
||||
return str(info.get('shop') or info.get('门店')).strip(), \
|
||||
str(info.get('brand') or info.get('品牌') or '').strip()
|
||||
internal = str(info.get('shop') or info.get('门店') or '').strip()
|
||||
if internal and _key(internal) in known:
|
||||
crm_key = _key(crm)
|
||||
if crm_key and (crm_key in name_key or name_key in crm_key):
|
||||
return internal, str(info.get('brand') or info.get('品牌') or '').strip()
|
||||
best, score = '', 0.0
|
||||
for e in existing:
|
||||
s = SequenceMatcher(None, name, e).ratio()
|
||||
for orig, key in pool:
|
||||
s = SequenceMatcher(None, name_key, key).ratio()
|
||||
if s > score:
|
||||
best, score = e, s
|
||||
best, score = orig, s
|
||||
return (best if score >= 0.45 else ''), ''
|
||||
|
||||
|
||||
def _guess_item(name):
|
||||
if '【' in name and '】' in name:
|
||||
return name.split('【', 1)[1].split('】', 1)[0].strip()
|
||||
_NORM_MAP = {ord('('): '(', ord(')'): ')', ord('['): '[', ord(']'): ']',
|
||||
ord('【'): '[', ord('】'): ']', ord(' '): ' ', ord('·'): '', ord('•'): '',
|
||||
ord('×'): 'x', ord('*'): '*'}
|
||||
|
||||
|
||||
def _norm_item(text):
|
||||
"""归一化:全半角括号统一、去 ·/空白/「分钟」/括号,便于关键词包含匹配。"""
|
||||
t = str(text or '').translate(_NORM_MAP)
|
||||
t = re.sub(r'\s+', '', t).lower().replace('分钟', '')
|
||||
return re.sub(r'[()\[\]]', '', t)
|
||||
|
||||
|
||||
def _item_rules():
|
||||
rules = [(_norm_item(k), v) for k, v in config.ITEM_KEYWORD_RULES]
|
||||
rules.sort(key=lambda kv: len(kv[0]), reverse=True) # 长关键词优先
|
||||
return rules
|
||||
|
||||
|
||||
# 能加人数后缀的基础项目(双人/三人餐)
|
||||
_HEADCOUNT_BASE = ('龙手足道', '印象贵足', '太极指压', '筋络归真', '玄门归真', '培元归真')
|
||||
|
||||
|
||||
def _headcount_suffix(normed):
|
||||
"""识别双人/三人:x2 / ×2 / 双人 → 双人餐;x3 / 三人 → 三人餐。"""
|
||||
if '三人' in normed or 'x3' in normed:
|
||||
return '三人餐'
|
||||
if '双人' in normed or 'x2' in normed:
|
||||
return '双人餐'
|
||||
return ''
|
||||
|
||||
|
||||
def run(table_path='', dry_run=False):
|
||||
def _guess_item(name):
|
||||
"""套餐名 → 项目:按关键词规则(长词优先)匹配,双人/三人餐自动加后缀。
|
||||
|
||||
匹配不到返回空——**不做【】提取**,因为【】里是套餐分类(健康足体/人气轻养等),
|
||||
当成项目会写错;空值交给人工补,不会污染基础信息。
|
||||
"""
|
||||
normed = _norm_item(name)
|
||||
suffix = _headcount_suffix(normed)
|
||||
for keyword, value in _item_rules():
|
||||
if not keyword or keyword not in normed:
|
||||
continue
|
||||
if suffix and value in _HEADCOUNT_BASE:
|
||||
return value + suffix
|
||||
return value
|
||||
return ''
|
||||
|
||||
|
||||
def scan(workbook, lay=None):
|
||||
"""读【报表】A/B 与【基础信息】A/E,返回待补条目(只读,不写表)。
|
||||
|
||||
``workbook`` 必须是 ``data_only=True`` 打开的,否则报表读到的是公式文本。
|
||||
"""
|
||||
lay = lay or layout()
|
||||
out = {'ok': False, 'new_shops': [], 'new_items': [], 'range_warnings': [],
|
||||
'message': '', 'written': 0}
|
||||
if lay['base_sheet'] not in workbook.sheetnames or \
|
||||
lay['report_sheet'] not in workbook.sheetnames:
|
||||
out['message'] = f'缺少【{lay["base_sheet"]}】或【{lay["report_sheet"]}】'
|
||||
return out
|
||||
base = workbook[lay['base_sheet']]
|
||||
report = workbook[lay['report_sheet']]
|
||||
for ws in (base, report):
|
||||
_reset_if_needed(ws)
|
||||
pairs = _read_report_pairs(report, lay['report_start'])
|
||||
shops, last_a, shop_values = _column_values(base, COL_BI_A, lay['shop_row'])
|
||||
items, last_e, _ = _column_values(base, COL_BI_E, lay['item_row'])
|
||||
internal_shops, _, internal_values = _column_values(base, COL_BI_B, lay['shop_row'])
|
||||
shop_map = _load_shop_map()
|
||||
|
||||
new_shops, new_items = [], []
|
||||
seen_shops, seen_items = set(), set()
|
||||
for shop, item in pairs:
|
||||
shop_key = _key(shop)
|
||||
if shop_key and shop_key not in shops and shop_key not in seen_shops:
|
||||
# 内部名候选池优先用 B 列(已是内部名),没有再退回 A 列
|
||||
internal, brand = _guess_shop(shop, internal_values or shop_values, shop_map)
|
||||
new_shops.append({'crm': shop, 'internal': internal, 'brand': brand})
|
||||
seen_shops.add(shop_key)
|
||||
item_key = _key(item)
|
||||
if item_key and item_key not in items and item_key not in seen_items:
|
||||
internal_item = _guess_item(item)
|
||||
if internal_item:
|
||||
new_items.append({'crm': item, 'internal': internal_item})
|
||||
seen_items.add(item_key)
|
||||
|
||||
warnings = []
|
||||
for name, last, limit in (
|
||||
('门店映射(A~B)', last_a, lay['shop_limit']),
|
||||
('品项映射(E~F)', last_e, lay['item_limit']),
|
||||
):
|
||||
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%}),建议尽快扩范围')
|
||||
for warning in warnings:
|
||||
config.log(warning, 'WARN')
|
||||
|
||||
out.update(ok=True, new_shops=new_shops, new_items=new_items,
|
||||
range_warnings=warnings, last_shop=last_a, last_item=last_e)
|
||||
return out
|
||||
|
||||
|
||||
def apply(workbook, scanned, lay=None):
|
||||
"""把 :func:`scan` 的结果写进【基础信息】,返回写入行数;不做任何猜测。"""
|
||||
lay = lay or layout()
|
||||
base = workbook[lay['base_sheet']]
|
||||
shops, last_a, _ = _column_values(base, COL_BI_A, lay['shop_row'])
|
||||
items, last_e, _ = _column_values(base, COL_BI_E, lay['item_row'])
|
||||
changed = 0
|
||||
r = last_a + 1
|
||||
for entry in scanned.get('new_shops') or []:
|
||||
crm = entry.get('crm') or ''
|
||||
crm_key = _key(crm)
|
||||
if not crm_key or crm_key in shops:
|
||||
continue
|
||||
base.cell(r, COL_BI_A, crm)
|
||||
base.cell(r, COL_BI_B, entry.get('internal') or crm)
|
||||
if entry.get('brand'):
|
||||
base.cell(r, COL_BI_C, entry['brand'])
|
||||
shops.add(crm_key)
|
||||
r += 1
|
||||
changed += 1
|
||||
r = last_e + 1
|
||||
for entry in scanned.get('new_items') or []:
|
||||
crm = entry.get('crm') or ''
|
||||
crm_key = _key(crm)
|
||||
if not crm_key or not entry.get('internal') or crm_key in items:
|
||||
continue
|
||||
base.cell(r, COL_BI_E, crm)
|
||||
base.cell(r, COL_BI_F, entry['internal'])
|
||||
items.add(crm_key)
|
||||
r += 1
|
||||
changed += 1
|
||||
return changed
|
||||
|
||||
|
||||
def write_changes(path, scanned, lay=None):
|
||||
"""把 scan 结果追加到【基础信息】(zip+XML,不破坏透视/外部链接)。
|
||||
|
||||
返回写入的单元格数;门店按 A/B(+C)、套餐按 E/F 追加在各自末行之后。
|
||||
"""
|
||||
lay = lay or layout()
|
||||
cells = []
|
||||
row_no = int(scanned.get('last_shop') or (lay['shop_row'] - 1)) + 1
|
||||
for entry in scanned.get('new_shops') or []:
|
||||
crm = entry.get('crm') or ''
|
||||
if not crm:
|
||||
continue
|
||||
cells.append((row_no, COL_BI_A, crm))
|
||||
cells.append((row_no, COL_BI_B, entry.get('internal') or crm))
|
||||
if entry.get('brand'):
|
||||
cells.append((row_no, COL_BI_C, entry['brand']))
|
||||
row_no += 1
|
||||
row_no = int(scanned.get('last_item') or (lay['item_row'] - 1)) + 1
|
||||
for entry in scanned.get('new_items') or []:
|
||||
crm = entry.get('crm') or ''
|
||||
if not crm or not entry.get('internal'):
|
||||
continue
|
||||
cells.append((row_no, COL_BI_E, crm))
|
||||
cells.append((row_no, COL_BI_F, entry['internal']))
|
||||
row_no += 1
|
||||
if not cells:
|
||||
return 0
|
||||
values = {}
|
||||
for row, col, value in cells:
|
||||
values.setdefault(row, [None] * COL_BI_F)[col - 1] = value
|
||||
sheet_xml.write_rows(path, lay['base_sheet'], values,
|
||||
start_row=min(values), last_row=max(values))
|
||||
return len(cells)
|
||||
|
||||
|
||||
def run(table_path='', dry_run=False, layout_name=LAYOUT_MEITUAN):
|
||||
src = str(table_path or '').strip()
|
||||
if not src:
|
||||
cands = glob.glob(os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, '美团*.xlsx'))
|
||||
cands = glob.glob(os.path.join(config.WORK_DIR, '美团*.xlsx'))
|
||||
src = cands[0] if cands else ''
|
||||
result = {'ok': False, 'message': '', 'path': src,
|
||||
'new_shops': [], 'new_items': [], 'range_warnings': []}
|
||||
'new_shops': [], 'new_items': [], 'range_warnings': [], 'written': 0}
|
||||
if not src or not os.path.isfile(src):
|
||||
result['message'] = '未找到本地美团核对表副本'
|
||||
return result
|
||||
|
||||
wb = openpyxl.load_workbook(src, data_only=False)
|
||||
lay = layout(layout_name)
|
||||
wb = openpyxl.load_workbook(src, read_only=True, data_only=True)
|
||||
try:
|
||||
if config.BASE_SHEET not in wb.sheetnames or config.REPORT_SHEET not in wb.sheetnames:
|
||||
result['message'] = f'{os.path.basename(src)} 缺少【{config.BASE_SHEET}】或【{config.REPORT_SHEET}】'
|
||||
return result
|
||||
base = wb[config.BASE_SHEET]
|
||||
report = wb[config.REPORT_SHEET]
|
||||
pairs = _read_report_pairs(report)
|
||||
shops, last_a = _column_values(base, COL_BI_A, config.BASE_INFO_ROW)
|
||||
items, last_e = _column_values(base, COL_BI_E, config.BASE_ITEM_ROW)
|
||||
shop_map = _load_shop_map()
|
||||
|
||||
new_shops, new_items = [], []
|
||||
for shop, item in pairs:
|
||||
if shop not in shops:
|
||||
internal, brand = _guess_shop(shop, shops, shop_map)
|
||||
new_shops.append({'crm': shop, 'internal': internal, 'brand': brand})
|
||||
if item:
|
||||
internal_item = _guess_item(item)
|
||||
if internal_item and internal_item not in items:
|
||||
new_items.append({'crm': item, 'internal': internal_item})
|
||||
|
||||
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')
|
||||
|
||||
result.update(new_shops=new_shops, new_items=new_items)
|
||||
if dry_run:
|
||||
result.update(ok=True, message=f'[演练] 新增门店 {len(new_shops)} / '
|
||||
f'套餐 {len(new_items)}')
|
||||
return result
|
||||
|
||||
changed = 0
|
||||
r = last_a + 1
|
||||
for entry in new_shops:
|
||||
internal = entry['internal'] or entry['crm']
|
||||
if internal in shops or not entry['crm']:
|
||||
continue
|
||||
base.cell(r, COL_BI_A, entry['crm'])
|
||||
base.cell(r, COL_BI_B, internal)
|
||||
if entry['brand']:
|
||||
base.cell(r, 3, entry['brand'])
|
||||
shops.add(entry['crm'])
|
||||
r += 1
|
||||
changed += 1
|
||||
r = last_e + 1
|
||||
for entry in new_items:
|
||||
if entry['internal'] in items:
|
||||
continue
|
||||
base.cell(r, COL_BI_E, entry['crm'])
|
||||
base.cell(r, COL_BI_F, entry['internal'])
|
||||
items.add(entry['internal'])
|
||||
r += 1
|
||||
changed += 1
|
||||
if changed:
|
||||
wb.save(src)
|
||||
result.update(ok=True, path=src,
|
||||
message=f'基础信息补维护:新增门店 {len(new_shops)} / '
|
||||
f'套餐 {len(new_items)},写入 {changed} 行到本地副本')
|
||||
return result
|
||||
scanned = scan(wb, lay)
|
||||
finally:
|
||||
wb.close()
|
||||
result.update(new_shops=scanned['new_shops'], new_items=scanned['new_items'],
|
||||
range_warnings=scanned['range_warnings'])
|
||||
if not scanned['ok']:
|
||||
result['message'] = f'{os.path.basename(src)} {scanned["message"]}'
|
||||
return result
|
||||
|
||||
new_shops, new_items = scanned['new_shops'], scanned['new_items']
|
||||
if dry_run:
|
||||
result.update(ok=True, message=f'[演练] 新增门店 {len(new_shops)} / '
|
||||
f'套餐 {len(new_items)}')
|
||||
return result
|
||||
if not new_shops and not new_items:
|
||||
result.update(ok=True, path=src, message='基础信息无新增,未改动')
|
||||
return result
|
||||
|
||||
changed = write_changes(src, scanned, lay)
|
||||
result.update(ok=True, path=src, written=changed,
|
||||
message=f'基础信息补维护:新增门店 {len(new_shops)} / '
|
||||
f'套餐 {len(new_items)},写入 {changed} 行到本地副本')
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user