# -*- coding: utf-8 -*- """Excel 读写层(sb_person_change 插件)。 - 模板生成:xlrd 读取 + xlutils 复制《增员模版.xls》/《减员模版.xls》, 保留 Sheet2 下拉字典与数据有效性(generate_add/generate_stop 同源); - 源名单回写:JSON 缓存防崩溃,运行结束统一 openpyxl 回写一次 (import_add/check_review 同源机制,缓存文件落在插件 debug/ 目录)。 """ import json import os from datetime import datetime from glob import glob import xlrd from xlutils.copy import copy as xl_copy from . import config def _log(msg): config.log(msg) # ==================== 模板写入(增员/减员共用) ==================== def write_template(template_file, output_path, unit_no, unit_name, records, tpl_cols, date_cols): """复制模板写入 B1/D1 及第4行起数据,另存为 output_path。 - xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留下拉字典; - B1=社保号(或单位社保号),D1=单位全称;数据从模板第4行起,按 tpl_cols 顺序写入; - 日期列以 yyyy/m/d 文本写入(不补零,如 2026/9/1); - 模板原数据区中未被覆盖的多余示例行清空。 """ rb = xlrd.open_workbook(template_file, formatting_info=True) orig_rows = rb.sheet_by_index(0).nrows wb = xl_copy(rb) ws = wb.get_sheet(0) # 批量导入 ws.write(0, 1, unit_no) # B1 社保号/单位社保号 ws.write(0, 3, unit_name) # D1 参保单位全称 start = config.TPL_DATA_START_ROW - 1 # 0-based:模板第4行 → index 3 for i, rec in enumerate(records): r = start + i for c, col in enumerate(tpl_cols): val = rec.get(col) if col in date_cols and val is not None: ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}") else: ws.write(r, c + 1, config._clean_value(val)) # 清空模板原数据区未被覆盖的多余示例行 for r in range(start + len(records), orig_rows): for c in range(1, len(tpl_cols) + 1): ws.write(r, c, "") os.makedirs(os.path.dirname(output_path), exist_ok=True) wb.save(output_path) def find_template_file(name): """定位模板(优先精确名,其次按 *<名>*.xls 匹配,取最新)。name 如「增员模版.xls」。""" exact = os.path.join(config.SOURCE_DIR, name) if os.path.isfile(exact): return exact keyword = name.rsplit(".", 1)[0] candidates = glob(os.path.join(config.SOURCE_DIR, f"*{keyword}*.xls")) if not candidates: raise FileNotFoundError( f"在 {config.SOURCE_DIR} 下未找到《{name}》,请先准备导入模板。") return max(candidates, key=os.path.getmtime) def get_output_dir_add(operation_type): """增员输出目录(SOURCE_DIR/新参保-增员 或 转移参保-增员),不存在则自动创建。""" sub = config.OUTPUT_DIR_NAME.get(operation_type) if not sub: raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.OUTPUT_DIR_NAME)})") out_dir = os.path.join(config.SOURCE_DIR, sub) os.makedirs(out_dir, exist_ok=True) return out_dir def get_output_dir_stop(): """减员输出目录(SOURCE_DIR/停保-减员),不存在则自动创建。""" out_dir = os.path.join(config.SOURCE_DIR, config.STOP_OUTPUT_DIR_NAME) os.makedirs(out_dir, exist_ok=True) return out_dir # ==================== 源名单回写(JSON 缓存防崩溃 + 结束统一回写) ==================== # 回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel); # 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存; # 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。 _PENDING_STATUS, _PENDING_REMARK = {}, {} _SOURCE_FILE_USED, _SOURCE_SHEET_USED = None, None def set_writeback_target(source_file, sheet_name): """登记本次使用的源名单(供回写与文件占用预检)。""" global _SOURCE_FILE_USED, _SOURCE_SHEET_USED _SOURCE_FILE_USED, _SOURCE_SHEET_USED = source_file, sheet_name def get_writeback_target(): return _SOURCE_FILE_USED, _SOURCE_SHEET_USED def _save_ckpt(): """把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。""" data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""), "remark": _PENDING_REMARK.get(cid, "")} for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))] config.DEBUG_DIR.mkdir(parents=True, exist_ok=True) tmp = config.CKPT_FILE.with_suffix(".tmp") tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") tmp.replace(config.CKPT_FILE) def load_ckpt(): """启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。""" recovered = set() if not config.CKPT_FILE.exists(): return recovered try: for it in json.loads(config.CKPT_FILE.read_text(encoding="utf-8")): cid = it.get("id") if it.get("status"): _PENDING_STATUS[cid] = it["status"] if it.get("remark"): _PENDING_REMARK[cid] = it["remark"] if cid: recovered.add(cid) return recovered except Exception as e: _log(f" 恢复回写缓存失败:{e}") return recovered def writeback_source(status_map, remark_map): """按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel): status_map {身份证: 办理状态};remark_map {身份证: 备注}。""" _PENDING_STATUS.update(status_map or {}) _PENDING_REMARK.update(remark_map or {}) try: _save_ckpt() except Exception as e: _log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}") def flush_writeback(): """把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件), 保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。""" if not (_PENDING_STATUS or _PENDING_REMARK): return if not _SOURCE_FILE_USED: raise RuntimeError("无源名单文件记录,无法回写") from openpyxl import load_workbook wb = load_workbook(_SOURCE_FILE_USED) ws = wb[_SOURCE_SHEET_USED] # 表头第3行定位列号 hdr = {} for c in ws[3]: if c.value is not None: hdr[str(c.value).strip()] = c.column col_id = hdr.get('身份证号码') col_status = hdr.get('办理状态') col_remark = hdr.get('备注') if not col_id or not col_status: raise RuntimeError("源名单缺少身份证号码/办理状态列,无法回写") changed = 0 pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK) ref = [config._norm_id(x) for x in pending_ids] for row in ws.iter_rows(min_row=4): cid = config._norm_id(row[col_id - 1].value) if cid and config._id_hit(cid, ref): r = row[0].row if cid in _PENDING_STATUS: ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid]) if cid in _PENDING_REMARK and col_remark: # 备注追加不覆盖:新备注换行追加在后面(已存在则不重复追加) cell = ws.cell(row=r, column=col_remark) old = str(cell.value or '').strip() new = str(_PENDING_REMARK[cid]).strip() if new not in old: # 重查场景:备注已写过则跳过防重复 cell.value = f"{old}\n{new}" if old else new changed += 1 try: wb.save(_SOURCE_FILE_USED) except PermissionError: # 缓存保留,下次启动自动恢复回写 raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存") _PENDING_STATUS.clear() _PENDING_REMARK.clear() if config.CKPT_FILE.exists(): config.CKPT_FILE.unlink() _log(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(_SOURCE_FILE_USED)}(缓存已清除)") _log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP)," "下次运行前请先用 Excel 打开并保存一次该名单以重算公式") # ==================== 调试截图 ==================== def shot(tab, name): """调试截图:仅 DEBUG_MODE 开启时保存页面截图并记录当前 URL。""" if not config.DEBUG_MODE: return try: shot_dir = config.DEBUG_DIR / "shots" shot_dir.mkdir(parents=True, exist_ok=True) ts = datetime.now().strftime("%H%M%S") tab.get_screenshot(path=str(shot_dir), name=f"{ts}_{name}.png") _log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}") except Exception as e: _log(f" [截图失败] {name}: {e}")