344 lines
16 KiB
Python
344 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0033 插件 - 积分工作簿各 sheet 写入与对比结果读取。
|
||
|
||
原则:openpyxl 只读写值区,模板公式(A 列圈人、K~AO 差值、AP~BT/BU~CY 镜像、SUBTOTAL)
|
||
一律不动;公式缓存值依赖 COM 全量重算(logic/recalc.py)。
|
||
"""
|
||
import os
|
||
import re
|
||
from datetime import date, datetime, timedelta
|
||
|
||
import openpyxl
|
||
|
||
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)
|
||
|
||
_MONTH_RE = re.compile(r"(\d{4})\s*年\s*(\d{1,2})\s*月")
|
||
|
||
|
||
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 copy_file_today_to_prev(wb, src_path):
|
||
"""「考勤-前一日导出」← 上一轮批次文件(文件名积分日期段含 T-3)里的「考勤--今日导出」。
|
||
|
||
与 copy_today_to_prev(复制本文件旧快照)相比:本文件的快照可能已被上一轮/重跑改写,
|
||
而上轮文件按积分日期稳定可寻,同一天重跑时差值可复现(重跑幂等)。
|
||
源文件读不出(缺表 / 打不开)抛异常,由调用方退化为文件内快照平滚。
|
||
"""
|
||
src = openpyxl.load_workbook(src_path, data_only=True, read_only=True)
|
||
try:
|
||
if config.SHEET_TODAY not in src.sheetnames:
|
||
raise RuntimeError(f"源文件缺少工作表「{config.SHEET_TODAY}」")
|
||
rows = [list(row) for row in src[config.SHEET_TODAY].iter_rows(
|
||
min_row=config.EXP_DATA_START, min_col=1, max_col=41, values_only=True)]
|
||
finally:
|
||
src.close()
|
||
# 只保留有工号的行:模板尾部常有带格式的空行,拷贝过来无意义(镜像按工号 VLOOKUP)
|
||
while rows and clean(rows[-1][0]) == "":
|
||
rows.pop()
|
||
|
||
ws_dst = wb[config.SHEET_PREV]
|
||
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("考勤-前一日导出 ← 上轮文件 %s 的今日导出快照:%d 行",
|
||
os.path.basename(src_path), len(rows))
|
||
return len(rows)
|
||
|
||
|
||
def reset_snapshots(wb):
|
||
"""跨月首轮:清空「考勤--今日导出」「考勤-前一日导出」两份快照(保留表头与格式)。
|
||
|
||
快照只在本月批次内连续有效:上月 1~31 日列的数据与本月同日列毫无对应关系,
|
||
若照旧平移到前一日导出,对比结果 K~AO 差值会变成「本月 day N - 上月 day N」,
|
||
进而把本月应补的天数判成 0 差值(整段漏导入)、把上月出勤本月未出勤的天数
|
||
判成负差值(凭空生成积分删除行)。清空后前一日镜像恒为 0,
|
||
[月首, T-3] 差值 = 今日镜像 → 全部转为补导入,本月首轮自然补齐月头几天。
|
||
|
||
今日导出也一并清掉:它在后续步骤会被整体重写,但先清空可保证本轮若中途失败
|
||
重跑时,不会把上月快照再平移进前一日导出(重跑时今日导出只会有本月数据或为空)。
|
||
"""
|
||
for name in (config.SHEET_TODAY, config.SHEET_PREV):
|
||
ws = wb[name]
|
||
old_last = scan_last_data_row(ws, 1, config.EXP_DATA_START)
|
||
write_block(ws, config.EXP_DATA_START, [], col_start=1,
|
||
old_last_row=old_last, col_count=41)
|
||
config.logger.info("%s 已清空(跨月首轮,上一月快照不参与本月差值):原数据至第 %d 行",
|
||
name, old_last)
|
||
|
||
|
||
def read_report_month(wb):
|
||
"""读「考勤统计报表」B2 标题(如「2026年10月考勤统计报表」)里的月份 → (year, month)。
|
||
|
||
用于判断目标文件现存数据属于哪个月(跨月首轮要作废上一月的快照)。
|
||
读不出返回 None,由调用方按来源文件名推断的日期兜底。
|
||
"""
|
||
v = existing_value(wb[config.SHEET_REPORT], 2, 2)
|
||
if isinstance(v, (datetime, date)):
|
||
return v.year, v.month
|
||
m = _MONTH_RE.search(clean(v))
|
||
if not m:
|
||
return None
|
||
year, month = int(m.group(1)), int(m.group(2))
|
||
if not 1 <= month <= 12:
|
||
return None
|
||
return year, month
|
||
|
||
|
||
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, t2, gap_days=()):
|
||
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。
|
||
|
||
新增段 = T-2 + gap_days(上轮积分日期到 T-2 之间漏处理的日期),两者均按镜像列=2
|
||
全量取人;修正段 = 其余 [月首, T-3] 日期按差值 >0 补 / <0 删(gap_days 不参与差值,
|
||
否则「上次快照已有值但从未推送」的日期会因差值=0 被漏掉)。
|
||
|
||
月首一律取「积分日期 T-2 所在月」的 1 号(不是运行日所在月):每月 1、2 号运行时
|
||
T-2 落在上个月,工作簿日列对应的就是上月的 1~31 日,必须按上月窗口取数,
|
||
否则上月最后两天的新增段会被整段漏掉。
|
||
"""
|
||
ws = wv[config.SHEET_CMP]
|
||
month_first = date(t2.year, t2.month, 1)
|
||
gap_days = sorted(d for d in (gap_days or ()) if month_first <= d < t2)
|
||
full_days = gap_days + [t2]
|
||
fix_end = t2 - timedelta(days=1)
|
||
gap_nums = {d.day for d in gap_days}
|
||
fix_days = []
|
||
if 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(t2.year, t2.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, t2, protected_dates):
|
||
"""收集「积分导入」需删除的行号(修正段旧行 + 同日新增段重跑幂等)。"""
|
||
month_first = date(t2.year, t2.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, 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, 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())
|
||
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, t2, del_rows):
|
||
"""「积分删除」:修正段全月刷新——删除 [月首, T-3] 旧行后按日期升序追加。"""
|
||
ws = wb[config.SHEET_DELETE]
|
||
month_first = date(t2.year, t2.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
|