feat(xq0041): 美团/抖音核对迁出至 XQ0085,保留导表与到账统计核对(v1.3.13)
download=只导打款/团购/预订收益明细;check_settlement=到账统计核对(并台账/门店归属/更新核对统计);金色印象与金色湖畔独立浏览器档案;新增 CRM 门店映射、基础信息同步与贴总表逻辑。
This commit is contained in:
@@ -1,19 +1,21 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
||||||
|
|
||||||
执行过程由 action 决定(UI 的两个开关派生):
|
两个独立动作(action),互不混跑:
|
||||||
action='download' → 只下载:登录经营宝(界面配了账号密码则自动填写提交,验证码/选商家仍需人工),
|
|
||||||
按勾选下载打款记录 / 团购收益明细 / 预订收益明细;
|
* ``download`` → 只导表:登录经营宝下载打款记录 / 团购收益明细 / 预订收益明细;
|
||||||
action='reconcile' → 只核对:**不开浏览器**,直接用本机最新的台账与收益明细并入台账、
|
* ``check_settlement`` → 到账统计核对:新美大到账统计的核对
|
||||||
更新核对统计(适合数据已下载、只想重算的场景);
|
(并入台账 → 门店归属 → 更新核对统计)。
|
||||||
action='all' → 下载后再核对(默认)。
|
|
||||||
|
美团核对 / 抖音核对已迁到 XQ0085 团购数据核对插件,本插件不再做。
|
||||||
|
|
||||||
|
``download_before`` 可在核对前先下载;不勾则读本机已有表(只校验文件存在)。
|
||||||
|
|
||||||
多公司(对齐 xq0042 抖音平台核对):金色印象(台账那家)与金色湖畔在平台上是两套登录,
|
多公司(对齐 xq0042 抖音平台核对):金色印象(台账那家)与金色湖畔在平台上是两套登录,
|
||||||
各自用独立的浏览器档案与调试端口(browser_sessions/xq0041 与 xq0041_b,端口 9222 / 9333),
|
各自用独立的浏览器档案与调试端口(browser_sessions/xq0041 与 xq0041_b,端口 9222 / 9333),
|
||||||
登录态互不干扰,避免同浏览器反复切号触发风控。
|
登录态互不干扰,避免同浏览器反复切号触发风控。
|
||||||
run_mode='full' → 只导金色印象 + 并入台账 + 更新核对统计(默认,历史行为)
|
run_mode='full' → 下载时只导金色印象(默认)
|
||||||
run_mode='export_only' → 按 export_companies 勾选的公司各导一份(可只导一家),不写任何表
|
run_mode='export_only' → 下载时按 export_companies 勾选的公司各导一份(不写表)
|
||||||
(湖畔文件名带「金色湖畔_」前缀)
|
|
||||||
并入台账 / 更新核对统计只认金色印象那份明细(湖畔文件天然落在台账 glob 之外)。
|
并入台账 / 更新核对统计只认金色印象那份明细(湖畔文件天然落在台账 glob 之外)。
|
||||||
|
|
||||||
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
||||||
@@ -26,7 +28,7 @@ from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
|||||||
|
|
||||||
from . import config
|
from . import config
|
||||||
from .data import browser, meituan_login, payment_download, profit_download
|
from .data import browser, meituan_login, payment_download, profit_download
|
||||||
from .logic import merge_ledger, stat_links
|
from .logic import merge_ledger, stat_links, store_map
|
||||||
|
|
||||||
|
|
||||||
def _parse_day(s):
|
def _parse_day(s):
|
||||||
@@ -54,38 +56,41 @@ def _resolve_pair(raw_from, raw_to):
|
|||||||
|
|
||||||
|
|
||||||
def _resolve_action(fields):
|
def _resolve_action(fields):
|
||||||
"""决定本次做什么:download / reconcile / all。
|
"""解析动作:download / check_settlement(美团核对已迁到 xq0085)。"""
|
||||||
|
raw = str(fields.get('action') or '').strip().lower()
|
||||||
|
if raw in config.ACTIONS:
|
||||||
|
return raw
|
||||||
|
if raw in ('all', 'reconcile', 'check_meituan'):
|
||||||
|
return config.ACTION_CHECK_SETTLEMENT
|
||||||
|
return config.ACTION_DOWNLOAD
|
||||||
|
|
||||||
UI 会直接给 action;老配置(无 action)按开关推导,缺省视为全流程。
|
|
||||||
"""
|
def _missing_inputs(action, work_dir):
|
||||||
action = str(fields.get('action') or '').strip().lower()
|
"""不下载时校验核对必需的本机文件(只看存在性,不读内容)。"""
|
||||||
if action in ('download', 'reconcile', 'all'):
|
import glob
|
||||||
return action
|
|
||||||
do_download = fields.get('do_download')
|
absent = []
|
||||||
do_reconcile = fields.get('do_reconcile')
|
|
||||||
do_download = True if do_download is None else bool(do_download)
|
def has(pattern):
|
||||||
do_reconcile = True if do_reconcile is None else bool(do_reconcile)
|
return bool(glob.glob(os.path.join(work_dir, pattern)))
|
||||||
if do_download and do_reconcile:
|
|
||||||
return 'all'
|
if action == config.ACTION_CHECK_SETTLEMENT:
|
||||||
if do_download:
|
if not has(config.LEDGER_GLOB):
|
||||||
return 'download'
|
absent.append(config.LEDGER_GLOB)
|
||||||
if do_reconcile:
|
if not has(config.DETAIL_GLOB):
|
||||||
return 'reconcile'
|
absent.append(config.DETAIL_GLOB)
|
||||||
return ''
|
return absent
|
||||||
|
|
||||||
|
|
||||||
class Xq0041Plugin(ScenePlugin):
|
class Xq0041Plugin(ScenePlugin):
|
||||||
id = 'xq0041'
|
id = 'xq0041'
|
||||||
name = '新美大平台核对'
|
name = '新美大平台核对'
|
||||||
version = '1.3.11'
|
version = '1.3.13'
|
||||||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
description = ('美团数据导出与到账统计核对:两个独立动作——「只导表」(下载打款记录/团购/'
|
||||||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
'预订收益明细)、「到账统计核对」(新美大到账统计:并台账 → 门店归属 → '
|
||||||
'并按日期把核对统计表整行同源取数公式(资金组取数)换成当天共享总表的链接;'
|
'更新核对统计)。美团核对与抖音核对已迁到 XQ0085 团购数据核对插件。'
|
||||||
'界面可配账号密码自动填好并勾选用户协议、浏览器内浮层提示你点登录'
|
'界面可配账号密码自动填好,登录/验证码/选商家/选版本由人工完成;'
|
||||||
'(登录按钮/验证码/选门店仍人工),并自动选「非餐饮商家版」;'
|
'金色印象与金色湖畔各自独立浏览器档案与调试端口,登录态互不干扰')
|
||||||
'执行模式分「含写表」(只导金色印象 + 并台账 + 更新核对统计)与'
|
|
||||||
'「仅导出」(金色印象 / 金色湖畔按需勾选,可只导一家,不写表),'
|
|
||||||
'两家各自独立浏览器档案与调试端口,登录态互不干扰')
|
|
||||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||||
uses_month = False
|
uses_month = False
|
||||||
capabilities = ['xq0041']
|
capabilities = ['xq0041']
|
||||||
@@ -102,10 +107,10 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
'enum': [config.RUN_MODE_FULL, config.RUN_MODE_EXPORT_ONLY]},
|
'enum': [config.RUN_MODE_FULL, config.RUN_MODE_EXPORT_ONLY]},
|
||||||
'export_companies': {'type': 'array', 'title': '导出范围(仅导出模式生效)',
|
'export_companies': {'type': 'array', 'title': '导出范围(仅导出模式生效)',
|
||||||
'default': ['a', 'b'], 'items': {'type': 'string'}},
|
'default': ['a', 'b'], 'items': {'type': 'string'}},
|
||||||
'action': {'type': 'string', 'title': '执行过程', 'default': 'all',
|
'action': {'type': 'string', 'title': '执行动作',
|
||||||
'enum': ['all', 'download', 'reconcile']},
|
'default': config.ACTION_CHECK_SETTLEMENT, 'enum': list(config.ACTIONS)},
|
||||||
'do_download': {'type': 'boolean', 'title': '下载数据', 'default': True},
|
'download_before': {'type': 'boolean',
|
||||||
'do_reconcile': {'type': 'boolean', 'title': '更新核对', 'default': True},
|
'title': '核对前先下载(不选则用本机已有表)', 'default': False},
|
||||||
'pay_enabled': {'type': 'boolean', 'title': '下载打款记录', 'default': True},
|
'pay_enabled': {'type': 'boolean', 'title': '下载打款记录', 'default': True},
|
||||||
'pay_date_from': {'type': 'string', 'title': '打款记录-开始日期', 'default': ''},
|
'pay_date_from': {'type': 'string', 'title': '打款记录-开始日期', 'default': ''},
|
||||||
'pay_date_to': {'type': 'string', 'title': '打款记录-结束日期', 'default': ''},
|
'pay_date_to': {'type': 'string', 'title': '打款记录-结束日期', 'default': ''},
|
||||||
@@ -116,6 +121,7 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||||||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||||||
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
||||||
|
'run_store_map': {'type': 'boolean', 'title': '门店归属(CRM 券号)', 'default': True},
|
||||||
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
||||||
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
||||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||||
@@ -128,18 +134,18 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
config.set_debug(fields.get('debug_mode'))
|
config.set_debug(fields.get('debug_mode'))
|
||||||
|
|
||||||
# ---------- 参数 ----------
|
# ---------- 参数 ----------
|
||||||
|
raw_action = str(fields.get('action') or '').strip().lower()
|
||||||
action = _resolve_action(fields)
|
action = _resolve_action(fields)
|
||||||
run_mode = config.normalize_run_mode(fields.get('run_mode'))
|
run_mode = config.normalize_run_mode(fields.get('run_mode'))
|
||||||
if run_mode == config.RUN_MODE_EXPORT_ONLY:
|
|
||||||
# 仅导出:两家公司各导一份,不写任何表(对齐 xq0042 的语义)
|
|
||||||
if action == 'reconcile':
|
|
||||||
raise RuntimeError('「仅导出」模式不做核对;要并台账请把执行模式切成「含写表」')
|
|
||||||
action = 'download'
|
|
||||||
if not action:
|
|
||||||
raise RuntimeError('请至少选择一个执行过程(下载数据 / 更新核对)')
|
|
||||||
do_download = action in ('all', 'download')
|
|
||||||
do_reconcile = action in ('all', 'reconcile')
|
|
||||||
export_only = run_mode == config.RUN_MODE_EXPORT_ONLY
|
export_only = run_mode == config.RUN_MODE_EXPORT_ONLY
|
||||||
|
if export_only and action != config.ACTION_DOWNLOAD:
|
||||||
|
raise RuntimeError('「仅导出」模式不做核对;要核对请把执行模式切成「含写表」')
|
||||||
|
|
||||||
|
only_download = action == config.ACTION_DOWNLOAD
|
||||||
|
check_settlement = action == config.ACTION_CHECK_SETTLEMENT
|
||||||
|
download_before = bool(fields.get('download_before', False))
|
||||||
|
do_download = only_download or download_before
|
||||||
|
do_check = check_settlement
|
||||||
|
|
||||||
codes = []
|
codes = []
|
||||||
if fields.get('profit_group', True):
|
if fields.get('profit_group', True):
|
||||||
@@ -150,6 +156,7 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
dry_run = bool(fields.get('dry_run'))
|
dry_run = bool(fields.get('dry_run'))
|
||||||
run_merge = bool(fields.get('run_merge', True))
|
run_merge = bool(fields.get('run_merge', True))
|
||||||
|
run_store_map = bool(fields.get('run_store_map', True))
|
||||||
run_links = bool(fields.get('run_links', True))
|
run_links = bool(fields.get('run_links', True))
|
||||||
force_login = bool(fields.get('force_login'))
|
force_login = bool(fields.get('force_login'))
|
||||||
# 保存目录同时是台账目录:并入台账 / 更新核对统计都读它
|
# 保存目录同时是台账目录:并入台账 / 更新核对统计都读它
|
||||||
@@ -167,8 +174,16 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
if do_download and not pay_on and not codes:
|
if do_download and not pay_on and not codes:
|
||||||
raise RuntimeError('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
raise RuntimeError('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||||
|
|
||||||
|
# 不下载就核对:只校验本机必需文件是否存在,缺了明确提示先导表
|
||||||
|
if not do_download and do_check:
|
||||||
|
absent = _missing_inputs(action, config.WORK_DIR)
|
||||||
|
if absent:
|
||||||
|
raise RuntimeError(
|
||||||
|
'未勾选「核对前先下载」,且本机缺少核对所需文件:' + '、'.join(absent)
|
||||||
|
+ f'(目录 {config.WORK_DIR});请先执行「只导表」,或勾「核对前先下载」')
|
||||||
|
|
||||||
# 并入台账依赖团购收益明细(台账只收团购口径)
|
# 并入台账依赖团购收益明细(台账只收团购口径)
|
||||||
if do_reconcile and run_merge and not codes and do_download:
|
if check_settlement and run_merge and not codes and do_download:
|
||||||
config.log('未勾选团购收益明细,本次跳过「并入台账」', 'WARN')
|
config.log('未勾选团购收益明细,本次跳过「并入台账」', 'WARN')
|
||||||
run_merge = False
|
run_merge = False
|
||||||
|
|
||||||
@@ -178,33 +193,38 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
os.makedirs(save_dir, exist_ok=True)
|
os.makedirs(save_dir, exist_ok=True)
|
||||||
|
|
||||||
companies = config.companies_for_mode(run_mode, fields.get('export_companies'))
|
companies = config.companies_for_mode(run_mode, fields.get('export_companies'))
|
||||||
plan = []
|
labels = {config.ACTION_DOWNLOAD: '只导表',
|
||||||
|
config.ACTION_CHECK_SETTLEMENT: '到账统计核对'}
|
||||||
|
plan = [labels[action]]
|
||||||
if do_download:
|
if do_download:
|
||||||
plan.append('公司 ' + ' + '.join(c['short'] for c in companies))
|
plan.append('先下载' if do_check else
|
||||||
|
'公司 ' + ' + '.join(c['short'] for c in companies))
|
||||||
if pay_on:
|
if pay_on:
|
||||||
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
||||||
if codes:
|
if codes:
|
||||||
name = '/'.join(n for c, n in ((1, '团购'), (11, '预订')) if c in codes)
|
name = '/'.join(n for c, n in ((1, '团购'), (11, '预订')) if c in codes)
|
||||||
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
||||||
if do_reconcile:
|
if check_settlement:
|
||||||
plan.append('并入台账' if run_merge else '')
|
plan.append('并入台账' if run_merge else '')
|
||||||
|
plan.append('门店归属(CRM 券号)' if run_store_map else '')
|
||||||
plan.append('更新核对统计' if run_links else '')
|
plan.append('更新核对统计' if run_links else '')
|
||||||
plan = [p for p in plan if p]
|
plan = [p for p in plan if p]
|
||||||
config.log(('本次执行:' + ';'.join(plan) if plan else '本次没有可执行的动作')
|
config.log('本次执行:' + ';'.join(plan) + f';目录 {save_dir}'
|
||||||
+ f';目录 {save_dir}'
|
|
||||||
+ ('(只核对不写入)' if dry_run else ''))
|
+ ('(只核对不写入)' if dry_run else ''))
|
||||||
config.log('执行模式:' + ('仅导出(金色印象 + 金色湖畔,不写表)' if export_only
|
config.log('下载:' + ('先下载再核对' if download_before else
|
||||||
else '含写表(只导金色印象 + 并台账 + 更新核对统计)'))
|
('只导表' if only_download else '不下载,用本机已有表')))
|
||||||
|
|
||||||
detail = {'action': action, 'run_mode': run_mode, 'pay': None, 'profit': None,
|
detail = {'action': action, 'action_label': labels[action],
|
||||||
'merge': None, 'links': None, 'results': {},
|
'download_before': download_before, 'run_mode': run_mode,
|
||||||
'companies': [c['short'] for c in companies]}
|
'pay': None, 'profit': None, 'merge': None, 'store': None,
|
||||||
|
'links': None,
|
||||||
|
'results': {}, 'companies': [c['short'] for c in companies]}
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
# ---------- 1~3:登录 + 下载(逐家公司:各自独立浏览器档案 + 端口) ----------
|
# ---------- 1~3:登录 + 下载(逐家公司:各自独立浏览器档案 + 端口) ----------
|
||||||
if do_download:
|
if do_download:
|
||||||
jobs = [(comp, *creds.get(comp['id'], ('', ''))) for comp in companies]
|
jobs = [(comp, *creds.get(comp['id'], ('', ''))) for comp in companies]
|
||||||
dl_end = 60 if do_reconcile else 95
|
dl_end = 60 if do_check else 95
|
||||||
span = (dl_end - 2) / len(jobs)
|
span = (dl_end - 2) / len(jobs)
|
||||||
errors = []
|
errors = []
|
||||||
try:
|
try:
|
||||||
@@ -217,9 +237,10 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
config.log(f'—— {label}:档案 {comp["profile"]} / 端口 {comp["port"]} ——')
|
config.log(f'—— {label}:档案 {comp["profile"]} / 端口 {comp["port"]} ——')
|
||||||
page = browser.open_page(force_login=force_login)
|
page = browser.open_page(force_login=force_login)
|
||||||
try:
|
try:
|
||||||
config.log(f'{label} 登录方式:' + ('界面配置的账号密码自动登录'
|
config.log(f'{label} 登录方式:' + ('界面配置的账号密码自动填入登录页'
|
||||||
if (user and pwd) else '手工登录'))
|
if (user and pwd) else '手工登录'))
|
||||||
ok, msg = meituan_login.ensure_login(page, user, pwd)
|
ok, msg = meituan_login.ensure_login(page, user, pwd,
|
||||||
|
force_login=force_login)
|
||||||
config.log(msg)
|
config.log(msg)
|
||||||
if not ok:
|
if not ok:
|
||||||
raise RuntimeError(f'{label} 登录失败:{msg}')
|
raise RuntimeError(f'{label} 登录失败:{msg}')
|
||||||
@@ -250,6 +271,8 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
if comp.get('ledger'):
|
if comp.get('ledger'):
|
||||||
detail['profit'] = r2
|
detail['profit'] = r2
|
||||||
ctx.progress(int(base + span))
|
ctx.progress(int(base + span))
|
||||||
|
# 下载期间站点可能轮换 Cookie,收尾再落盘一次
|
||||||
|
meituan_login.save_cookies(page)
|
||||||
detail['results'] = detail.get('results') or {}
|
detail['results'] = detail.get('results') or {}
|
||||||
detail['results'][label] = {'ok': True}
|
detail['results'][label] = {'ok': True}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -266,16 +289,31 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
if errors:
|
if errors:
|
||||||
raise RuntimeError(';'.join(errors))
|
raise RuntimeError(';'.join(errors))
|
||||||
|
|
||||||
# ---------- 4~5:并入台账 + 更新核对(不依赖浏览器) ----------
|
# ---------- 核对:到账统计(不依赖浏览器;美团/抖音核对已迁到 xq0085) ----------
|
||||||
if do_reconcile:
|
if do_check:
|
||||||
ctx.progress(65 if do_download else 10)
|
ctx.progress(62 if do_download else 5)
|
||||||
|
|
||||||
|
if check_settlement:
|
||||||
|
# 之前的核对:新美大到账统计
|
||||||
if run_merge:
|
if run_merge:
|
||||||
m = merge_ledger.run(dry_run=dry_run)
|
m = merge_ledger.run(dry_run=dry_run)
|
||||||
config.log(m.get('message') or '')
|
config.log(m.get('message') or '')
|
||||||
detail['merge'] = m
|
detail['merge'] = m
|
||||||
if not m.get('ok'):
|
if not m.get('ok'):
|
||||||
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
||||||
ctx.progress(85 if do_download else 60)
|
if run_store_map:
|
||||||
|
# 门店归属:券号 join CRM,结果单列输出(不动台账)
|
||||||
|
ctx.progress(72 if do_download else 45)
|
||||||
|
sm = store_map.run(dry_run=dry_run,
|
||||||
|
progress_from=(72 if do_download else 45),
|
||||||
|
progress_to=(84 if do_download else 58))
|
||||||
|
config.log(sm.get('message') or '')
|
||||||
|
detail['store'] = sm
|
||||||
|
if not sm.get('ok'):
|
||||||
|
# CRM 未登录 / 未挂载 SDK 时只告警:不影响台账与核对统计
|
||||||
|
config.log(f'门店归属未完成:{sm.get("message")}', 'WARN')
|
||||||
|
|
||||||
|
ctx.progress(88 if do_download else 65)
|
||||||
|
|
||||||
if run_links:
|
if run_links:
|
||||||
# 纯核对时让后端按本机最新明细文件的日期推断(跟随实际数据);
|
# 纯核对时让后端按本机最新明细文件的日期推断(跟随实际数据);
|
||||||
@@ -290,13 +328,16 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
ctx.progress(100)
|
ctx.progress(100)
|
||||||
|
|
||||||
# ---------- 汇总 ----------
|
# ---------- 汇总 ----------
|
||||||
parts = []
|
parts = [detail.get('action_label') or '执行完成']
|
||||||
if detail['pay'] and detail['pay'].get('empty'):
|
if detail['pay'] and detail['pay'].get('empty'):
|
||||||
parts.append(f'打款记录 {pay_from}~{pay_to} 无数据')
|
parts.append(f'打款记录 {pay_from}~{pay_to} 无数据')
|
||||||
if files:
|
if files:
|
||||||
parts.append(f'下载 {len(files)} 个文件')
|
parts.append(f'下载 {len(files)} 个文件')
|
||||||
if detail['merge'] and detail['merge'].get('appended'):
|
if detail['merge'] and detail['merge'].get('appended'):
|
||||||
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
||||||
|
if detail['store'] and detail['store'].get('ok'):
|
||||||
|
parts.append(f'门店归属 {detail["store"]["mapped"]} 行 / '
|
||||||
|
f'{detail["store"]["stores"]} 家店')
|
||||||
if detail['links'] and detail['links'].get('rows'):
|
if detail['links'] and detail['links'].get('rows'):
|
||||||
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
||||||
if not parts:
|
if not parts:
|
||||||
|
|||||||
@@ -60,6 +60,60 @@ SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
|||||||
LINK_BOOK = '马敏团购总表'
|
LINK_BOOK = '马敏团购总表'
|
||||||
LINK_SHEET = '资金组取数'
|
LINK_SHEET = '资金组取数'
|
||||||
|
|
||||||
|
# ==================== 订单收入明细表(团购 + 预订合并) ====================
|
||||||
|
PROFIT_HEADER_ROW = 2 # 团购/预订收益明细的表头行
|
||||||
|
DAILY_SHEET = '订单收入明细表' # 共享表里贴明细的 sheet
|
||||||
|
DAILY_HEADER_ROW = 3 # 该 sheet 的表头行(数据从第 4 行起)
|
||||||
|
DAILY_DATA_START = 4
|
||||||
|
DAILY_WORK_DIR = '_work' # 共享表拉下来的本地副本目录(共享盘只读)
|
||||||
|
# 汇总时剔除的业务类型(C 列);其余全要
|
||||||
|
DAILY_EXCLUDE_BUSINESS = ('其他',)
|
||||||
|
|
||||||
|
# ==================== 基础信息补维护(报表 #N/A → 新增门店/项目) ====================
|
||||||
|
BASE_SHEET = '基础信息' # A~C:消费门店名称 / 门店 / 品牌;E~F:套餐名 / 品项名称
|
||||||
|
REPORT_SHEET = '报表' # J=VLOOKUP(门店名) K=VLOOKUP(套餐名),查不到显示 #N/A
|
||||||
|
REPORT_DATA_START = 5
|
||||||
|
BASE_INFO_ROW = 3 # 基础信息 A/B/C 的数据起始行(第 2 行是表头)
|
||||||
|
BASE_ITEM_ROW = 2 # E/F 的数据起始行
|
||||||
|
# 报表 J/K 的 VLOOKUP 范围上界(写死在公式里:$A$3:$B$1973 / $E$2:$F$12924)
|
||||||
|
BASE_INFO_VLOOKUP_MAX = 1973
|
||||||
|
BASE_ITEM_VLOOKUP_MAX = 12924
|
||||||
|
BASE_RANGE_WARN_RATIO = 0.9 # 用到 90% 就提醒(只告警,不改公式)
|
||||||
|
|
||||||
|
# ==================== 报表粘贴到马敏团购总表(只写值) ====================
|
||||||
|
# 源 → 目标(字段一一对应,按位置贴,不按表头名)
|
||||||
|
MASTER_SHEET_MEITUAN = '平台-新美大' # 美团【报表】I~P → 本 sheet A~H
|
||||||
|
MASTER_SHEET_DOUYIN = '平台-抖音' # 抖音【报表】N~Z → 本 sheet A~M
|
||||||
|
MEITUAN_REPORT_COLS = ('I', 'P')
|
||||||
|
DOUYIN_REPORT_COLS = ('N', 'Z')
|
||||||
|
MASTER_DATA_START = 5 # 平台-新美大 / 平台-抖音 的数据起始行(表头第 3/4 行)
|
||||||
|
MASTER_SHEET_GROUP_STATS = '团购统计' # CRM 团购支付数据 → 本 sheet(A~I 同结构)
|
||||||
|
GROUP_STATS_DATA_START = 2 # 【团购统计】表头第 1 行,数据从第 2 行起
|
||||||
|
CRM_EXPORT_DIR = r'D:\资料\财务\CRM数据导出'
|
||||||
|
CRM_GROUP_PAY_PREFIX = '团购支付数据' # 文件名:团购支付数据-YYYYMMDD.xlsx
|
||||||
|
DOUYIN_WORK_DIR = r'D:\资料\财务\抖音平台核对'
|
||||||
|
DOUYIN_TABLE_PREFIX = '抖音'
|
||||||
|
DOUYIN_TABLE_EXT = '.xlsx'
|
||||||
|
|
||||||
|
# ==================== 共享盘每日核对表(美团M.D.xlsx) ====================
|
||||||
|
# 结构:{SHARE_ROOT}\2026年11月\11.10\美团11.10.xlsx
|
||||||
|
# 每天把昨天那份复制到今天的日期目录,文件名日期同步替换(内容留给人工填)
|
||||||
|
SHARE_CHECK_ROOT = SHARE_ROOT
|
||||||
|
SHARE_TABLE_KEYWORD = '美团'
|
||||||
|
SHARE_TABLE_EXT = '.xlsx'
|
||||||
|
|
||||||
|
# ==================== 门店归属(美团门店名 → 内部门店/品牌) ====================
|
||||||
|
# 口径差异:美团收益明细的日期是「验券/退款/调整时间」,CRM 团购核销报表按「核销日」归档,
|
||||||
|
# 同一笔单在两边可能差一天;实测按 ±1 天取窗口,券号命中率从 78.6% → 100%。
|
||||||
|
CRM_DATE_WINDOW = 1
|
||||||
|
# CRM 团购核销报表 key(crm_sdk.reports.REPORTS)
|
||||||
|
CRM_GROUP_REPORT = 'groupData'
|
||||||
|
CRM_PAGE_SIZE = 500
|
||||||
|
# 累积映射表(美团门店名 → 内部门店),跨次复用,命中过的门店不必再算
|
||||||
|
STORE_MAP_FILE = '门店映射表.json'
|
||||||
|
# 门店核对结果文件前缀:门店核对_起_止.xlsx
|
||||||
|
STORE_OUT_PREFIX = '门店核对'
|
||||||
|
|
||||||
|
|
||||||
def set_work_dir(path=None):
|
def set_work_dir(path=None):
|
||||||
"""界面「保存目录」覆盖默认目录(账单 + 台账同目录)。
|
"""界面「保存目录」覆盖默认目录(账单 + 台账同目录)。
|
||||||
@@ -88,16 +142,14 @@ LOGIN_FRAME_HINTS = (
|
|||||||
|
|
||||||
# 登录后的「选择商家版本」页(epassport,main .biz-item 卡片):
|
# 登录后的「选择商家版本」页(epassport,main .biz-item 卡片):
|
||||||
# 「我是餐饮商家(餐饮商家版)」/「我是非餐饮商家(服务零售商家版)」
|
# 「我是餐饮商家(餐饮商家版)」/「我是非餐饮商家(服务零售商家版)」
|
||||||
# 金色印象属服务零售(足浴/休闲)→ 自动点「我是非餐饮商家」,避免手工点错版本进错后台。
|
# 金色印象属服务零售(足浴/休闲);登录后如出现这一页,由人工点「我是非餐饮商家」,
|
||||||
|
# 这里只用它拼页面提示文案,不再自动点选。
|
||||||
BIZ_LINE_KEYWORD = '非餐饮'
|
BIZ_LINE_KEYWORD = '非餐饮'
|
||||||
BIZ_LINE_MARKERS = ('我是餐饮商家', '我是非餐饮商家')
|
|
||||||
BIZ_LINE_MAX_TRIES = 3 # 最多尝试 3 次(卡片容器 → 确定按钮 → 卡片本身)
|
|
||||||
BIZ_LINE_INTERVAL = 6 # 每次尝试的最小间隔(秒)
|
|
||||||
|
|
||||||
# ==================== 运行参数 ====================
|
# ==================== 运行参数 ====================
|
||||||
LOGIN_WAIT = 600 # 等待人工登录(含验证码/选商家)超时
|
LOGIN_WAIT = 600 # 等待人工登录(含验证码/选商家)超时
|
||||||
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
|
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
|
||||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
SETTLE_WAIT = 8 # 进入后台后等首屏请求结束再确认状态
|
||||||
POLL_SECONDS = 2
|
POLL_SECONDS = 2
|
||||||
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
|
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
|
||||||
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
||||||
@@ -129,12 +181,14 @@ COMPANIES = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
_cur_company = 'a'
|
_cur_company = 'a'
|
||||||
COOKIE_FILE = ''
|
COOKIE_FILE = '' # 当前公司的 Cookie 落盘文件(set_company 时切换)
|
||||||
COOKIE_HEADER_FILE = ''
|
|
||||||
TOKEN_FILE = ''
|
|
||||||
META_FILE = ''
|
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 执行动作(三个独立分支,互不混跑) ====================
|
||||||
|
ACTION_DOWNLOAD = 'download' # 只导表:不做任何核对
|
||||||
|
ACTION_CHECK_SETTLEMENT = 'check_settlement' # 到账统计核对(新美大到账统计)
|
||||||
|
ACTIONS = (ACTION_DOWNLOAD, ACTION_CHECK_SETTLEMENT)
|
||||||
|
|
||||||
# ==================== 执行模式 ====================
|
# ==================== 执行模式 ====================
|
||||||
# export_only:仅导出(两家都导,不并台账、不更新核对统计);
|
# export_only:仅导出(两家都导,不并台账、不更新核对统计);
|
||||||
# full:含写表(只导 ledger=True 的金色印象,导出后并台账 + 更新核对统计)。
|
# full:含写表(只导 ledger=True 的金色印象,导出后并台账 + 更新核对统计)。
|
||||||
@@ -170,18 +224,16 @@ def companies_for_mode(mode, picks=None):
|
|||||||
|
|
||||||
|
|
||||||
def set_company(cid='a'):
|
def set_company(cid='a'):
|
||||||
"""切换当前档案(连带切换 cookie 落盘文件),返回生效的公司配置。
|
"""切换当前档案(连带切换 Cookie 落盘文件),返回生效的公司配置。
|
||||||
|
|
||||||
meituan_login 直接读 config.COOKIE_FILE 等模块属性,这里改全局即全局生效。
|
登录态优先由浏览器 profile 保存;COOKIE_FILE 是按公司分文件的备份,
|
||||||
|
profile 失效时注回浏览器再试一次。
|
||||||
"""
|
"""
|
||||||
global _cur_company, COOKIE_FILE, COOKIE_HEADER_FILE, TOKEN_FILE, META_FILE
|
global _cur_company, COOKIE_FILE
|
||||||
comp = get_company(cid)
|
comp = get_company(cid)
|
||||||
_cur_company = comp['id']
|
_cur_company = comp['id']
|
||||||
suffix = '' if comp['id'] == 'a' else f"_{comp['id']}"
|
suffix = '' if comp['id'] == 'a' else f"_{comp['id']}"
|
||||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, f'meituan_cookies{suffix}.json')
|
COOKIE_FILE = os.path.join(SESSIONS_DIR, f'meituan_cookies{suffix}.json')
|
||||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, f'meituan_cookies_header{suffix}.txt')
|
|
||||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, f'meituan_tokens{suffix}.json')
|
|
||||||
META_FILE = os.path.join(SESSIONS_DIR, f'meituan_session_meta{suffix}.json')
|
|
||||||
return comp
|
return comp
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""CRM 门店归属数据层:券号 → 内部门店 / 品牌。
|
||||||
|
|
||||||
|
为什么不按门店名匹配:美团门店名与内部门店名是两套口径(改名 / 错字 / 别名,
|
||||||
|
如「大渡口店」实际是「春晖路CEO会馆」),字符串匹配只能到 89%,剩下的必须人工。
|
||||||
|
**券号是订单级唯一关联**:CRM 团购核销记录里同一条数据就带 ``ticketCode`` +
|
||||||
|
``shopName`` + ``shopId``,与美团收益明细的「券号」join,实测命中 100%。
|
||||||
|
|
||||||
|
数据来自 ``crm_sdk``(执行机按插件 ``requires.sdks`` 下发挂载):
|
||||||
|
* 门店主数据:``stores.Catalog``(品牌 → 门店,含 OLD 旧店,按名称反查品牌)
|
||||||
|
* 核销明细:``reports.list_all(client, 'groupData', reportDate=日)``
|
||||||
|
|
||||||
|
SDK 未挂载 / CRM 未登录时**不阻断主流程**:返回 ``ok=False``,由调用方降级提示。
|
||||||
|
"""
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
|
def _sdk():
|
||||||
|
"""延迟 import,SDK 未挂载时返回 None(不抛,便于降级)。"""
|
||||||
|
try:
|
||||||
|
import crm_sdk # noqa: WPS433 - 运行时由执行机挂载
|
||||||
|
return crm_sdk
|
||||||
|
except ImportError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def available():
|
||||||
|
"""crm_sdk 是否可用(插件被单独拷贝/未下发 SDK 时为 False)。"""
|
||||||
|
return _sdk() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _day_range(days, window=None):
|
||||||
|
"""把日期集合按 ±N 天展开成待查日期列表(升序去重)。"""
|
||||||
|
window = config.CRM_DATE_WINDOW if window is None else int(window)
|
||||||
|
out = set()
|
||||||
|
for d in days or ():
|
||||||
|
base = _to_date(d)
|
||||||
|
if not base:
|
||||||
|
continue
|
||||||
|
for delta in range(-window, window + 1):
|
||||||
|
out.add((base + datetime.timedelta(days=delta)).isoformat())
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_date(value):
|
||||||
|
"""兼容 date / datetime / 'YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS'。"""
|
||||||
|
if isinstance(value, datetime.datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, datetime.date):
|
||||||
|
return value
|
||||||
|
text = str(value or '').strip()[:10]
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||||
|
try:
|
||||||
|
return datetime.datetime.strptime(text, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _client():
|
||||||
|
"""构建 CRM 客户端(登录态复用优先,失效时才走账号密码/扫码)。"""
|
||||||
|
sdk = _sdk()
|
||||||
|
if sdk is None:
|
||||||
|
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
|
||||||
|
login = sdk.auth.ensure_login(log=config.log)
|
||||||
|
if not login.get('success'):
|
||||||
|
return None, None, f"CRM 登录失败:{login.get('message') or '未知原因'}"
|
||||||
|
session = sdk.auth.build_session()
|
||||||
|
if session is None:
|
||||||
|
return None, None, 'CRM 登录态不可用(Cookie 缺失)'
|
||||||
|
return sdk, sdk.CrmClient(session, log=config.log), ''
|
||||||
|
|
||||||
|
|
||||||
|
def load(days, *, window=None, progress_from=0, progress_to=0):
|
||||||
|
"""拉取指定日期窗口内全部团购核销记录,建「券号 → 门店」索引。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
days: 美团收益明细里出现的验券日期(``date`` / ``str`` 均可)
|
||||||
|
window: 前后各多看几天(默认 :data:`config.CRM_DATE_WINDOW`)
|
||||||
|
progress_from / progress_to: 进度区间(0~100),逐日拉取时上报
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{"ok", "message", "tickets": {券号: {shop, shop_id, brand, date}},
|
||||||
|
"days": [...], "count": n}``
|
||||||
|
"""
|
||||||
|
empty = {'ok': False, 'message': '', 'tickets': {}, 'days': [], 'count': 0}
|
||||||
|
wanted = _day_range(days, window)
|
||||||
|
if not wanted:
|
||||||
|
empty['message'] = '收益明细里没有可解析的验券日期,跳过门店归属'
|
||||||
|
return empty
|
||||||
|
|
||||||
|
sdk, client, err = _client()
|
||||||
|
if err:
|
||||||
|
empty['message'] = err
|
||||||
|
return empty
|
||||||
|
|
||||||
|
# 门店主数据:品牌 → 门店(用于给 shopName 反查品牌 + 校验门店名是否在册)
|
||||||
|
try:
|
||||||
|
catalog = sdk.stores.Catalog.load(client)
|
||||||
|
except Exception as e: # noqa: BLE001 - 网络/权限异常降级
|
||||||
|
empty['message'] = f'拉取 CRM 门店树失败:{e}'
|
||||||
|
return empty
|
||||||
|
if not len(catalog):
|
||||||
|
# 接口对未认证/无授权账号返回 S0 + 空数组,不是 401,必须按失败处理
|
||||||
|
empty['message'] = 'CRM 门店树为空(登录态失效或无门店授权)'
|
||||||
|
return empty
|
||||||
|
config.log(f'CRM 门店主数据:{len(catalog)} 家 / 品牌 {"/".join(catalog.brands)}')
|
||||||
|
|
||||||
|
tickets = {}
|
||||||
|
total_days = len(wanted)
|
||||||
|
span = max(0, int(progress_to) - int(progress_from))
|
||||||
|
for idx, day in enumerate(wanted, 1):
|
||||||
|
try:
|
||||||
|
rows = sdk.reports.list_all(client, config.CRM_GROUP_REPORT,
|
||||||
|
reportDate=day, page_size=config.CRM_PAGE_SIZE)
|
||||||
|
except Exception as e: # noqa: BLE001 - 单日失败不影响整体
|
||||||
|
config.log(f'CRM {day} 团购核销取数失败(跳过):{e}', 'WARN')
|
||||||
|
continue
|
||||||
|
for row in rows or ():
|
||||||
|
code = str(row.get('ticketCode') or '').strip()
|
||||||
|
shop = str(row.get('shopName') or '').strip()
|
||||||
|
if not code or not shop:
|
||||||
|
continue
|
||||||
|
tickets[code] = {
|
||||||
|
'shop': shop,
|
||||||
|
'shop_id': str(row.get('shopId') or '').strip(),
|
||||||
|
'brand': catalog.brand_of(shop),
|
||||||
|
'date': day,
|
||||||
|
}
|
||||||
|
config.log(f'CRM {day}:{len(rows or [])} 行(累计券号 {len(tickets)})')
|
||||||
|
if span:
|
||||||
|
config.progress(int(progress_from + span * idx / total_days))
|
||||||
|
|
||||||
|
return {
|
||||||
|
'ok': bool(tickets),
|
||||||
|
'message': (f'CRM 券号 {len(tickets)} 条({wanted[0]}~{wanted[-1]})' if tickets
|
||||||
|
else f'{wanted[0]}~{wanted[-1]} 未取到 CRM 核销记录'),
|
||||||
|
'tickets': tickets,
|
||||||
|
'days': wanted,
|
||||||
|
'count': len(tickets),
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,190 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
||||||
|
|
||||||
|
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
|
||||||
|
|
||||||
|
源(共享盘,只读)
|
||||||
|
1111/TG/2026年11月/11.10/美团11.10.xlsx
|
||||||
|
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
||||||
|
目标(本地副本)
|
||||||
|
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
|
||||||
|
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
|
||||||
|
|
||||||
|
两张表复制到本地后,后续所有处理(明细贴表、报表写值)都只改本地副本。
|
||||||
|
|
||||||
|
要点:
|
||||||
|
|
||||||
|
* **按日期取表**:源文件优先按 ``{关键词}{月}.{日}.xlsx`` 精确匹配;
|
||||||
|
匹配不到再在该日目录里取关键词命中的唯一 xlsx(人工临时改过名的场景);
|
||||||
|
* **跨月自动回退**:1 号的「昨天」在上个月的目录,月份目录按源日期算;
|
||||||
|
* **幂等**:本地目标已存在且非空就跳过,重复运行不会覆盖当天已处理的数据;
|
||||||
|
* **不依赖第三方库**:UNC 路径用标准库只读打开 + 本地写入,缺少凭据时给出提示。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_day(value):
|
||||||
|
"""``date`` / ``datetime`` / 'YYYY-MM-DD' 统一成 date;无法解析返回 None。"""
|
||||||
|
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 month_dir(root, day):
|
||||||
|
"""月份目录:``2026年11月``。"""
|
||||||
|
return os.path.join(root, f'{day.year}年{day.month}月')
|
||||||
|
|
||||||
|
|
||||||
|
def day_dir(root, day):
|
||||||
|
"""日期目录:``11.10``(不补零,与共享盘现有命名一致)。"""
|
||||||
|
return os.path.join(month_dir(root, day), f'{day.month}.{day.day}')
|
||||||
|
|
||||||
|
|
||||||
|
def table_name(keyword, day, ext):
|
||||||
|
"""核对表文件名:``美团11.10.xlsx``。"""
|
||||||
|
return f'{keyword}{day.month}.{day.day}{ext}'
|
||||||
|
|
||||||
|
|
||||||
|
def _list_tables(folder, keyword, ext):
|
||||||
|
"""列出目录里关键词 + 后缀命中的 xlsx(排除 Excel 临时文件 ``~$``)。"""
|
||||||
|
try:
|
||||||
|
names = os.listdir(folder)
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
for name in names:
|
||||||
|
low = name.lower()
|
||||||
|
if name.startswith('~$') or not low.endswith(ext.lower()):
|
||||||
|
continue
|
||||||
|
if keyword and keyword not in name:
|
||||||
|
continue
|
||||||
|
out.append(name)
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_source(folder, keyword, prev_day, ext):
|
||||||
|
"""在昨天目录里挑源文件:先精确日期,再退化为目录内唯一命中的表。"""
|
||||||
|
exact = os.path.join(folder, table_name(keyword, prev_day, ext))
|
||||||
|
if os.path.isfile(exact):
|
||||||
|
return exact
|
||||||
|
candidates = _list_tables(folder, keyword, ext)
|
||||||
|
if len(candidates) == 1:
|
||||||
|
return os.path.join(folder, candidates[0])
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
|
||||||
|
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
||||||
|
keyword: 文件名关键词(默认 :data:`config.SHARE_TABLE_KEYWORD`,如「美团」)
|
||||||
|
ext: 后缀(默认 :data:`config.SHARE_TABLE_EXT`)
|
||||||
|
day: 目标日期(默认今天)
|
||||||
|
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``,共享盘只读不写入)
|
||||||
|
dry_run: 只检查不复制
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{"ok", "message", "src", "dst", "skipped"}``
|
||||||
|
"""
|
||||||
|
root = str(share_root or config.SHARE_CHECK_ROOT).strip().strip('"').rstrip('\\/')
|
||||||
|
kw = str(keyword or config.SHARE_TABLE_KEYWORD).strip()
|
||||||
|
suffix = str(ext or config.SHARE_TABLE_EXT).strip()
|
||||||
|
if suffix and not suffix.startswith('.'):
|
||||||
|
suffix = '.' + suffix
|
||||||
|
target = _parse_day(day) or date.today()
|
||||||
|
prev = target - timedelta(days=1)
|
||||||
|
|
||||||
|
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
|
||||||
|
dst_dir = str(local_dir or os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR))
|
||||||
|
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
|
||||||
|
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
|
||||||
|
|
||||||
|
if not src_path:
|
||||||
|
folder = day_dir(root, prev)
|
||||||
|
found = _list_tables(folder, kw, suffix)
|
||||||
|
result['message'] = (
|
||||||
|
f'共享盘 {folder} 下没有找到 {kw}*{suffix}'
|
||||||
|
+ (f'(现有:{"、".join(found)})' if found else
|
||||||
|
';若共享盘未连接,请先确认当前机器能访问 ' + root))
|
||||||
|
return result
|
||||||
|
|
||||||
|
if os.path.isfile(dst_path) and os.path.getsize(dst_path) > 0:
|
||||||
|
result.update(ok=True, skipped=True,
|
||||||
|
message=f'本地副本已存在,跳过复制:'
|
||||||
|
f'{os.path.basename(dst_path)}')
|
||||||
|
return result
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → '
|
||||||
|
f'{dst_path}')
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.makedirs(dst_dir, exist_ok=True)
|
||||||
|
shutil.copy2(src_path, dst_path)
|
||||||
|
except OSError as e:
|
||||||
|
tip = ''
|
||||||
|
if getattr(e, 'winerror', None) in (53, 67, 64, 1219, 1326):
|
||||||
|
tip = '(共享盘网络路径不可达 / 缺少凭据,请确认本机已能访问该共享)'
|
||||||
|
result['message'] = f'复制失败:{e}{tip}'
|
||||||
|
return result
|
||||||
|
|
||||||
|
if not os.path.isfile(dst_path) or os.path.getsize(dst_path) == 0:
|
||||||
|
result['message'] = f'复制后本地副本缺失或为空:{dst_path}'
|
||||||
|
return result
|
||||||
|
|
||||||
|
result.update(ok=True, message=f'已从共享盘复制 {os.path.basename(src_path)} → '
|
||||||
|
f'本地 {os.path.basename(dst_path)}')
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def copy_prev_tables(share_root='', day=None, local_dir='', dry_run=False):
|
||||||
|
"""把昨天的核对表 + 马敏团购总表一起拉到本地副本(共享盘只读)。
|
||||||
|
|
||||||
|
源文件在共享盘 ``{share_root}/{年}月/{月}.{日}/``,本地目标在 ``WORK_DIR/_work/``:
|
||||||
|
|
||||||
|
* 核对表:``美团11.10.xlsx`` → 本地 ``美团11.11.xlsx``
|
||||||
|
* 共享总表:``马敏团购总表11.10.xlsx`` → 本地 ``马敏团购总表11.11.xlsx``
|
||||||
|
|
||||||
|
Args:
|
||||||
|
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
||||||
|
day: 目标日期(默认今天;传「核对营业日」时按指定日期)
|
||||||
|
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``)
|
||||||
|
dry_run: 只检查不复制
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{"ok", "message", "tables": [...], "copied", "skipped", "failed"}``
|
||||||
|
"""
|
||||||
|
jobs = (
|
||||||
|
('核对表', config.SHARE_TABLE_KEYWORD, config.SHARE_TABLE_EXT),
|
||||||
|
('共享总表', config.LINK_BOOK, config.SHARE_TABLE_EXT),
|
||||||
|
)
|
||||||
|
tables = []
|
||||||
|
for label, keyword, ext in jobs:
|
||||||
|
item = copy_prev_table(share_root=share_root, keyword=keyword, ext=ext,
|
||||||
|
day=day, local_dir=local_dir, dry_run=dry_run)
|
||||||
|
item['label'] = label
|
||||||
|
tables.append(item)
|
||||||
|
|
||||||
|
failed = [t for t in tables if not t.get('ok')]
|
||||||
|
return {
|
||||||
|
'ok': not failed,
|
||||||
|
'message': ';'.join(f'{t["label"]}:{t["message"]}' for t in tables),
|
||||||
|
'tables': tables,
|
||||||
|
'copied': sum(1 for t in tables if t.get('ok') and not t.get('skipped')),
|
||||||
|
'skipped': sum(1 for t in tables if t.get('skipped')),
|
||||||
|
'failed': len(failed),
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# -*- 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}
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"id": "xq0041",
|
"id": "xq0041",
|
||||||
"name": "新美大平台核对",
|
"name": "新美大平台核对",
|
||||||
"version": "1.3.11",
|
"version": "1.3.13",
|
||||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并按日期把核对统计表整行同源取数公式([n]资金组取数!$B$xx,实测 V/W/Y/Z)换成当天共享总表的链接。界面可配经营宝账号密码自动填好并勾选用户协议,登录页右上角浮层提示你去点「登录」(登录按钮、滑块/短信验证码、选门店仍由人工完成),登录一次后可长期复用。执行模式分「含写表」(只导金色印象 + 并台账 + 更新核对统计)与「仅导出」(金色印象 / 金色湖畔按需勾选,可只导一家,不写表);两家各自独立浏览器档案与调试端口(xq0041 / xq0041_b、9222 / 9333),登录态互不干扰,避免同浏览器反复切号触发风控,金色湖畔报表文件名带「金色湖畔_」前缀。",
|
"description": "美团数据导出与到账统计核对,两个独立动作:download=只导表(下载打款记录/团购/预订收益明细);check_settlement=到账统计核对(新美大到账统计:并入台账 → 门店归属 → 更新核对统计)。美团核对与抖音核对已迁到 XQ0085 团购数据核对插件。界面可配经营宝账号密码自动填好,登录/验证码/选商家由人工完成;金色印象与金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b、9222 / 9333),登录态互不干扰,金色湖畔报表文件名带「金色湖畔_」前缀。",
|
||||||
"category": "财务",
|
"category": "财务",
|
||||||
"icon": "",
|
"icon": "",
|
||||||
"platform": "",
|
"platform": "",
|
||||||
@@ -12,6 +12,13 @@
|
|||||||
"capabilities": [
|
"capabilities": [
|
||||||
"xq0041"
|
"xq0041"
|
||||||
],
|
],
|
||||||
|
"requires": {
|
||||||
|
"sdks": {
|
||||||
|
"crm_sdk": {
|
||||||
|
"compat": "^0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"platforms": []
|
"platforms": []
|
||||||
},
|
},
|
||||||
@@ -22,7 +29,7 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "金色印象-经营宝账号",
|
"title": "金色印象-经营宝账号",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "金色印象的美团经营宝账号(手机号/账号)。与密码一起填写后自动登录;留空=手工登录"
|
"description": "金色印象的美团经营宝账号(手机号/账号)。与密码一起填写后自动填进登录页,登录/验证码仍由人工完成;留空=手工登录"
|
||||||
},
|
},
|
||||||
"mt_password": {
|
"mt_password": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -68,26 +75,19 @@
|
|||||||
},
|
},
|
||||||
"action": {
|
"action": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "执行过程",
|
"title": "执行动作",
|
||||||
"default": "all",
|
"default": "check_settlement",
|
||||||
"enum": [
|
"enum": [
|
||||||
"all",
|
|
||||||
"download",
|
"download",
|
||||||
"reconcile"
|
"check_settlement"
|
||||||
],
|
],
|
||||||
"description": "all=下载后核对;download=只下载;reconcile=只核对(不下载)"
|
"description": "download=只导表;check_settlement=到账统计核对(新美大到账统计:并台账/门店归属/更新核对统计)。美团核对/抖音核对请用 XQ0085 团购数据核对"
|
||||||
},
|
},
|
||||||
"do_download": {
|
"download_before": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "下载数据",
|
"title": "核对前先下载(不选则用本机已有表)",
|
||||||
"default": true,
|
"default": false,
|
||||||
"description": "登录经营宝,把账单下载到本机目录"
|
"description": "勾了先导表再核对;不勾则直接读本机已有表,核对前只校验必需文件是否存在,缺了会提示先执行「只导表」"
|
||||||
},
|
|
||||||
"do_reconcile": {
|
|
||||||
"type": "boolean",
|
|
||||||
"title": "更新核对",
|
|
||||||
"default": true,
|
|
||||||
"description": "读本机最新的台账与收益明细,并入台账并更新核对统计,不重新下载"
|
|
||||||
},
|
},
|
||||||
"pay_enabled": {
|
"pay_enabled": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
@@ -149,6 +149,12 @@
|
|||||||
"default": true,
|
"default": true,
|
||||||
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
||||||
},
|
},
|
||||||
|
"run_store_map": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "门店归属(CRM 券号)",
|
||||||
|
"default": true,
|
||||||
|
"description": "用 CRM 团购核销的券号把美团「消费门店」翻译成内部门店 + 品牌,输出「门店核对_起_止.xlsx」(门店映射 / 门店汇总 / 未匹配)与累积映射表;不改动台账。CRM 未登录时只告警跳过"
|
||||||
|
},
|
||||||
"run_links": {
|
"run_links": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "更新核对统计",
|
"title": "更新核对统计",
|
||||||
|
|||||||
@@ -90,8 +90,9 @@
|
|||||||
两家是平台上的两个主体,各用一套登录:金色印象档案 <b>xq0041</b> / 端口 9222,
|
两家是平台上的两个主体,各用一套登录:金色印象档案 <b>xq0041</b> / 端口 9222,
|
||||||
金色湖畔档案 <b>xq0041_b</b> / 端口 9333,Cookie 分开落盘,不会出现同一浏览器反复切号。<br>
|
金色湖畔档案 <b>xq0041_b</b> / 端口 9333,Cookie 分开落盘,不会出现同一浏览器反复切号。<br>
|
||||||
</template>
|
</template>
|
||||||
账号密码都填:脚本自动填好账号密码并勾选用户协议,然后在浏览器右上角弹一条橙色提示。
|
账号密码都填:脚本只把账号密码填进登录页,然后在浏览器右上角弹一条橙色提示。
|
||||||
<b>「登录」按钮、滑块 / 短信验证码、选门店都由你在浏览器里点</b>,脚本只等结果。
|
<b>「登录」按钮、滑块 / 短信验证码、选门店、选商家版本都由你在浏览器里点</b>,脚本只等结果。
|
||||||
|
登录成功后 Cookie 按公司分文件落盘,下次优先复用浏览器档案,档案失效时再注回 Cookie 备份。
|
||||||
都留空:完全手工登录(密码不会出现在「恢复上次参数」里)。
|
都留空:完全手工登录(密码不会出现在「恢复上次参数」里)。
|
||||||
</div>
|
</div>
|
||||||
</el-form>
|
</el-form>
|
||||||
@@ -255,11 +256,12 @@
|
|||||||
<details class="help">
|
<details class="help">
|
||||||
<summary><span>流程说明与口径</span><span class="h-arrow">▾</span></summary>
|
<summary><span>流程说明与口径</span><span class="h-arrow">▾</span></summary>
|
||||||
<div class="help-body">
|
<div class="help-body">
|
||||||
<div class="hb-line"><b>① 登录</b>:打开经营宝(ecom.meituan.com),配了账号密码就先自动填好
|
<div class="hb-line"><b>① 登录</b>:打开经营宝(ecom.meituan.com),配了账号密码就只把账号密码
|
||||||
<b>并勾选用户协议</b>,浏览器右上角浮层会提示你点「登录」;登录按钮、滑块 / 短信验证码与
|
<b>填进登录表单</b>(不勾协议、不点登录),浏览器右上角浮层会提示你完成登录;登录按钮、
|
||||||
「选商家」全部交人工。进后台后浮层自动消失,Cookies 落盘到
|
滑块 / 短信验证码、「选商家」与「选商家版本」全部交人工。进后台后浮层自动消失,
|
||||||
<b>%LOCALAPPDATA%\37duAutomation\.sessions\meituan_*</b>,浏览器档案在
|
Cookies 按公司分文件落盘到
|
||||||
<b>browser_sessions\xq0041</b>,下次直接复用,过期才会再要求登录。<br>
|
<b>%LOCALAPPDATA%\37duAutomation\.sessions\meituan_cookies*.json</b>,浏览器档案在
|
||||||
|
<b>browser_sessions\xq0041</b>,下次先复用档案,档案失效再注回 Cookie 备份,仍失效才要求登录。<br>
|
||||||
<b>两家公司</b>:金色印象档案 <b>xq0041</b> / 端口 <b>9222</b>,金色湖畔档案 <b>xq0041_b</b> /
|
<b>两家公司</b>:金色印象档案 <b>xq0041</b> / 端口 <b>9222</b>,金色湖畔档案 <b>xq0041_b</b> /
|
||||||
端口 <b>9333</b>,Cookie 分开落盘,登录态互不覆盖,不会出现「同一浏览器反复切号」的高风控特征。<br>
|
端口 <b>9333</b>,Cookie 分开落盘,登录态互不覆盖,不会出现「同一浏览器反复切号」的高风控特征。<br>
|
||||||
<b>执行模式</b>:「仅导出」两家都导(湖畔文件名带「金色湖畔_」前缀,不写表);
|
<b>执行模式</b>:「仅导出」两家都导(湖畔文件名带「金色湖畔_」前缀,不写表);
|
||||||
@@ -366,7 +368,7 @@ const {
|
|||||||
const user = (form.mt_username || '').trim()
|
const user = (form.mt_username || '').trim()
|
||||||
const pwd = (form.mt_password || '').trim()
|
const pwd = (form.mt_password || '').trim()
|
||||||
if (form.do_download && (user || pwd) && !(user && pwd)) {
|
if (form.do_download && (user || pwd) && !(user && pwd)) {
|
||||||
ElMessage.warning('账号和密码要么都填(自动登录),要么都留空(手工登录)')
|
ElMessage.warning('账号和密码要么都填(自动填写),要么都留空(手工登录)')
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if (form.run_mode === 'export_only') {
|
if (form.run_mode === 'export_only') {
|
||||||
@@ -381,7 +383,7 @@ const {
|
|||||||
const u2 = (form.mt2_username || '').trim()
|
const u2 = (form.mt2_username || '').trim()
|
||||||
const p2 = (form.mt2_password || '').trim()
|
const p2 = (form.mt2_password || '').trim()
|
||||||
if (exportB.value && (u2 || p2) && !(u2 && p2)) {
|
if (exportB.value && (u2 || p2) && !(u2 && p2)) {
|
||||||
ElMessage.warning('金色湖畔的账号和密码要么都填(自动登录),要么都留空(手工登录)')
|
ElMessage.warning('金色湖畔的账号和密码要么都填(自动填写),要么都留空(手工登录)')
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>新美大平台核对</title>
|
<title>新美大平台核对</title>
|
||||||
<script type="module" crossorigin src="/pui/xq0041/assets/index-BcCXU4Vw.js"></script>
|
<script type="module" crossorigin src="/pui/xq0041/assets/index-DELRgOsV.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-BVdn0lhW.css">
|
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-Xqpz4Bby.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>␍
|
<div id="app"></div>␍
|
||||||
|
|||||||
Reference in New Issue
Block a user