Files
37duAutomation/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/douyin_daily.py
T

257 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""抖音核对:核销明细 → 四口径预计收入合计 + 报表 O/P 基础信息补维护。
步骤(对应需求):
1. 本地副本 ``抖音M.D.xlsx``(由 share_copy 从共享盘只读复制而来);
2. 导出的「核销明细」A~BR 按值贴进【核销明细】,旧数据区清空重贴;
3. 筛 BS(核销时间)=营业日、I(核销状态)=已核销,AF(预计收入转数字) 合计 → 明细口径;
4. 【透视】K 列、【报表】Y 列、【转换】(BQ=营业日 & I=已核销) AE 列合计 → 另三口径;
5. 四个合计需一致(不等则 WARN,不擅自改公式/透视缓存);
6. 【报表】O/P 列乱码 → 新增门店/项目补进【基础信息】(只加检查与写入本地副本)。
与美团侧一致:openpyxl 读值、zip+XML 写值(保留透视/公式),共享盘全程只读。
"""
import os
import re
from datetime import date, datetime, timedelta
import openpyxl
from openpyxl.utils import column_index_from_string as col
from openpyxl.utils import get_column_letter as letter
from .. import config
from . import base_info_sync, com_refresh, share_copy
def _as_date(value):
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value or '').strip()
m = re.match(r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})', text)
if m:
try:
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
except ValueError:
pass
return None
def _to_number(value):
if value is None or value == '':
return 0.0
if isinstance(value, bool):
return 0.0
if isinstance(value, (int, float)):
return float(value)
text = str(value).replace(',', '').replace('¥', '').replace('%', '').strip()
if not text:
return 0.0
try:
return float(text)
except ValueError:
return 0.0 # 透视/报表里混着表头文本,按 0 算
def _col(s):
return col(str(s).strip().upper())
def _read_export_detail(path):
"""导出核销明细:表头第 DY_HEADER_ROW 行,取 A~BR 列,全量数据。"""
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
try:
ws = wb[wb.sheetnames[0]]
# 平台导出的 dimension 可能写成 1×1(实测 11 月版本),read_only 下会读到 0 行
if (ws.max_row or 1) <= 1 or (ws.max_column or 1) <= 1:
ws.reset_dimensions()
hi = _col(config.DY_DETAIL_PASTE_LAST_COL)
rows = [list(r) for r in ws.iter_rows(min_row=config.DY_HEADER_ROW + 1,
min_col=1, max_col=hi, values_only=True)]
while rows and all(v is None for v in rows[-1]):
rows.pop()
return rows
finally:
wb.close()
def _local_table(day):
return os.path.join(config.WORK_DIR,
share_copy.table_name(config.DOUYIN_SHARE_KEYWORD, day,
config.SHARE_TABLE_EXT))
def _match_day(value, target):
"""BS/BQ 这类辅助列存的是「日号数字」,不是日期;两种都要能对上营业日。"""
if isinstance(value, bool):
return False
if isinstance(value, (int, float)):
return int(value) == target.day
return _as_date(value) == target
def _sum_filtered(ws, time_col, status_col, income_col, target):
"""按 时间=营业日 & 状态=已核销 过滤,累计预计收入(转数字)。"""
t, s, i = _col(time_col), _col(status_col), _col(income_col)
total = 0.0
count = 0
for r in range(config.DY_DETAIL_DATA_START, int(ws.max_row or 0) + 1):
if not _match_day(ws.cell(r, t).value, target):
continue
if str(ws.cell(r, s).value or '').strip() != config.DY_STATUS_VALUE:
continue
total += _to_number(ws.cell(r, i).value)
count += 1
return round(total, 2), count
def _sum_column(ws, income_col, start_row=2):
i = _col(income_col)
total = 0.0
for r in range(start_row, int(ws.max_row or 0) + 1):
total += _to_number(ws.cell(r, i).value)
return round(total, 2)
def _sheet_visible_rows(ws, col_letter, start_row=2):
"""透视类 sheet:按指定列非空统计(不真正刷新缓存,只复算可见行)。"""
c = _col(col_letter)
return [r for r in range(start_row, int(ws.max_row or 0) + 1)
if ws.cell(r, c).value is not None]
def _write_detail_values(table_path, rows):
"""按值重贴【核销明细】A~BR(zip+XML),返回写入函数供复用。"""
from .paste_to_master import _sheet_xml_path, _patch_sheet_xml, _write_master
# 直接复用 paste_to_master 的写盘入口(单 sheet、起始行 2)
return _write_master(table_path,
[('核销明细', rows, 1, config.DY_DETAIL_DATA_START)])
def _base_info_layout():
return base_info_sync.layout(base_info_sync.LAYOUT_DOUYIN)
def _base_info_scan(workbook):
"""【报表】A/B 与【基础信息】A/E 比对(与美团同一套逻辑),只读不写。
``workbook`` 必须是 data_only 打开的,否则报表读到的是 VLOOKUP 公式文本。
"""
return base_info_sync.scan(workbook, _base_info_layout())
def run(day=None, dry_run=False, use_com=None):
target = _as_date(day) or date.today()
result = {'ok': False, 'message': '', 'path': '', 'day': target.isoformat(),
'detail_rows': 0, 'detail_total': 0.0, 'pivot_total': 0.0,
'report_total': 0.0, 'convert_total': 0.0, 'consistent': False,
'base_info': None}
table = _local_table(target)
if not os.path.isfile(table):
result['message'] = f'未找到本地抖音核对表副本:{table}(请先从共享盘复制)'
return result
# 核销明细导出优先找抖音分支目录,其次过程表
export = config.latest_file(config.DOUYIN_DETAIL_GLOB)
if not export:
result['message'] = f'未找到导出的核销明细({config.DOUYIN_DETAIL_GLOB})'
return result
rows = _read_export_detail(export)
if not rows:
result['message'] = f'核销明细导出为空:{export}'
return result
wb = openpyxl.load_workbook(table, data_only=True)
try:
if '核销明细' not in wb.sheetnames:
result['message'] = f'{os.path.basename(table)} 缺少【核销明细】'
return result
detail_ws = wb['核销明细']
detail_total, detail_count = _sum_filtered(
detail_ws, config.DY_DETAIL_TIME_COL, config.DY_DETAIL_STATUS_COL,
config.DY_DETAIL_INCOME_COL, target)
pivot_total = 0.0
if config.DY_PIVOT_SHEET in wb.sheetnames:
pivot_total = _sum_column(wb[config.DY_PIVOT_SHEET], config.DY_PIVOT_INCOME_COL)
report_total = 0.0
if config.REPORT_SHEET in wb.sheetnames:
report_total = _sum_column(wb[config.REPORT_SHEET], config.DY_REPORT_INCOME_COL)
convert_total = 0.0
if config.DY_CONVERT_SHEET in wb.sheetnames:
convert_total, _ = _sum_filtered(
wb[config.DY_CONVERT_SHEET], config.DY_CONVERT_TIME_COL,
config.DY_DETAIL_STATUS_COL, config.DY_CONVERT_INCOME_COL, target)
totals = (detail_total, pivot_total, report_total, convert_total)
consistent = max(totals) - min(totals) < 0.01
result.update(detail_rows=len(rows), detail_total=detail_total,
pivot_total=pivot_total, report_total=report_total,
convert_total=convert_total, consistent=consistent)
base_info = _base_info_scan(wb)
result['base_info'] = base_info
if dry_run:
result.update(ok=True,
message=f'[演练] 核销明细 {len(rows)} 行;四口径 '
f'{detail_total}/{pivot_total}/{report_total}/{convert_total}'
+ ('' if consistent else '(不一致)'))
return result
_write_detail_values(table, rows)
# 基础信息写入需要可保存的 workbook;zip+XML 不影响,单独用 openpyxl 追加。
# 直接复用扫描结果,不再重读报表(重读会拿到公式文本,曾把 A 列写坏)。
if base_info.get('ok') and (base_info['new_shops'] or base_info['new_items']):
changed = base_info_sync.write_changes(table, base_info, _base_info_layout())
base_info['written'] = changed
# 保存后真正刷新透视缓存 + 公式,再从缓存读四口径
do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com)
refresh = com_refresh.refresh(table, sheets=[config.DY_PIVOT_SHEET,
config.REPORT_SHEET,
config.DY_CONVERT_SHEET]) if do_com else \
{'ok': False, 'engine': '', 'message': '未启用 COM 刷新'}
result['com_refresh'] = refresh
if refresh.get('ok'):
try:
wb3 = openpyxl.load_workbook(table, data_only=True)
try:
detail_total, _ = _sum_filtered(
wb3['核销明细'], config.DY_DETAIL_TIME_COL,
config.DY_DETAIL_STATUS_COL, config.DY_DETAIL_INCOME_COL, target)
pivot_total = _sum_column(wb3[config.DY_PIVOT_SHEET],
config.DY_PIVOT_INCOME_COL)
report_total = _sum_column(wb3[config.REPORT_SHEET],
config.DY_REPORT_INCOME_COL)
convert_total, _ = _sum_filtered(
wb3[config.DY_CONVERT_SHEET], config.DY_CONVERT_TIME_COL,
config.DY_DETAIL_STATUS_COL, config.DY_CONVERT_INCOME_COL, target)
finally:
wb3.close()
except Exception as e:
config.log(f'COM 刷新后读四口径失败,沿用旧值:{e}', 'WARN')
elif do_com:
config.log(f'抖音透视未刷新({refresh.get("message")}),四口径为旧缓存/复算值', 'WARN')
totals = (detail_total, pivot_total, report_total, convert_total)
consistent = max(totals) - min(totals) < 0.01
result.update(ok=True, path=table, detail_total=detail_total,
pivot_total=pivot_total, report_total=report_total,
convert_total=convert_total, consistent=consistent,
message=f'核销明细已贴 {len(rows)} 行;四口径 '
f'{detail_total:.2f}/{pivot_total:.2f}/'
f'{report_total:.2f}/{convert_total:.2f}'
+ ('' if consistent else '(不一致!)'))
if not consistent:
config.log('抖音四口径合计不一致,请检查透视缓存 / 报表公式 / 转换表', 'WARN')
return result
finally:
try:
wb.close()
except Exception:
pass