Files
37duAutomation/workflows/XQ0001-0100/XQ0011 考勤月报封存检查/working_days_shift_check.py
T
puddy dbb05e6ab3 feat(electron-shell): 启动链路修复与执行/配置收口插件侧
- 启动链路 P1-P7 修复:预算对齐、完成事件推送、端口占用提示、前端阶段文案接管
- 静态缓存按 IS_FROZEN 区分开发/打包态,bootPhaseOwned 竞态修复
- 一键执行与参数配置统一收口到插件界面,定时任务引用 config_id
- 环境包迁移到 %LOCALAPPDATA%\37duAutomation\python-env,重装零解压
- shell-updater:缓存包 sha256 校验、静默升级后自动拉起新版、自动清理旧安装包
- after-pack 钩子生成 shell.version 修复打包态版本识别
- 插件 xq0031/xq0045 迁移至 plugins/XQ0001-0100/ 号段分桶中文目录
2026-09-28 14:20:35 +08:00

315 lines
14 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: working_days_shift_check.py
@Author: 小布丁
@CreateTime: 2026-08-31
@UpdateTime: 2026-09-24
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
保存为固定路径 考勤封存数据_{月份}.xlsx。
- 本模块只读取该预处理封存表,不再直连接口。
- 每员工一条封存记录,检查1用到的字段(aa.md 列定义):
base_code 工号 / staff_name 姓名
join_date 入职日期 / leaveOffice_date 离职时间(算在职天数)
kq_stat_month_yq_work_day_in 在职应勤工作日
kq_stat_cal_ext9 休息天(考勤日报休息日天数总和)
BELONG_UNIT_ORG_NAME 所属单位 / DEPT_ORG_ONE~FIVE 一级~五级部门
判断口径(对应需求文档 XQ0011 检查1):
- 在职天数:由封存「入职/离职时间」计算员工当月应在职的自然天数;
- 在职应勤工作日 + 休息天:直接取封存字段 kq_stat_month_yq_work_day_in / kq_stat_cal_ext9;
- 差值 = 在职天数 - (应勤工作日 + 休息天);差值非 0 视为异常,异常类型 = 「当月在职天数有差缺排班」。
样例:37035483 8-3 离职,在职天数 3;应勤 3、休息 0 → 差值 0 正常。
在职天数口径(统一采用「月初1日~末日」与「入职日起~离职日止」闭区间交集的自然天数,含首尾)
- 全月在职:月初1日即已在职且当月末在职 → 在职天数 = 当月自然天数;
- 月初1日在职、当月内离职:在职天数 = 离职日 - 1号 + 1 → 覆盖需求「离职时间 - 1号」;
- 月初1日尚未入职、月末在职:在职天数 = 末日 - 入职日 + 1 → 覆盖需求「末日 - 入职时间」;
- 当月在册(月初未入职且月内离职):在职天数 = 离职日 - 入职日 + 1 → 覆盖需求「离职 - 入职」;
- 月初1日与末日均在职但有入离职异动:在职天数 = 自然天数 - 异动缺勤段。
(注:口径与封存样例一致,均含入职/离职当天。若贵司某类口径不含离职/入职当天,请调 _working_days。)
离职时间来源(优先级):
- 首选:考勤封存的离职日期(leaveOffice_date)——封存为按月统计快照,能反映当月离职;
- 兜底:花名册离职时间(按工号查 员工花名册.xlsx 的「离职时间」列)——仅封存缺离职时间时使用。
(花名册为当前快照,离职后重新入职者其离职时间会被刷新清空,故不可作为首选。)
输出:
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含岗位/入职时间/离职时间/在职天数/应勤/休息/差值便于排查)。
依赖安装(启动校验:必须预先装齐):
pip install requests pandas openpyxl python-dotenv
运行前置:
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
环境变量(可选):
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
@Version: 1.3.0
"""
# ==================== 标准库导入 ====================
import os
import sys
import traceback
from datetime import date, datetime
from typing import Dict, List, Optional, Tuple
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from seal_data_export import ( # noqa: E402
enrich_dept_fields,
load_roster_dept_map,
load_seal_rows,
)
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
try:
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
class _PrintLogger:
def debug(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def info(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def warning(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def exception(self, msg, *args, **kwargs):
print(msg % args if args else msg)
traceback.print_exc()
logger = _PrintLogger()
# ==================== 共享路径 & 常量配置 ====================
SAVE_DIR = os.getenv("monthly_wd_save_dir") or r"D:\资料\人资\考勤月报封存检查"
# 异常类型(对应需求文档检查1)
ABNORMAL_TYPE = "当月在职天数有差缺排班"
# 封存记录的字段→角色映射(字段名以 aa.md 接口列定义为准)
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
SEAL_NAME_FIELD = "staff_name"
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
SEAL_POST_FIELD = "POST_ALIAS_NAME" # aa.md:岗位
ROSTER_LEAVE_FIELD = "离职时间" # 花名册:离职时间(封存缺离职时间时的兜底来源)
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天(考勤日报休息日天数总和)
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
SEAL_DEPT_FIELDS = ["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"] # 一~五级部门
# 输出列(对应需求文档检查1输出字段;岗位由花名册回填,入职/离职时间为计算采用值)
OUTPUT_COLUMNS = [
"37工号", "姓名", "岗位", "入职时间", "离职时间", "月报检查月份", "异常类型",
"在职天数", "应勤工作日", "休息天", "差值",
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
]
# ==================== 通用工具 ====================
def _clean(v) -> str:
if v is None:
return ""
if pd.isna(v):
return ""
s = str(v).strip()
if s.lower() in ("nan", "none", "nat"):
return ""
return s
def _text(v) -> str:
t = _clean(v)
if t.endswith(".0"):
t = t[:-2]
return t
def _num(v) -> float:
try:
return float(_clean(v))
except (TypeError, ValueError):
return 0.0
def _parse_date(v) -> Optional[date]:
s = _clean(v)
if not s:
return None
s = s[:10]
try:
return datetime.strptime(s, "%Y-%m-%d").date()
except (TypeError, ValueError):
return None
def _prev_month(year: int, month: int) -> Tuple[int, int]:
if month == 1:
return year - 1, 12
return year, month - 1
def _month_range(ym: str) -> Tuple[date, date]:
y, m = int(ym[:4]), int(ym[5:7])
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
return date(y, m, 1), date(y, m, total_days)
def _working_days(first: date, last: date, join: Optional[date], leave: Optional[date]) -> int:
"""计算员工当月在职自然天数(月区间 ∩ 在职区间闭区间,含首尾)。"""
lo = first if not join else (join if join >= first else first)
hi = last if not leave else (leave if leave <= last else last)
if lo > hi:
return 0
return (hi - lo).days + 1
# ==================== 主流程 ====================
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
"""按工号建立 封存记录索引(一员工一条)。"""
mapping: Dict[str, dict] = {}
for rec in rows:
code = ""
for f in SEAL_CODE_FIELDS:
code = _text(rec.get(f))
if code:
break
if code:
mapping.setdefault(code, rec)
return mapping
def run_working_days_shift_check(month: str = None) -> List[dict]:
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表(并写 Excel 留档)。
Args:
month: 检查月份 "YYYY-MM",默认上月。
Returns:
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
"""
today = date.today()
if month:
try:
first, last = _month_range(month)
except (ValueError, IndexError, TypeError):
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
ym = month
else:
py, pm = _prev_month(today.year, today.month)
first, last = _month_range(f"{py:04d}-{pm:02d}")
ym = f"{py:04d}-{pm:02d}"
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
seal_rows = load_seal_rows(ym)
if not seal_rows:
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
seal_map = _build_seal_map(seal_rows)
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
# 2. 逐人检查
abnormal: List[dict] = []
roster_map = None
leave_from_roster = 0
for code, rec in seal_map.items():
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
# 离职时间口径:考勤封存优先;封存缺离职时间时用花名册兜底。
# (花名册为当前快照,离职后重新入职者无离职时间,故仅作兜底、不作首选)
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
if leave is None:
if roster_map is None:
roster_map = load_roster_dept_map()
roster_info = roster_map.get(code) or {}
leave = _parse_date(roster_info.get(ROSTER_LEAVE_FIELD))
if leave is not None:
leave_from_roster += 1
wd = _working_days(first, last, join, leave)
if wd <= 0:
continue # 当月无在职日,跳过
work = _num(rec.get(SEAL_WORK_FIELD))
rest = _num(rec.get(SEAL_REST_FIELD))
diff = wd - (work + rest)
if diff != 0:
abnormal.append(enrich_dept_fields({
"37工号": code,
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
"入职时间": join.isoformat() if join else "",
"离职时间": leave.isoformat() if leave else "",
"月报检查月份": ym,
"异常类型": ABNORMAL_TYPE,
"在职天数": wd,
"应勤工作日": int(work),
"休息天": int(rest),
"差值": diff,
}, code, rec))
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
if leave_from_roster:
logger.info("其中 %d 人离职时间由花名册兜底(封存未提供离职时间)", leave_from_roster)
# 3. 导出异常名单
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")
try:
pd.DataFrame(abnormal if abnormal else [],
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
except PermissionError:
raise RuntimeError(
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
return abnormal
def main(args=None) -> dict:
"""影刀「调用模块」入口;也可作为脚本直接运行。
args: dict,可选字段:month("YYYY-MM",默认上月)。
"""
if args is None:
args = {}
month = args.get("month") or os.getenv("monthly_wd_month") or (sys_argv_if(2))
try:
rows = run_working_days_shift_check(month)
logger.info("=" * 60)
logger.info("【检查1 在职天数是否均排班验证完成】")
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
logger.info(" 输出目录:%s", SAVE_DIR)
logger.info("=" * 60)
return {"success": True, "count": len(rows)}
except Exception as e:
logger.error("检查1执行失败:%s", e)
return {"success": False, "message": str(e)}
def sys_argv_if(idx):
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
return sys.argv[idx] if len(sys.argv) > idx else None
if __name__ == "__main__":
main()