- 新增 XQ0042 抖音平台核对、XQ0041 新美大平台核对插件的 UI 源码与打包脚本 - 重构续签电子签、服务岗转正不通过电子签等插件的版本与配置 - 删除旧版考勤异常处理、微盟数据导出等冗余插件文件 - 修复出勤积分更新插件的 OPM 推送判断逻辑 - 优化壳子插件页面的 iframe 滚动条样式
368 lines
14 KiB
Python
368 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: mt_stat_links.py
|
||
@Description: XQ0041 核对统计表 —— 按日期补 V/W 列外部链接公式。
|
||
|
||
业务口径(已从台账 62 条既有链接反推):
|
||
「新美大核对统计」按日期一行(A 列),V/W 列取当天「马敏团购总表」的外部引用:
|
||
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留 E)
|
||
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留 F)
|
||
外部文件路径格式:
|
||
file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||
(例:2026-10-27 → 2026年10月\\10.27\\马敏团购总表10.27.xlsx)
|
||
|
||
实现(不依赖 Excel/openpyxl 保存,避免丢透视表):
|
||
1. 扫描既有 externalLinkN.xml.rels,建立「目标路径 → 引用序号 N」映射,能复用就复用;
|
||
2. 缺的日子新增 externalLink63/64... + rels + workbook.xml 的 externalReferences
|
||
+ workbook.xml.rels 关系 + [Content_Types].xml 声明;
|
||
3. 目标 sheet 只改对应行的 V/W 两个单元格,其余部件逐字节原样拷贝。
|
||
|
||
运行(仓库根下,本地 .venv):
|
||
.venv\\Scripts\\python.exe "tests\\xq0041_新美大\\mt_stat_links.py"
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import sys
|
||
import time
|
||
import zipfile
|
||
from datetime import date, datetime, timedelta
|
||
|
||
from openpyxl import load_workbook
|
||
|
||
try:
|
||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||
except Exception:
|
||
pass
|
||
|
||
# ================== 台账与工作表 ==================
|
||
WORK_DIR = r'D:\资料\财务\新美大平台核对'
|
||
LEDGER_GLOB = '新美大到账统计*.xlsx'
|
||
STAT_SHEET = '新美大核对统计'
|
||
DETAIL_GLOB = '团购收益明细_*.xlsx'
|
||
|
||
# ================== 外部链接规则 ==================
|
||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG' # 财务共享盘根(与历史 62 条链接一致)
|
||
LINK_BOOK = '马敏团购总表' # 文件名前缀
|
||
LINK_SHEET = '资金组取数' # 被引用工作簿里的 sheet 名
|
||
FORMULA_V = '==[%d]%s!$B$5' % (0, LINK_SHEET) # 占位,实际按索引拼
|
||
FORMULA_W = '==[%d]%s!$B$6' % (0, LINK_SHEET)
|
||
|
||
# ================== 行为开关 ==================
|
||
DRY_RUN = False # True=只打印计划不落盘
|
||
BACKUP = True
|
||
|
||
_APP_DATA_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||
LOG_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
|
||
|
||
def _log(msg, level='INFO'):
|
||
head = f'[{time.strftime("%H:%M:%S")}][核对统计]'
|
||
print(f'{head} {msg}' if level == 'INFO' else f'{head}[{level}] {msg}', flush=True)
|
||
|
||
|
||
def _pick_latest(pattern, exclude=('备份',)):
|
||
import glob
|
||
files = [p for p in glob.glob(os.path.join(WORK_DIR, pattern))
|
||
if not any(x in os.path.basename(p) for x in exclude)]
|
||
if not files:
|
||
return None
|
||
files.sort(key=lambda p: os.path.getmtime(p))
|
||
return files[-1]
|
||
|
||
|
||
def _target_path(d):
|
||
"""某天对应的马敏团购总表绝对路径。"""
|
||
return os.path.join(SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
|
||
f'{LINK_BOOK}{d.month}.{d.day}.xlsx')
|
||
|
||
|
||
def _file_uri(path):
|
||
"""Windows 路径 → file:/// 形式(与既有 62 条 externalLink rels 一致:
|
||
`file:///\\\\caiwu01\\共享文件夹\\...`,XML 属性值里反斜杠不转义)。"""
|
||
return 'file:///' + path
|
||
|
||
|
||
def _resolve_period():
|
||
"""确定要补的日期区间:优先取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的文件名。"""
|
||
p = _pick_latest(DETAIL_GLOB)
|
||
if p:
|
||
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(p))
|
||
if m:
|
||
s = datetime.strptime(m.group(1), '%Y%m%d').date()
|
||
e = datetime.strptime(m.group(2), '%Y%m%d').date()
|
||
return s, e, f'明细文件名 {os.path.basename(p)}'
|
||
m = re.search(r'(\d{8})', os.path.basename(p))
|
||
if m:
|
||
d = datetime.strptime(m.group(1), '%Y%m%d').date()
|
||
return d, d, f'明细文件名 {os.path.basename(p)}'
|
||
today = date.today()
|
||
return today - timedelta(days=1), today, '默认 昨天~今天'
|
||
|
||
|
||
def _sheet_xml_path(zf, sheet_name):
|
||
import xml.etree.ElementTree as ET
|
||
NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||
NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||
NS_PKG = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||
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_PKG}Relationship'):
|
||
if rel.get('Id') == rid:
|
||
t = (rel.get('Target') or '').lstrip('/')
|
||
return t if t.startswith('xl/') else 'xl/' + t
|
||
return None
|
||
|
||
|
||
def _col_num(letters):
|
||
n = 0
|
||
for ch in letters:
|
||
n = n * 26 + (ord(ch) - 64)
|
||
return n
|
||
|
||
|
||
def _col_letter(n):
|
||
s = ''
|
||
while n > 0:
|
||
n, r = divmod(n - 1, 26)
|
||
s = chr(65 + r) + s
|
||
return s
|
||
|
||
|
||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||
|
||
|
||
def _set_row_cells(row_xml, row_no, cells):
|
||
"""在 <row> 里设置若干单元格(cells: {列字母: (公式, 样式)}),保持列序。"""
|
||
keep = []
|
||
for m in _CELL_RE.finditer(row_xml):
|
||
col = m.group(1)
|
||
if col in cells:
|
||
continue
|
||
keep.append((_col_num(col), m.group(0)))
|
||
style_default = None
|
||
for m in _CELL_RE.finditer(row_xml):
|
||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||
if sm:
|
||
style_default = sm.group(1)
|
||
break
|
||
for col, (formula, style) in cells.items():
|
||
s = style or style_default
|
||
s_attr = f' s="{s}"' if s else ''
|
||
keep.append((_col_num(col),
|
||
f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||
keep.sort(key=lambda x: x[0])
|
||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||
return f'<row{attrs.group(1) if attrs else " r=" + str(row_no)}>{"".join(c for _, c in keep)}</row>'
|
||
|
||
|
||
def _parse_links(zf):
|
||
"""扫描既有 externalLinkN.xml.rels → {目标路径(小写): N},以及最大序号。"""
|
||
mapping, max_n = {}, 0
|
||
for name in zf.namelist():
|
||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||
if not m:
|
||
continue
|
||
n = int(m.group(1))
|
||
max_n = max(max_n, n)
|
||
txt = zf.read(name).decode('utf-8', 'replace')
|
||
tm = re.search(r'Target="([^"]+)"', txt)
|
||
if tm:
|
||
mapping[tm.group(1).replace('\\\\', '\\').lower()] = n
|
||
return mapping, max_n
|
||
|
||
|
||
_EXTLINK_TPL = (
|
||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
|
||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
|
||
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
|
||
)
|
||
_EXTLINK_RELS_TPL = (
|
||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
|
||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||
)
|
||
|
||
|
||
def main():
|
||
ledger = _pick_latest(LEDGER_GLOB)
|
||
if not ledger:
|
||
_log(f'未找到台账:{LEDGER_GLOB}', 'ERROR')
|
||
return 2
|
||
_log(f'台账:{os.path.basename(ledger)}')
|
||
|
||
d_from, d_to, why = _resolve_period()
|
||
_log(f'日期区间:{d_from} ~ {d_to}(来源:{why})')
|
||
|
||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||
if STAT_SHEET not in wb.sheetnames:
|
||
_log(f'缺少 sheet「{STAT_SHEET}」', 'ERROR')
|
||
return 3
|
||
ws = wb[STAT_SHEET]
|
||
date_rows = {}
|
||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||
v = row[0]
|
||
if isinstance(v, datetime):
|
||
date_rows[v.date()] = i
|
||
elif isinstance(v, date):
|
||
date_rows[v] = i
|
||
wb.close()
|
||
_log(f'核对统计表共 {len(date_rows)} 个日期行({min(date_rows)} ~ {max(date_rows)})')
|
||
|
||
# 需要处理的日期
|
||
day = d_from
|
||
days = []
|
||
while day <= d_to:
|
||
days.append(day)
|
||
day += timedelta(days=1)
|
||
|
||
missing_rows = [d for d in days if d not in date_rows]
|
||
if missing_rows:
|
||
_log(f'以下日期在核对统计表里没有对应行,跳过:{[str(d) for d in missing_rows]}', 'WARN')
|
||
days = [d for d in days if d in date_rows]
|
||
if not days:
|
||
_log('没有可处理的日期行', 'ERROR')
|
||
return 4
|
||
|
||
zf = zipfile.ZipFile(ledger)
|
||
link_map, max_link = _parse_links(zf)
|
||
_log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||
|
||
# 规划:每个日期用哪个索引
|
||
plan = []
|
||
need_new = []
|
||
for d in days:
|
||
path = _target_path(d)
|
||
uri = _file_uri(path)
|
||
key = path.lower()
|
||
if key in link_map:
|
||
plan.append((d, date_rows[d], link_map[key], path, '复用'))
|
||
else:
|
||
idx = max_link + len(need_new) + 1
|
||
need_new.append((idx, path, uri))
|
||
plan.append((d, date_rows[d], idx, path, '新增'))
|
||
|
||
for d, row_no, idx, path, mode in plan:
|
||
_log(f' {d} → 第{row_no}行 V/W 用 [{idx}]({mode}){path}')
|
||
|
||
_log('=' * 66)
|
||
for idx, path, uri in need_new:
|
||
_log(f'新增 externalLink{idx}.xml → {uri}')
|
||
_log('=' * 66)
|
||
|
||
if DRY_RUN:
|
||
_log('DRY_RUN=True:只打印计划,未写入。')
|
||
zf.close()
|
||
return 0
|
||
|
||
if not os.path.isdir(SHARE_ROOT):
|
||
_log(f'提示:共享盘当前不可达({SHARE_ROOT}),公式仍会写入,'
|
||
f'等共享盘恢复后打开 Excel 点「更新」即可取值', 'WARN')
|
||
|
||
if BACKUP:
|
||
bak = os.path.join(
|
||
WORK_DIR,
|
||
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||
_log(f'备份 → {os.path.basename(bak)}')
|
||
shutil.copy2(ledger, bak)
|
||
|
||
# ---------- 读取需要改写的部件 ----------
|
||
sheet_path = _sheet_xml_path(zf, STAT_SHEET)
|
||
if not sheet_path:
|
||
_log(f'找不到「{STAT_SHEET}」对应的 xml', 'ERROR')
|
||
zf.close()
|
||
return 5
|
||
sheet_xml = zf.read(sheet_path) # 该 sheet 仅 300KB 左右,整读
|
||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||
|
||
# ---------- 改 sheet:写入 V/W 公式 ----------
|
||
text = sheet_xml.decode('utf-8')
|
||
row_cells = {}
|
||
for d, row_no, idx, path, mode in plan:
|
||
row_cells.setdefault(row_no, {})['__idx'] = idx
|
||
for row_no, info in row_cells.items():
|
||
idx = info['__idx']
|
||
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', text, re.S)
|
||
if not m:
|
||
_log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||
continue
|
||
new_row = _set_row_cells(m.group(0), row_no, {
|
||
'V': (f'=[{idx}]{LINK_SHEET}!$B$5', None),
|
||
'W': (f'=[{idx}]{LINK_SHEET}!$B$6', None),
|
||
})
|
||
text = text[:m.start()] + new_row + text[m.end():]
|
||
_log(f'第 {row_no} 行已写入 V/W([{idx}])')
|
||
|
||
# ---------- 新增外部链接 ----------
|
||
for idx, path, uri in need_new:
|
||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||
rid = f'rId{rid_num}'
|
||
wb_rels = wb_rels.replace(
|
||
'</Relationships>',
|
||
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
|
||
f'officeDocument/2006/relationships/externalLink" '
|
||
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
|
||
wb_xml = wb_xml.replace('</externalReferences>',
|
||
f'<externalReference r:id="{rid}"/></externalReferences>')
|
||
ct_xml = ct_xml.replace(
|
||
'</Types>',
|
||
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
|
||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||
_log(f'外部链接 {idx} 已登记({rid})')
|
||
|
||
# ---------- 重写 zip ----------
|
||
tmp = ledger + '.rebuild.tmp'
|
||
replace = {
|
||
sheet_path: text.encode('utf-8'),
|
||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
|
||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||
}
|
||
new_files = {}
|
||
for idx, path, uri in need_new:
|
||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||
(_EXTLINK_TPL % LINK_SHEET).encode('utf-8')
|
||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||
(_EXTLINK_RELS_TPL % uri).encode('utf-8')
|
||
|
||
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 replace:
|
||
dst.writestr(zi, replace.pop(info.filename))
|
||
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 list(replace.items()) + list(new_files.items()):
|
||
dst.writestr(name, data)
|
||
zf.close()
|
||
os.replace(tmp, ledger)
|
||
|
||
_log('=' * 66)
|
||
_log(f'完成:{len(plan)} 个日期行更新 V/W,新增外部链接 {len(need_new)} 条')
|
||
_log('=' * 66)
|
||
return 0
|
||
|
||
|
||
if __name__ == '__main__':
|
||
raise SystemExit(main())
|