# -*- coding: utf-8 -*-
"""台账增量合并:把「核销明细」里比台账更新的行追加到「金色印象--抖音」。
财务口径(2026-10 确认,参考 xq0041 新美大):
1. 台账取同目录 `抖音到账统计YYYY.M月.xlsx` 里**月份最新**的一份(排除 `_备份*`);
2. 取该 sheet「核销时间」列的**最大时间**;
3. 核销明细(可一次多份,`核销明细-核销时间-起_止.xlsx`)里比该时间旧的行剔除,
其余按**表头同名**对齐追加(明细比台账多的列忽略,台账独有的列留空);
4. 写入起点 = **真实数据末行 + 1**(max_row 被尾部空公式行撑大,直接用会在中间留空行),
尾部既有空公式行先清掉,避免与新数据交错;
5. 公式列按模板行(真实末行)下拉:A 列 `=M*1`、BT~CA 核对区
(内联公式按行号平移;共享公式 `` 先按 si 找主定义再平移,
效果等同手工双击右下角);**CC 列业务不管,不写**。
写入方式:只改目标 sheet 的 XML(清尾部空行、`` 前插行、更新 dimension),
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 4 个外部链接,openpyxl 全量 load→save 会丢
透视表,且目标 sheet 解压后 314MB、网表尾部还有 1.4 万行空公式行。
"""
import glob
import os
import re
import shutil
import time
import zipfile
from datetime import date, datetime
from openpyxl import load_workbook
from openpyxl.reader.strings import read_string_table
from .zipio import open_zip
from .. import config
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
_ROW_RE = re.compile(rb']*?(?:/>|>(.*?)
)', re.S)
_CELL_RE = re.compile(rb']*?)(?:/>|>(.*?))', re.S)
_V_RE = re.compile(rb'([^<]*)')
_F_RE = re.compile(rb']*?)(?:/>|>(.*?))', re.S)
_IS_T_RE = re.compile(rb']*>(.*?)', re.S)
_NUM_RE = re.compile(r'-?\d+(?:\.\d+)?')
_SI_RE = re.compile(rb'si="(\d+)"')
# ==================== 通用小工具 ====================
def _to_dt(v):
if v is None:
return None
if isinstance(v, datetime):
return v
if isinstance(v, date):
return datetime(v.year, v.month, v.day)
s = str(v).strip()
if not s:
return None
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:
return datetime.strptime(s, fmt)
except ValueError:
continue
return None
def _month_key(path):
m = _MONTH_RE.search(os.path.basename(path))
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
def _pick_latest(pattern, by_month=True, root=None):
"""排除备份文件与临时文件(`_备份20261029_145157.xlsx` 同样匹配 glob)。"""
files = [p for p in glob.glob(os.path.join(root or config.WORK_DIR, pattern))
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
if not files:
return None
if by_month:
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
else:
files.sort(key=os.path.getmtime)
return files[-1]
def _col_letter(n):
s = ''
while n > 0:
n, r = divmod(n - 1, 26)
s = chr(65 + r) + s
return s
def _col_num(letters):
n = 0
for ch in letters:
n = n * 26 + (ord(ch) - 64)
return n
def _skip_cols():
return {_col_num(c) for c in config.FORMULA_SKIP_COLS}
def _xml_text(v):
return (str(v).replace('&', '&').replace('<', '<')
.replace('>', '>').replace('"', '"'))
def _num_text(v):
"""能当数字写就返回数字文本,否则 None(金额列写成数值,避免整列变文本)。"""
if v is None or isinstance(v, bool):
return None
if isinstance(v, (int, float)):
f = float(v)
else:
s = str(v).strip().replace(',', '')
if not _NUM_RE.fullmatch(s):
return None
f = float(s)
if f.is_integer() and abs(f) < 1e15:
return str(int(f))
return repr(round(f, 10))
# ==================== 台账读取(流式,不整体加载) ====================
def _sheet_xml_path(zf, sheet_name):
import xml.etree.ElementTree as ET
root = ET.fromstring(zf.read('xl/workbook.xml'))
rid = None
for s in root.iter(f'{_NS_MAIN}sheet'):
if s.get('name') == sheet_name:
rid = s.get(f'{_NS_REL}id')
break
if not rid:
return None
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
if rel.get('Id') == rid:
t = (rel.get('Target') or '').lstrip('/')
return t if t.startswith('xl/') else 'xl/' + t
return None
def _cell_map(inner):
out = {}
for m in _CELL_RE.finditer(inner):
out[m.group(1)] = (m.group(3), m.group(4) or b'')
return out
def _cell_text(attrs, body, strings):
if b't="inlineStr"' in attrs:
tm = _IS_T_RE.search(body)
return tm.group(1).decode('utf-8', 'replace') if tm else None
vm = _V_RE.search(body)
if not vm:
return None
raw = vm.group(1)
if b't="s"' in attrs:
try:
idx = int(raw)
except ValueError:
return None
return strings[idx] if 0 <= idx < len(strings) else None
return raw.decode('utf-8', 'replace')
def _is_num(attrs, body):
if b't=' in attrs:
return False
return b'' in body
def _scan_ledger(path, sheet_name):
"""扫台账:表头、真实末行、时间列最大值、末行模板样式、分母/分子类型。"""
zf = open_zip(path)
try:
sheet_path = _sheet_xml_path(zf, sheet_name)
if not sheet_path:
return {'ok': False, 'message': f'台账里找不到 sheet「{sheet_name}」'}
try:
strings = read_string_table(zf.open('xl/sharedStrings.xml'))
except KeyError:
strings = []
header, last_data_row = {}, config.HEADER_ROW
max_dt, max_keys = None, set()
tpl_cells, tpl_row_no = {}, 0
type_rows, shared = [], {}
with zf.open(sheet_path) as f:
buf = b''
while True:
chunk = f.read(4 << 20)
if not chunk and not buf:
break
buf += chunk
pos = 0
while True:
m = _ROW_RE.search(buf, pos)
if not m:
break
pos = m.end()
r = int(m.group(1))
inner = m.group(2) or b''
cells = _cell_map(inner)
# 共享公式主定义:只有主定义带公式文本,其余是自闭合引用
if b't="shared"' in inner:
for letter, (attrs, body) in cells.items():
fm = _F_RE.search(body)
if not fm or not fm.group(2) or b't="shared"' not in fm.group(1):
continue
sm = _SI_RE.search(fm.group(1))
if sm:
shared[sm.group(1).decode()] = (
r, fm.group(2).decode('utf-8', 'replace'))
if r == config.HEADER_ROW:
for letter, (attrs, body) in cells.items():
name = _cell_text(attrs, body, strings)
if name and str(name).strip():
header.setdefault(str(name).strip(),
_col_num(letter.decode()))
continue
if r < config.DATA_START_ROW:
continue
keys = []
for col in (b'B', b'F', b'M'):
cell = cells.get(col)
keys.append(_cell_text(cell[0], cell[1], strings) if cell else None)
if not any(k for k in keys):
continue # 尾部只剩公式的空行
last_data_row = r
tpl_cells = _tpl_from_cells(cells)
tpl_row_no = r
types = {}
for letter, (attrs, body) in cells.items():
if b' config.NUM_TYPE_SAMPLE:
type_rows.pop(0)
dt = _to_dt(keys[2])
if dt is not None:
key = (keys[0] or '', keys[1] or '', keys[2] or '')
if max_dt is None or dt > max_dt:
max_dt, max_keys = dt, {key}
elif dt == max_dt:
max_keys.add(key)
buf = buf[pos:]
if not chunk:
break
# 数值列判定:末 N 行里数字出现次数多于文本才算(金额列写数值,其余照旧写文本)
num_cols = set()
counts = {}
for row in type_rows:
for letter, kind in row.items():
c = counts.setdefault(letter, [0, 0])
c[0 if kind == 'num' else 1] += 1
for letter, (num_cnt, txt_cnt) in counts.items():
if num_cnt > txt_cnt:
num_cols.add(_col_num(letter.decode()))
return {'ok': True, 'header': header, 'last_data_row': last_data_row,
'max_dt': max_dt, 'max_keys': max_keys, 'tpl': tpl_cells,
'tpl_row': tpl_row_no, 'num_cols': num_cols, 'shared': shared,
'max_row': _max_row(zf, sheet_path)}
finally:
zf.close()
def _max_row(zf, sheet_path):
"""dimension 里的最大行号(尾部空公式行也算)。"""
head = zf.open(sheet_path).read(4096)
m = re.search(rb'{num}'))
continue
cells.append((lcol, f''
f'{_xml_text(raw)}'))
for letter, info in tpl.items():
cnum = _col_num(letter)
if cnum in val_cols or cnum in skip_cols:
continue
formula = None
if info.get('f'):
formula = _shift_formula(info['f'], tpl_row, r)
elif info.get('si') and info['si'] in shared:
def_row, text = shared[info['si']]
formula = _shift_formula(text, def_row, r)
if not formula:
continue
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
cells.append((cnum, f'{formula}'))
if not cells:
continue
cells.sort(key=lambda x: x[0])
parts.append(f'{"".join(c for _, c in cells)}
')
return ''.join(parts).encode('utf-8')
# ==================== 原生 XML 写入 ====================
def _append_rows_native(path, sheet_name, payload, new_max_row, skip_from_row):
"""流式重写目标 sheet:更新 dimension → 丢弃尾部空公式行 → 插新行 → 其余部件原样拷贝。"""
tmp = path + '.rebuild.tmp'
marker = b''
skip_tag = f'= 0 and (i_skip < 0 or i_mark < i_skip):
fout.write(buf[:i_mark])
fout.write(payload)
fout.write(buf[i_mark:])
shutil.copyfileobj(fin, fout, 4 << 20)
inserted = True
break
if i_skip >= 0:
fout.write(buf[:i_skip])
buf = buf[i_skip:]
dropping = True
continue
keep = max(len(skip_tag), len(marker), 512 * 1024)
fout.write(buf[:-keep])
buf = buf[-keep:]
src.close() # Windows 下必须先放句柄,否则 os.replace 失败
if not inserted:
try:
os.remove(tmp)
except OSError:
pass
raise RuntimeError('sheet xml 里没找到 ,未做任何修改')
os.replace(tmp, path)
return len(payload)
# ==================== 明细读取 ====================
def _header_index(header):
out = {}
for i, v in enumerate(header):
if v is None:
continue
name = str(v).strip()
if name and name not in out:
out[name] = i
return out
def _read_details(files, ledger_max, max_keys):
"""读全部核销明细,剔除比台账旧的行与台账边界已有的行。"""
head, rows = None, []
total = skip_old = skip_dup = skip_notime = 0
seen = set()
for path in files:
# 平台导出的明细 dimension 常是 A1(read_only 只会读到第一列),文件不大,直接完整加载
wb = load_workbook(path, data_only=True)
try:
ws = wb.worksheets[0]
it = ws.iter_rows(values_only=True)
first = next(it, None)
if first is None:
continue
dhead = _header_index(first)
if head is None:
head = dhead
for name in ('订单编号', config.TIME_COL):
if name not in dhead:
return {'ok': False,
'message': f'明细「{os.path.basename(path)}」缺少列「{name}」'}
ti = head[config.TIME_COL]
oi = head.get('订单编号')
ci = next((i for n, i in head.items() if n.startswith('券码')), None)
for row in it:
if row is None:
continue
total += 1
raw_t = row[ti] if ti < len(row) else None
dt = _to_dt(raw_t)
if dt is None:
skip_notime += 1
continue
if dt < ledger_max:
skip_old += 1
continue
key = (str(row[oi] or '') if oi is not None and oi < len(row) else '',
str(row[ci] or '') if ci is not None and ci < len(row) else '',
str(raw_t or ''))
if dt == ledger_max and key in max_keys:
skip_dup += 1
continue
if key in seen:
skip_dup += 1
continue
seen.add(key)
rows.append((dt, row))
finally:
wb.close()
# 多份明细按核销时间排序后追加,保持台账「时间递增」的历史形态
rows.sort(key=lambda x: x[0])
return {'ok': True, 'head': head or {}, 'rows': [r for _, r in rows],
'total': total, 'skip_old': skip_old, 'skip_dup': skip_dup,
'skip_notime': skip_notime}
# ==================== 入口 ====================
def run(dry_run=False, detail_dir=None, ledger_dir=None):
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。
detail_dir:核销明细所在目录(默认=保存目录);ledger_dir:台账所在目录。
两者都可为空 → 回退 config.WORK_DIR(历史上导出与台账同目录)。
"""
detail_dir = detail_dir or config.WORK_DIR
ledger_dir = ledger_dir or config.WORK_DIR
if not os.path.isdir(ledger_dir):
return {'ok': False, 'message': f'台账目录不存在:{ledger_dir}'}
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True, root=ledger_dir)
if not ledger:
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}({ledger_dir})'}
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)[0]}年'
f'{_month_key(ledger)[1]}月)')
if not os.path.isdir(detail_dir):
return {'ok': False, 'message': f'核销明细目录不存在:{detail_dir}'}
details = [p for p in glob.glob(os.path.join(detail_dir, config.DETAIL_GLOB))
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')
and not os.path.basename(p).startswith('~$')]
if not details:
return {'ok': False, 'message': f'未找到核销明细:{config.DETAIL_GLOB}({detail_dir})'}
details.sort(key=os.path.getmtime)
config.log(f'核销明细 {len(details)} 份:' +
'、'.join(os.path.basename(p) for p in details))
t0 = time.time()
info = _scan_ledger(ledger, config.LEDGER_SHEET)
if not info.get('ok'):
return {'ok': False, 'message': info.get('message')}
if config.TIME_COL not in info['header']:
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
if info['max_dt'] is None:
return {'ok': False, 'message': f'台账「{config.TIME_COL}」列没有有效时间'}
last_data = info['last_data_row']
tail = (info.get('max_row') or last_data) - last_data
config.log(f'台账真实末行 {last_data},{config.TIME_COL}最大 {info["max_dt"]},'
f'尾部 {tail} 行空公式行(dimension 到 {info.get("max_row")});'
f'扫描耗时 {time.time() - t0:.1f}s')
bad_formula = _check_formula_cols(info)
if bad_formula:
msg = f'模板行 {info["tpl_row"]} 的公式列 {bad_formula} 找不到共享公式主定义'
if 'A' in bad_formula:
return {'ok': False, 'message': msg + '(A 列日期为公式,无法下拉)'}
config.log(msg + ',这些列本次留空', 'WARN')
fcols = [c for c, v in info['tpl'].items() if v.get('f') or v.get('si')]
config.log(f'公式列(按模板行下拉):{fcols}', 'DEBUG')
config.log(f'不写公式的列:{list(config.FORMULA_SKIP_COLS)}(业务口径:CC 不管)', 'DEBUG')
det = _read_details(details, info['max_dt'], info['max_keys'])
if not det.get('ok'):
return {'ok': False, 'message': det.get('message')}
rows = det['rows']
config.log(f'明细共 {det["total"]} 行:保留 {len(rows)},'
f'早于台账 {det["skip_old"]},重复 {det["skip_dup"]},'
f'无核销时间 {det["skip_notime"]}')
if not rows:
return {'ok': True, 'appended': 0, 'ledger': ledger,
'message': '明细里没有比台账更新的记录'}
lhead = info['header']
dhead = det['head']
col_map = [(didx, lhead[name]) for name, didx in dhead.items()
if name in lhead and lhead[name] != 1] # A 列日期是公式,不写值
missing = [n for n in lhead if n not in dhead]
ignored = [n for n in dhead if n not in lhead]
config.log(f'列映射 {len(col_map)} 列;台账独有(留空):{missing or "无"};'
f'明细独有(忽略):{ignored or "无"}', 'DEBUG')
start_row = last_data + 1
new_max_row = start_row + len(rows) - 1
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
if dry_run:
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
'ledger': ledger, 'message': f'[演练] 将追加 {len(rows)} 行'}
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
if os.path.exists(lock):
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),'
'请关闭后重跑'}
try:
with open(ledger, 'r+b'):
pass
except OSError as e:
return {'ok': False, 'message': f'台账不可写(可能被 Excel 占用):{e}'}
bak = os.path.join(
os.path.dirname(ledger),
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份'
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
shutil.copy2(ledger, bak)
config.log(f'已备份 → {os.path.basename(bak)}')
payload = _rows_xml(rows, start_row, col_map, info['tpl'], info['tpl_row'],
info['shared'], info['num_cols'])
t1 = time.time()
size = _append_rows_native(ledger, config.LEDGER_SHEET, payload, new_max_row,
skip_from_row=start_row)
config.log(f'并入完成:{len(rows)} 行,耗时 {time.time() - t1:.1f}s'
f'(写入 {size / 1024:.0f} KB)')
verify = _scan_ledger(ledger, config.LEDGER_SHEET)
if verify.get('ok'):
config.log(f'校验:真实末行 {verify["last_data_row"]}(预期 {new_max_row}),'
f'{config.TIME_COL}最大 {verify["max_dt"]}')
return {'ok': True, 'appended': len(rows), 'start_row': start_row,
'end_row': new_max_row, 'ledger': ledger,
'message': f'已并入 {len(rows)} 行到台账'}