Files
37duAutomation/workflows/XQ0001-0100/XQ0011 考勤月报封存检查/monthly_report_check.py
T
puddy d1af551eac chore: 清理废弃插件与冗余文档,重构项目目录结构
1.  删除旧版xq0031_xq0032插件的冗余UI源码与配置文件
2.  迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录
3.  清理过期的需求列表、评分文档与流程底稿
4.  更新.gitignore匹配规则,适配新的目录结构
2026-09-21 16:59:05 +08:00

233 lines
8.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@FileName: monthly_report_check.py
@Author: 小布丁
@CreateTime: 2026-09-21
@UpdateTime: 2026-09-21
@Description: 考勤月报封存检查 - 汇总执行与单工作簿输出(影刀单文件,自包含)。
依次运行检查1~检查6,将各异常名单合并写入一个 Excel 工作簿(每个检查一个 sheet),
并生成「汇总」sheet 概览各检查异常人数。各检查模块仍保留独立输出文件,便于单独排查。
运行前置:需先运行「seal_data_export.py」导出当月预处理封存表,并完成
「37du花名册导出」「37du调动台账导出」(统一输出到 D:\\资料\\人资\\考勤月报封存检查)。
输出:
考勤月报封存检查_{月份}_{时间戳}.xlsx 单工作簿(汇总 + 检查1~6 共 7 个 sheet)
环境变量(可选):
monthly_report_save_dir 汇总工作簿输出目录(默认 D:\\资料\\人资\\考勤月报封存检查)
@Version: 1.0.0
"""
# ==================== 标准库导入 ====================
import os
import sys
import traceback
from datetime import date, datetime
from typing import Callable, Dict, List, Optional, Tuple
# ==================== 同目录模块引入(各检查模块,复用其 run_* 与输出列定义) ====================
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from working_days_shift_check import ( # noqa: E402
run_working_days_shift_check, OUTPUT_COLUMNS as COL_CHECK1,
)
from attendance_rest_check import ( # noqa: E402
run_attendance_rest_check, OUTPUT_COLUMNS as COL_CHECK2,
)
from latest_seal_check import ( # noqa: E402
run_latest_seal_check, OUTPUT_COLUMNS as COL_CHECK3,
)
from full_attendance_check import ( # noqa: E402
run_full_attendance_check, OUTPUT_COLUMNS as COL_CHECK4,
)
from unsealed_check import ( # noqa: E402
run_unsealed_check, OUTPUT_COLUMNS as COL_CHECK5,
)
from overtime_compensation_check import ( # noqa: E402
run_overtime_compensation_check, OUTPUT_COLUMNS as COL_CHECK6,
)
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
try:
from dotenv import load_dotenv
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
f"缺失依赖详情: {_import_err}"
)
load_dotenv()
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
class _PrintLogger:
@staticmethod
def debug(msg, *args):
if args:
msg = msg % args
print(f"[DEBUG] {msg}")
@staticmethod
def info(msg, *args):
if args:
msg = msg % args
print(f"[INFO] {msg}")
@staticmethod
def warning(msg, *args):
if args:
msg = msg % args
print(f"[WARN] {msg}")
@staticmethod
def error(msg, *args):
if args:
msg = msg % args
print(f"[ERROR] {msg}")
logger = _PrintLogger()
# ==================== 共享路径 & 常量配置 ====================
SAVE_DIR = os.getenv("monthly_report_save_dir") or r"D:\资料\人资\考勤月报封存检查"
# 检查元信息:(编号, sheet 名, 异常类型标签, run 函数, 输出列)
CHECK_META: List[Tuple[str, str, str, Callable, List[str]]] = [
("检查1", "检查1-在职天数排班异常", "在职天数 ≠ 应勤工作日 + 休息天",
run_working_days_shift_check, COL_CHECK1),
("检查2", "检查2-出勤及排休天数异常", "出勤/正休天数与应勤天标准不符",
run_attendance_rest_check, COL_CHECK2),
("检查3", "检查3-封存非最新值", "考勤封存非最新值,请重新封存",
run_latest_seal_check, COL_CHECK3),
("检查4", "检查4-全勤验证异常", "晋升当月要求全勤 / 迟到早退",
run_full_attendance_check, COL_CHECK4),
("检查5", "检查5-未封存名单", "考勤月报未封存,请处理",
run_unsealed_check, COL_CHECK5),
("检查6", "检查6-延时加班异常", "经营系管理岗不应享受延时加班,请核对",
run_overtime_compensation_check, COL_CHECK6),
]
# ==================== 通用工具 ====================
def _prev_month(year: int, month: int) -> Tuple[int, int]:
if month == 1:
return year - 1, 12
return year, month - 1
def _normalize_month(month) -> str:
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
if not month:
py, pm = _prev_month(date.today().year, date.today().month)
return f"{py:04d}-{pm:02d}"
s = str(month).strip()
if len(s) == 6 and s.isdigit():
return f"{s[:4]}-{s[4:]}"
return s
def sys_argv_if(idx):
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
return sys.argv[idx] if len(sys.argv) > idx else None
# ==================== 主流程 ====================
def run_all_checks(month: str = None) -> Dict[str, object]:
"""依次运行检查1~6,返回各检查异常名单行列表(每项含编号/sheet/类型/行列表)。"""
ym = _normalize_month(month)
logger.info("===== 考勤月报封存检查(汇总)月份:%s =====", ym)
results: List[dict] = []
total = 0
for no, sheet_name, label, run_fn, _cols in CHECK_META:
try:
rows = run_fn(month=ym)
except Exception as e:
logger.error("%s 执行失败:%s\n%s", no, e, traceback.format_exc())
rows = []
results.append({
"no": no,
"sheet_name": sheet_name,
"label": label,
"rows": rows,
})
total += len(rows)
logger.info("%s 完成:异常 %d 人", no, len(rows))
return {"ym": ym, "results": results, "total": total}
def write_workbook(result: Dict[str, object]) -> str:
"""将各检查异常名单写入单工作簿(汇总 + 每检查一个 sheet)。"""
ym = result["ym"]
os.makedirs(SAVE_DIR, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = os.path.join(SAVE_DIR, f"考勤月报封存检查_{ym}_{ts}.xlsx")
# 汇总 sheet 行
summary_rows = [{
"序号": i + 1,
"检查编号": it["no"],
"异常类型": it["label"],
"异常人数": len(it["rows"]),
} for i, it in enumerate(result["results"])]
summary_rows.append({
"序号": len(summary_rows) + 1,
"检查编号": "合计",
"异常类型": "",
"异常人数": result["total"],
})
try:
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
pd.DataFrame(summary_rows).to_excel(
writer, sheet_name="汇总", index=False)
for it, (_, _, _, _, cols) in zip(result["results"], CHECK_META):
rows = it["rows"]
sheet_name = it["sheet_name"]
if not rows:
# 空结果也保留 sheet,便于人工核对
pd.DataFrame(columns=cols).to_excel(
writer, sheet_name=sheet_name, index=False)
continue
pd.DataFrame(rows, columns=cols).to_excel(
writer, sheet_name=sheet_name, index=False)
except PermissionError:
raise RuntimeError(
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
logger.info("汇总工作簿已保存:%s(共 %d 人异常)", save_path, result["total"])
return save_path
def main(args=None) -> dict:
"""影刀「调用模块」入口;也可作为脚本直接运行。
args: dict,可选字段:month("YYYY-MM",默认上月)。
"""
if args is None:
args = {}
month = args.get("month") or os.getenv("monthly_report_month") or (sys_argv_if(2))
try:
result = run_all_checks(month)
save_path = write_workbook(result)
logger.info("=" * 60)
logger.info("【考勤月报封存检查汇总完成】")
logger.info(" 检查月份:%s | 异常总人数:%d", result["ym"], result["total"])
logger.info(" 汇总工作簿:%s", save_path)
logger.info(" 各检查异常人数:%s", "、".join(
f"{it['no']}:{len(it['rows'])}" for it in result["results"]))
logger.info("=" * 60)
return {"success": True, "count": result["total"],
"detail": {it["no"]: len(it["rows"]) for it in result["results"]},
"path": save_path}
except Exception as e:
if "正被占用" in str(e):
logger.error("=========== 提醒 ===========")
logger.error(str(e))
return {"success": False, "message": str(e)}
logger.error("汇总检查执行失败:%s\n%s", e, traceback.format_exc())
return {"success": False, "message": str(e)}
if __name__ == "__main__":
main()