# -*- coding: utf-8 -*- """名单回写(JSON 缓存防崩溃,运行结束统一写 Excel 一次)。 原影刀版 import_add/import_stop/check_review/check_review_stop 各自维护一套 「内存累积 + JSON 缓存 + 结束统一落盘」机制,此处收敛为 Writeback 类: - 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel) - 运行结束 flush() 统一写 Excel 一次,保存成功校验后删除缓存 - 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单 - kind 区分回写列:add → 办理状态;stop → 办理停保;缓存文件名也分开,增/减互不干扰 """ import json import os from .. import config class Writeback: """按 kind(add/stop)绑定的名单回写器。""" def __init__(self, kind): self.kind = kind cache_name = ("writeback_pending.json" if kind == "add" else "writeback_pending_stop.json") self._cache_path = os.path.join(config.CKPT_DIR, cache_name) self._status_col = "办理状态" if kind == "add" else config.STOP_PROCESSED_COL self._pending_status = {} self._pending_remark = {} self._source_file = None self._source_sheet = None # ---------------- 源名单绑定(flush 依赖) ---------------- def bind_source(self, source_file, source_sheet): self._source_file = source_file self._source_sheet = source_sheet def has_pending(self): return bool(self._pending_status or self._pending_remark) # ---------------- JSON 缓存 ---------------- def _save_ckpt(self): """把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。""" data = [{"id": cid, "status": self._pending_status.get(cid, ""), "remark": self._pending_remark.get(cid, "")} for cid in dict.fromkeys(list(self._pending_status) + list(self._pending_remark))] os.makedirs(config.CKPT_DIR, exist_ok=True) tmp = self._cache_path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=1) os.replace(tmp, self._cache_path) def load_ckpt(self): """启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。""" recovered = set() if not os.path.isfile(self._cache_path): return recovered try: with open(self._cache_path, "r", encoding="utf-8") as f: for it in json.load(f): cid = it.get("id") if it.get("status"): self._pending_status[cid] = it["status"] if it.get("remark"): self._pending_remark[cid] = it["remark"] if cid: recovered.add(cid) except Exception as e: config.log(f" 恢复回写缓存失败:{e}") return recovered # ---------------- 累积 ---------------- def writeback_source(self, status_map, remark_map): """按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel)。""" self._pending_status.update(status_map or {}) self._pending_remark.update(remark_map or {}) try: self._save_ckpt() except Exception as e: config.log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}") # ---------------- 统一落盘 ---------------- def flush(self): """把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件), 保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。""" if not self.has_pending(): return 0 if not self._source_file: raise RuntimeError("无源名单文件记录,无法回写") from openpyxl import load_workbook wb = load_workbook(self._source_file) ws = wb[self._source_sheet] # 表头第3行定位列号 hdr = {} for c in ws[config.SOURCE_HEADER_ROW]: if c.value is not None: hdr[str(c.value).strip()] = c.column col_id = hdr.get('身份证号码') col_status = hdr.get(self._status_col) col_remark = hdr.get('备注') if not col_id or not col_status: raise RuntimeError(f"源名单缺少身份证号码/{self._status_col}列,无法回写") changed = 0 pending_ids = set(self._pending_status) | set(self._pending_remark) ref = [config._norm_id(x) for x in pending_ids] for row in ws.iter_rows(min_row=config.SOURCE_HEADER_ROW + 1): cid = config._norm_id(row[col_id - 1].value) if cid and config._id_hit(cid, ref): r = row[0].row if cid in self._pending_status: ws.cell(row=r, column=col_status, value=self._pending_status[cid]) if cid in self._pending_remark and col_remark: # 备注追加不覆盖:新备注换行追加(已存在则不重复追加) cell = ws.cell(row=r, column=col_remark) old = str(cell.value or '').strip() new = str(self._pending_remark[cid]).strip() if new not in old: cell.value = f"{old}\n{new}" if old else new changed += 1 try: wb.save(self._source_file) except PermissionError: # 缓存保留,下次启动自动恢复回写 raise RuntimeError(f"源名单文件被占用(请关闭 Excel 后重跑),回写未保存") self._pending_status.clear() self._pending_remark.clear() if os.path.isfile(self._cache_path): os.unlink(self._cache_path) config.log(f" 源名单回写完成:更新 {changed} 行 → " f"{os.path.basename(self._source_file)}(缓存已清除)") config.log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP)," "下次运行前请先用 Excel 打开并保存一次该名单以重算公式") return changed