feat: 新增多插件 UI 支持及运行日志集中回传功能

本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
2026-10-26 15:42:50 +08:00
parent 9fd687ada8
commit 843ff244a6
453 changed files with 243002 additions and 4493 deletions
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 业务逻辑层(工作簿读写、文件选择、状态记录、COM 重算)。"""
+105
View File
@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - WPS/Excel COM 全量重算 + 取消筛选。
openpyxl 覆盖保存后公式缓存丢失,必须经 COM 全量重算并保存,后续 data_only 读取才有值。
引擎按 Ket.Application(WPS)→ et.Application(旧版 WPS)→ Excel.Application 兜底;
目标文件已在 WPS/Excel 中打开时复用该工作簿,不关闭、不退出用户实例。
"""
import os
from .. import config
class ComRecalcError(RuntimeError):
"""公式重算失败(无可用 COM 引擎 / 文件被锁定 / COM 异常)。"""
def recalc_target(file_path):
"""对 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。"""
file_path = os.path.abspath(file_path)
if not os.path.isfile(file_path):
raise ComRecalcError(f"待重算文件不存在:{file_path}")
import pythoncom
import win32com.client
pythoncom.CoInitialize()
app = None
prog_id = ""
wb = None
already_open = False
try:
last_err = None
for pid in config.COM_PROG_IDS:
try:
app = win32com.client.Dispatch(pid)
prog_id = pid
break
except Exception as e:
last_err = e
if app is None:
raise ComRecalcError(
"本机未检测到可用的 WPS/Excel COM(依次尝试 "
+ " / ".join(config.COM_PROG_IDS) + f" 均失败):{last_err}")
try:
app.DisplayAlerts = False
for w in app.Workbooks:
try:
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
wb = w
already_open = True
break
except Exception:
continue
if wb is None:
wb = app.Workbooks.Open(file_path)
removed = 0
for ws in wb.Worksheets:
try:
if ws.AutoFilterMode:
ws.AutoFilterMode = False
removed += 1
except Exception:
pass
try:
wb.Application.CalculateFullRebuild()
except Exception:
try:
wb.Application.CalculateFull()
except Exception:
wb.Application.Calculate()
wb.Save()
config.logger.info("COM 处理完成(%s):取消 %d 个 sheet 筛选,公式全量重算并保存%s",
prog_id, removed,
"(复用已打开的工作簿)" if already_open else "")
finally:
try:
app.DisplayAlerts = True
except Exception:
pass
if wb is not None and not already_open:
try:
wb.Close(SaveChanges=False)
except Exception:
pass
except ComRecalcError:
raise
except Exception as e:
raise ComRecalcError(
f"公式重算失败({prog_id or 'COM'}):{e}\n"
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。") from e
finally:
if app is not None:
try:
if app.Workbooks.Count == 0:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass
+62
View File
@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 离职当月再入职人员无效积分段踢除。"""
from datetime import date
from .. import config
_CODE = "hr_staff_base.base_code"
_NAME = "hr_staff_base.staff_name"
def _clean(v):
if v is None:
return ""
return str(v).strip()
def blank_rejoin_gap(report_rows, rejoin_rows, old_codes_map=None):
"""就地清空再入职人员无效积分段,返回清空的考勤状态单元格数。
- 台账工号:清 [离职日, 再入职日) 中间段;
- 历史工号(换工号再入职):清 [再入职日, 月末],但要求报告行工号+姓名同时匹配,
避免工号被复用后误清他人积分。
"""
old_codes_map = old_codes_map or {}
gaps = {} # 台账工号 -> (leave_day, join_day)
old_gaps = {} # 历史工号 -> (join_day, 再入职人姓名)
for r in rejoin_rows:
code = _clean(r.get(_CODE))
name = _clean(r.get(_NAME))
ld = r.get(f"{config.REJOIN_FIELD_PREFIX}.leave_date")
jd = r.get(f"{config.REJOIN_FIELD_PREFIX}.join_date")
if not code or not ld or not jd:
continue
try:
leave = date.fromisoformat(str(ld).strip()[:10])
join = date.fromisoformat(str(jd).strip()[:10])
except ValueError:
continue
gaps[code] = (leave.day, join.day)
for old_code in old_codes_map.get(code, ()):
old_gaps[old_code] = (join.day, name)
if not gaps and not old_gaps:
return 0
cleared = 0
for row in report_rows:
code, row_name = row[0], row[8]
if code in gaps:
leave_day, join_day = gaps[code]
for d in range(leave_day, join_day):
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
row[8 + d] = ""
cleared += 1
elif code in old_gaps:
join_day, rejoin_name = old_gaps[code]
if row_name != rejoin_name:
continue
for d in range(join_day, 32):
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
row[8 + d] = ""
cleared += 1
return cleared
+138
View File
@@ -0,0 +1,138 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - openpyxl 工作表通用操作(清洗 / 日期解析 / 行块写删)。
内存约束:openpyxl 的 ws.cell(row=r, column=c) 对不存在的单元格会**创建** Cell 对象,
百万行模板上逐行扫描会凭空造出几十万个 Cell(单个约 220 字节,且 save 时还要序列化),
是本插件出现 MemoryError 的主因。因此扫描类操作一律改为遍历 ws._cells(只读已存在的
单元格),绝不使用 "for r in range(start, ws.max_row + 1): ws.cell(...)" 的写法。
"""
from datetime import date, datetime
def clean(v):
"""None → "",其余转字符串并去首尾空白(与人工粘贴一致)。"""
if v is None:
return ""
return str(v).strip()
def to_date(v):
"""积分日期单元格 → date(datetime/date 直取,字符串尝试 ISO 解析),失败返回 None。"""
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if v is None:
return None
try:
return date.fromisoformat(str(v).strip()[:10])
except ValueError:
return None
def cell_map(ws):
"""可写工作表内部单元格字典 {(row, col): Cell};read_only 工作表返回 None。"""
return getattr(ws, "_cells", None)
def existing_value(ws, row, col):
"""读取单元格值但不创建 Cell(模板上大量空白格不落地)。"""
cells = cell_map(ws)
if cells is None:
return ws.cell(row=row, column=col).value
cell = cells.get((row, col))
return None if cell is None else cell.value
def delete_sheet_rows(ws, row_nums):
"""按行号集合删除行:合并连续段后从后往前 delete_rows,避免逐行移动。"""
if not row_nums:
return 0
nums = sorted(set(row_nums))
removed = 0
start = prev = nums[0]
segments = []
for n in nums[1:]:
if n == prev + 1:
prev = n
continue
segments.append((start, prev - start + 1))
start = prev = n
segments.append((start, prev - start + 1))
for seg_start, seg_len in sorted(segments, reverse=True):
ws.delete_rows(seg_start, seg_len)
removed += seg_len
return removed
def scan_last_data_row(ws, col, start_row):
"""扫描某列非空值的最后一行(只遍历已存在单元格,不创建空白 Cell)。"""
last = start_row - 1
cells = cell_map(ws)
if cells is None:
for r in range(start_row, ws.max_row + 1):
if ws.cell(row=r, column=col).value not in (None, ""):
last = r
return last
for (r, c), cell in cells.items():
if c != col or r < start_row:
continue
if cell.value not in (None, "") and r > last:
last = r
return last
def scan_last_formula_row(ws, col, start_row):
"""扫描某列最后一个公式单元格(值以 = 开头),同样不创建 Cell。"""
last = start_row - 1
cells = cell_map(ws)
if cells is None:
for r in range(start_row, ws.max_row + 1):
v = ws.cell(row=r, column=col).value
if isinstance(v, str) and v.startswith("="):
last = r
return last
for (r, c), cell in cells.items():
if c != col or r < start_row:
continue
v = cell.value
if isinstance(v, str) and v.startswith("=") and r > last:
last = r
return last
def iter_rows_with_value(ws, col, start_row):
"""按行号升序产出 (行号, 该列值),只遍历已存在单元格,不创建 Cell。"""
cells = cell_map(ws)
if cells is None:
for r in range(start_row, ws.max_row + 1):
v = ws.cell(row=r, column=col).value
if v not in (None, ""):
yield r, v
return
row_nums = sorted(r for (r, c) in cells if c == col and r >= start_row)
for r in row_nums:
v = cells[(r, col)].value
if v not in (None, ""):
yield r, v
def write_block(ws, start_row, rows_values, col_start, old_last_row, col_count=None):
"""写入行块并清理旧尾部:新行写入 [start_row, start_row+n),其后旧数据行清 None。"""
n = len(rows_values)
if col_count is None:
col_count = len(rows_values[0]) if rows_values else 0
for i, row_vals in enumerate(rows_values):
r = start_row + i
for j, v in enumerate(row_vals):
ws.cell(row=r, column=col_start + j, value=v)
# 清尾只清理真实存在的单元格,避免在空白行上凭空创建 Cell
tail_start = start_row + n
if old_last_row >= tail_start:
cells = cell_map(ws)
for r in range(tail_start, old_last_row + 1):
for c in range(col_start, col_start + col_count):
cell = cells.get((r, c)) if cells is not None else None
if cell is not None:
cell.value = None
return n
+27
View File
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 新增段历史记录(_xq0033_state.json)。
结构:{数据文件名: {"new_dates": ["YYYY-MM-DD", ...]}}
删除旧修正行时跳过这些日期,防止误删历轮新增段。
"""
import json
import os
from .. import config
def load_state(path):
"""读取状态文件(不存在或损坏时按空处理并告警)。"""
if not path or not os.path.exists(path):
return {}
try:
with open(path, encoding="utf-8") as f:
return json.load(f) or {}
except Exception as e:
config.logger.warning("状态文件读取失败(按空历史处理):%s", e)
return {}
def save_state(path, state):
with open(path, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=2)
+109
View File
@@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 积分工作簿目标文件选择。
文件名 = 前缀 + 积分日期段(如 1009 单日 / 1011-12 跨日)。
优先复用文件名含 T-2 的文件(续用追加);否则复制修改时间最新的文件另存为
「前缀{T-2 MMDD}.xlsx」作为新批(积分导入/删除表由调用方清空重写)。
"""
import os
import re
import shutil
from datetime import date, timedelta
from .. import config
def parse_name_dates(filename, year=None):
"""从文件名解析积分日期段集合 → {date}(跨日按起止展开为逐日)。"""
stem = os.path.splitext(filename)[0]
if stem.startswith(config.FILE_PREFIX):
stem = stem[len(config.FILE_PREFIX):]
year = year or date.today().year
dates = set()
first_month = None
for seg in stem.split("-"):
seg = seg.strip()
if re.fullmatch(r"\d{4}", seg):
m, d = int(seg[:2]), int(seg[2:])
if 1 <= m <= 12 and 1 <= d <= 31:
first_month = m
dates.add(date(year, m, d))
elif re.fullmatch(r"\d{2}", seg) and first_month is not None:
d = int(seg)
if 1 <= d <= 31:
dates.add(date(year, first_month, d))
if len(dates) > 1:
lo, hi = min(dates), max(dates)
span, cur = set(), lo
while cur <= hi:
span.add(cur)
cur += timedelta(days=1)
dates = span
return dates
def pick_latest_file(save_dir, force_file=None):
"""仅推送时使用:取目录内修改时间最新的批次文件(不新建批次)。"""
if force_file:
if not os.path.isfile(force_file):
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
return os.path.abspath(force_file)
if not os.path.isdir(save_dir):
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
files = [f for f in os.listdir(save_dir)
if f.startswith(config.FILE_PREFIX) and f.endswith(".xlsx")
and not f.startswith("~$")]
if not files:
raise FileNotFoundError(f"目录 {save_dir} 未找到「{config.FILE_PREFIX}*.xlsx」文件")
return os.path.join(save_dir, max(files, key=lambda f: os.path.getmtime(os.path.join(save_dir, f))))
def pick_target_file(today, save_dir, force_file=None):
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件, 上轮已处理的积分日期)。
第三个返回值取「被复制批次文件名里的最大日期」,用于识别两次运行之间漏处理的日期;
指定工作簿时来源不可信,返回 None(不做补漏推断)。
"""
if force_file:
if not os.path.isfile(force_file):
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
return os.path.abspath(force_file), False, None
if not os.path.isdir(save_dir):
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
locks = [f for f in os.listdir(save_dir)
if f.startswith("~$") and f.endswith(".xlsx")]
if locks:
raise RuntimeError(
"检测到 WPS/Excel 锁文件(%s),目标文件正被打开,请先关闭后重试" % "、".join(locks))
files = [f for f in os.listdir(save_dir)
if f.startswith(config.FILE_PREFIX) and f.endswith(".xlsx")
and not f.startswith("~$") and parse_name_dates(f, today.year)]
if not files:
raise RuntimeError(
f"目录 {save_dir} 下未找到「{config.FILE_PREFIX}MMDD.xlsx」格式数据文件,"
"请先放入模板文件")
t2 = today - timedelta(days=2)
for f in files:
if t2 in parse_name_dates(f, today.year):
path = os.path.join(save_dir, f)
config.logger.info("命中文件名含 T-2(%s) 的数据文件:%s(续用追加模式)",
t2.strftime("%m%d"), f)
return path, False, t2
newest = max(files, key=lambda f: os.path.getmtime(os.path.join(save_dir, f)))
src_dates = parse_name_dates(newest, today.year)
covered_until = max(src_dates) if src_dates else None
new_name = f"{config.FILE_PREFIX}{t2.strftime('%m%d')}.xlsx"
new_path = os.path.join(save_dir, new_name)
if os.path.exists(new_path):
config.logger.warning("新批文件 %s 已存在但文件名未匹配 T-2,直接复用", new_name)
return new_path, False, covered_until
shutil.copy2(os.path.join(save_dir, newest), new_path)
config.logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s"
"(上轮积分日期推断为 %s)",
newest, new_name, covered_until or "未知")
return new_path, True, covered_until
+272
View File
@@ -0,0 +1,272 @@
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 积分工作簿各 sheet 写入与对比结果读取。
原则:openpyxl 只读写值区,模板公式(A 列圈人、K~AO 差值、AP~BT/BU~CY 镜像、SUBTOTAL)
一律不动;公式缓存值依赖 COM 全量重算(logic/recalc.py)。
"""
from datetime import date, datetime, timedelta
from .. import config
from .sheet_utils import (clean, delete_sheet_rows, existing_value, iter_rows_with_value,
scan_last_data_row, scan_last_formula_row, to_date, write_block)
def ensure_sheets(wb):
"""校验模板完整性:缺少任一必需工作表直接报错。"""
for name in config.ALL_SHEETS:
if name not in wb.sheetnames:
raise RuntimeError(f"目标文件缺少工作表「{name}」,请确认模板完整")
# ==================== 考勤统计报表 / 快照 / 对比结果 ====================
def write_report_sheet(wb, rows, year, month):
"""「考勤统计报表」:B2 月份标题 + B6 起写入全量行(B~AO 40 列),清旧尾部。"""
ws = wb[config.SHEET_REPORT]
ws["B2"] = f"{year}年{month:02d}月考勤统计报表"
old_last = scan_last_data_row(ws, 2, config.REPORT_DATA_START)
n = write_block(ws, config.REPORT_DATA_START, rows, col_start=2, old_last_row=old_last)
last_formula = scan_last_formula_row(ws, 1, config.REPORT_DATA_START)
if config.REPORT_DATA_START + n - 1 > last_formula:
config.logger.warning(
"考勤统计报表写入 %d 行超过 A 列公式预置行数(%d),超出行不会被圈人公式判定!"
"请在模板中下拉 A 列公式后重跑", n, last_formula - config.REPORT_DATA_START + 1)
config.logger.info("考勤统计报表写入 %d 行(原数据至第 %d 行),标题:%s",
n, old_last, ws["B2"].value)
return n
def copy_today_to_prev(wb):
"""「考勤-前一日导出」← 旧「考勤--今日导出」全量(A~AO 41 列原样平移)。"""
ws_src, ws_dst = wb[config.SHEET_TODAY], wb[config.SHEET_PREV]
old_last = scan_last_data_row(ws_src, 1, config.EXP_DATA_START)
# 只读取已存在的单元格,避免在空白行上凭空创建 Cell(大模板下会撑爆内存)
rows = [[existing_value(ws_src, r, c) for c in range(1, 42)]
for r in range(config.EXP_DATA_START, old_last + 1)]
dst_old_last = scan_last_data_row(ws_dst, 1, config.EXP_DATA_START)
write_block(ws_dst, config.EXP_DATA_START, rows, col_start=1, old_last_row=dst_old_last)
config.logger.info("考勤-前一日导出已更新为原今日导出快照:%d 行", len(rows))
return len(rows)
def select_report_rows(wb_values):
"""读「考勤统计报表」A 列="正确" 的行 → 40 列值列表,排除黑名单岗位。
read_only 模式必须走 iter_rows(随机 cell 访问会极慢)。
"""
ws = wb_values[config.SHEET_REPORT]
sel = []
for row in ws.iter_rows(min_row=config.REPORT_DATA_START, min_col=1, max_col=41,
values_only=True):
if row[0] is None or row[1] in (None, ""):
continue
if clean(row[0]) != "正确":
continue
data = list(row[1:41])
if clean(data[6]) in config.EXCLUDE_POSTS: # H 列岗位名称
continue
sel.append(data)
return sel
def write_today_export(wb, sel_rows):
"""「考勤--今日导出」:清空重写。报表 B~AO 40 列 → A~AN 40 列(技师工号落 H 列)。"""
ws = wb[config.SHEET_TODAY]
old_last = scan_last_data_row(ws, 1, config.EXP_DATA_START)
out = [list(row[:9]) + [row[9 + i] for i in range(31)] for row in sel_rows]
write_block(ws, config.EXP_DATA_START, out, col_start=1, old_last_row=old_last)
config.logger.info("考勤--今日导出写入 %d 行(原数据至第 %d 行)", len(out), old_last)
return len(out)
def write_compare_values(wb, sel_rows):
"""「对比结果」:今日导出行前 9 列(工号~姓名)→ B4 起 B~J 值区,旧超出行清空。"""
ws = wb[config.SHEET_CMP]
old_last = scan_last_data_row(ws, 2, config.CMP_DATA_START)
out = [list(row[:9]) for row in sel_rows]
n = write_block(ws, config.CMP_DATA_START, out, col_start=2, old_last_row=old_last)
last_formula = scan_last_formula_row(ws, 42, config.CMP_DATA_START) # AP 列镜像公式
if config.CMP_DATA_START + n - 1 > last_formula:
config.logger.warning(
"对比结果写入 %d 行超过公式预置行数(%d),超出行差值/镜像公式缺失!"
"请在模板中下拉 K~CY 列公式后重跑", n, last_formula - config.CMP_DATA_START + 1)
config.logger.info("对比结果写入 %d 行员工信息(原值区至第 %d 行)", n, old_last)
return n
def read_compare_results(wv, today, t2, gap_days=()):
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。
新增段 = T-2 + gap_days(上轮积分日期到 T-2 之间漏处理的日期),两者均按镜像列=2
全量取人;修正段 = 其余 [月首, T-3] 日期按差值 >0 补 / <0 删(gap_days 不参与差值,
否则「上次快照已有值但从未推送」的日期会因差值=0 被漏掉)。
"""
ws = wv[config.SHEET_CMP]
month_first = date(today.year, today.month, 1)
gap_days = sorted(d for d in (gap_days or ()) if month_first <= d < t2)
if t2 >= month_first:
full_days = gap_days + [t2]
else:
config.logger.warning("T-2(%s) 不在本月报表范围,跳过新增段(月初边缘场景属正常)", t2)
full_days = []
fix_end = t2 - timedelta(days=1)
gap_nums = {d.day for d in gap_days}
fix_days = []
if t2 >= month_first and fix_end >= month_first:
fix_days = [d for d in range(month_first.day, fix_end.day + 1) if d not in gap_nums]
new_rows, fix_rows, del_rows = [], [], []
for row in ws.iter_rows(min_row=config.CMP_DATA_START, min_col=1, max_col=72,
values_only=True):
info = list(row[1:10])
if clean(info[0]) == "":
continue
for d in full_days:
idx = 40 + d.day
if idx >= len(row):
continue
v = row[idx]
try:
if v not in (None, "") and abs(float(v) - 2) < 1e-9:
new_rows.append((info, d))
except (TypeError, ValueError):
pass
for d in fix_days:
idx = 9 + d
if idx >= len(row):
continue
v = row[idx]
if v in (None, ""):
continue
try:
diff = float(v)
except (TypeError, ValueError):
continue
fix_date = date(today.year, today.month, d)
if diff > 0:
fix_rows.append((info, fix_date))
elif diff < 0:
del_rows.append((info, fix_date))
new_rows.sort(key=lambda x: x[1])
fix_rows.sort(key=lambda x: x[1])
del_rows.sort(key=lambda x: x[1])
return new_rows, fix_rows, del_rows
# ==================== 积分导入 / 积分删除 ====================
def _clear_import_sheets(wb):
"""新批文件:清空积分导入/删除全部数据行。"""
for name in (config.SHEET_IMPORT, config.SHEET_DELETE):
ws = wb[name]
last = scan_last_data_row(ws, 2, config.IMP_DATA_START)
if last >= config.IMP_DATA_START:
ws.delete_rows(config.IMP_DATA_START, last - config.IMP_DATA_START + 1)
config.logger.info("%s 已清空(原数据至第 %d 行)", name, last)
def _gather_rows_to_delete(ws, today, t2, protected_dates):
"""收集「积分导入」需删除的行号(修正段旧行 + 同日新增段重跑幂等)。"""
month_first = date(today.year, today.month, 1)
t3 = t2 - timedelta(days=1)
row_nums = []
unknown = 0
for r, _code in iter_rows_with_value(ws, 2, config.IMP_DATA_START):
d = to_date(existing_value(ws, r, 11)) # K 积分日期
if d is None:
unknown += 1
continue
if d == t2:
row_nums.append(r)
elif month_first <= d <= t3 and d not in protected_dates:
row_nums.append(r)
if unknown:
config.logger.warning("积分导入存在 %d 行积分日期无法解析,已原样保留", unknown)
return row_nums
def write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_new_batch):
"""「积分导入」:删除旧修正段/同日新增段 → 追加新增段(在前)+ 修正段(按日期升序)。"""
ws = wb[config.SHEET_IMPORT]
if is_new_batch:
_clear_import_sheets(wb)
state.setdefault(file_key, {})["new_dates"] = []
protected = set(state.get(file_key, {}).get("new_dates", [])) | {t2 - timedelta(days=1)}
row_nums = _gather_rows_to_delete(ws, today, t2, protected)
removed = delete_sheet_rows(ws, row_nums)
last = scan_last_data_row(ws, 2, config.IMP_DATA_START)
out = [list(info) + [datetime(d.year, d.month, d.day)] for info, d in new_rows]
out += [list(info) + [datetime(d.year, d.month, d.day)] for info, d in fix_rows]
write_block(ws, last + 1, out, col_start=2, old_last_row=last)
for r in range(last + 1, last + 1 + len(out)):
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
dates = set(state.setdefault(file_key, {}).setdefault("new_dates", []))
for _info, d in new_rows: # 新增段含补漏日期,全部纳入历史保护
dates.add(d.isoformat())
if t2 >= date(today.year, today.month, 1):
dates.add(t2.isoformat())
state[file_key]["new_dates"] = sorted(dates)
new_dates_txt = "、".join(sorted({d.isoformat() for _info, d in new_rows})) or t2.isoformat()
config.logger.info(
"积分导入:删除旧行 %d(历史新增段保护日期 %s),追加新增段 %d 行(%s)+ 修正段 %d 行,现共 %d 行",
removed, state[file_key].get("new_dates") or "无", len(new_rows), new_dates_txt,
len(fix_rows), scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
return len(out)
def write_delete_sheet(wb, today, t2, del_rows):
"""「积分删除」:修正段全月刷新——删除 [月首, T-3] 旧行后按日期升序追加。"""
ws = wb[config.SHEET_DELETE]
month_first = date(today.year, today.month, 1)
t3 = t2 - timedelta(days=1)
row_nums = []
for r, _code in iter_rows_with_value(ws, 2, config.IMP_DATA_START):
d = to_date(existing_value(ws, r, 11))
if d is not None and month_first <= d <= t3:
row_nums.append(r)
removed = delete_sheet_rows(ws, row_nums)
last = scan_last_data_row(ws, 2, config.IMP_DATA_START)
out = [list(info) + [datetime(d.year, d.month, d.day)] for info, d in del_rows]
write_block(ws, last + 1, out, col_start=2, old_last_row=last)
for r in range(last + 1, last + 1 + len(out)):
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
config.logger.info("积分删除:删除旧行 %d,追加修正删行 %d 行,现共 %d 行",
removed, len(out),
scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
return len(out)
# ==================== 当月再入职名单 ====================
def write_rejoin_sheet(wb, rows):
"""「当月再入职名单」:按 H 再入职工号追加,已存在行不重写(人工维护字段不被覆盖)。"""
ws = wb[config.SHEET_REJOIN]
last = scan_last_data_row(ws, 2, config.REJOIN_DATA_START)
existing = set()
for r, code in iter_rows_with_value(ws, 8, config.REJOIN_DATA_START):
existing.add(clean(code))
out = []
for r in rows:
code = clean(r.get("hr_staff_base.base_code"))
if not code or code in existing:
continue
existing.add(code)
out.append([
clean(r.get("pt_staff_stru.DEPT_ORG_FOUR")),
clean(r.get("hr_staff_base.staff_name")),
"", # D 员工工号(人工维护)
"", # E 合计享受出勤积分天数(人工维护)
clean(r.get(f"{config.REJOIN_FIELD_PREFIX}.leave_date")),
clean(r.get(f"{config.REJOIN_FIELD_PREFIX}.join_date")),
code,
clean(r.get(f"{config.REJOIN_FIELD_PREFIX}.remark")),
])
if out:
n = write_block(ws, last + 1, out, col_start=2, old_last_row=last, col_count=8)
else:
n = 0
config.logger.info("当月再入职名单:新增 %d 行(原数据至第 %d 行,已存在 %d 人不重写)",
len(out), last, len(rows) - len(out))
return n