build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置

- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间
- 新增插件根目录迁移逻辑,解决旧版权限问题
- 新增多个服务端实体、DTO、配置模块等基础代码
- 新增插件 UI 模板及相关静态资源
This commit is contained in:
2026-10-15 11:38:45 +08:00
parent 872d3dc5c8
commit f0a94bf523
717 changed files with 88647 additions and 17543 deletions
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
"""数据层:源名单 / 台账读取、按业务口径筛选分组。"""
-154
View File
@@ -1,154 +0,0 @@
# -*- coding: utf-8 -*-
"""数据层:源名单(参保名单/停保名单)与社保户头管理台账的读取、筛选、取号。
统一承载 XQ0008(名单制作)与 XQ0014(系统办理/核查)共用的数据读取逻辑:
- load_records(kind, operation_type, status_filter):读源名单并按业务口径筛选
- load_units / load_check_tasks:按参保单位分组(办理/核查任务)
- load_accounts:从台账取各单位政务平台账号
"""
import os
from datetime import datetime
from .. import config
def read_source(kind):
"""定位并解析源名单,返回 (source_file, sheet_name)。
kind: 'add' 参保名单 sheet / 'stop' 停保名单 sheet(sheet 名年月动态,取最新)。
"""
source_file = config._latest_file(config.get_base_dir(), config.SOURCE_GLOB)
now = datetime.now()
xl = __import__('pandas').ExcelFile(source_file)
if kind == 'add':
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_ADD}",
config.SHEET_KEY_ADD)
else:
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_STOP}",
config.SHEET_KEY_STOP,
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
return source_file, sheet_name
def load_records(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
"""读源名单并按业务口径筛选,返回 DataFrame(表头第3行)。
- kind: 'add'(参保名单)/ 'stop'(停保名单)
- operation_type: 增员时的参保类型('新参保'/'转移参保');减员忽略(固定两类都办)
- status_filter: 'empty' 办理状态/办理停保为空;'待审核' 等于该值
- exclude_ids: 排除的身份证号集合(上次已回写人员,防重复申报/核查)
"""
import pandas as pd
source_file, sheet_name = read_source(kind)
print_source = os.path.basename(source_file)
# 对齐原版 dtype 保护:add 只指定身份证/电话两列为文本(18 位身份证防 float 丢精度),
# stop 全列文本;dtype 字典引用 sheet 不存在的列不会报错
dtype = {"身份证号码": str, "电话号码": str} if kind == 'add' else str
df = pd.read_excel(source_file, sheet_name=sheet_name,
header=config.SOURCE_HEADER_ROW - 1, dtype=dtype)
if kind == 'add':
status_col = "办理状态"
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
mask &= (df["参保类型"].astype(str).str.strip() == operation_type)
else:
status_col = config.STOP_PROCESSED_COL
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
mask &= (df["类型"].astype(str).str.strip().isin(config.STOP_TYPES))
if status_filter == "empty":
st_text = df[status_col].astype(str).str.strip().str.lower()
mask &= (df[status_col].isna() | st_text.isin(['', 'nan', 'none', 'nat']))
else:
mask &= (df[status_col].astype(str).str.strip() == status_filter)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [config._norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
config.log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报/核查)")
return sub, source_file, sheet_name, status_col
def load_units(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
"""读取名单并筛选,返回 [(参保单位, 人数), ...](按单位分组,名称排序)。"""
sub, source_file, sheet_name, status_col = load_records(
kind, operation_type, status_filter, exclude_ids)
print_source = os.path.basename(source_file)
if kind == 'add':
desc = f"{config.TARGET_REGION} ∩ 参保类型={operation_type}"
else:
desc = f"{config.TARGET_REGION} ∩ 类型∈{'/'.join(config.STOP_TYPES)}"
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
if sub.empty:
config.log(f"没有筛选到数据({desc} ∩ {status_col}={'空' if status_filter == 'empty' else status_filter})")
return [], source_file, sheet_name
grouped = sub.groupby(sub["参保单位"].astype(str).str.strip()).size()
units = sorted(grouped.items(), key=lambda t: t[0])
config.log(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
return units, source_file, sheet_name
def load_check_tasks(kind, status_filter=config.CHECK_STATUS, exclude_ids=frozenset()):
"""读取名单筛选 办理状态/办理停保=待审核 的行,按参保单位分组。
返回 [{unit, count, cids(set)}],供核查流程使用。
"""
operation_type = config.WEB_ADD_TYPE if kind == 'add' else None
sub, source_file, sheet_name, status_col = load_records(
kind, operation_type, status_filter, exclude_ids)
print_source = os.path.basename(source_file)
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
if sub.empty:
config.log(f"没有筛选到数据({status_col}={status_filter})")
return [], source_file, sheet_name
tasks = []
for unit, g in sub.groupby(sub["参保单位"].astype(str).str.strip()):
cids = {config._norm_id(v) for v in g['身份证号码']}
cids.discard('')
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
tasks.sort(key=lambda t: t['unit'])
config.log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / "
f"{len(tasks)} 个参保单位({status_col}={status_filter})")
return tasks, source_file, sheet_name
def load_accounts(unit_names):
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
取不到的单位不在返回值中(由预检统一报错)。
"""
import pandas as pd
ledger_file = config._latest_file(config.get_ledger_dir(), config.LEDGER_GLOB)
now = datetime.now()
xl = pd.ExcelFile(ledger_file)
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例",
config.SHEET_KEY_LEDGER,
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
config.log(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
df = df[df[config.LEDGER_COL["户头"]].notna()].copy()
for c in config.LEDGER_COL.values():
df[c] = df[c].map(config._to_text)
pool = df[(df[config.LEDGER_COL["城市"]] == config.TARGET_REGION)
& (df[config.LEDGER_COL["在用"]] == "是")]
accounts = {}
for name in unit_names:
hit = pool[pool[config.LEDGER_COL["户头"]] == name]
if hit.empty:
continue # 预检阶段统一报「台账未匹配」
row = hit.iloc[0]
credit, plat_user, plat_pwd = (
row[config.LEDGER_COL["信用代码"]], row[config.LEDGER_COL["平台用户名"]],
row[config.LEDGER_COL["平台密码"]])
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
return accounts
-133
View File
@@ -1,133 +0,0 @@
# -*- 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