Files
37duAutomation/yingdao/XQ0011 考勤月报封存检查/working_days_shift_check.py
T
puddy 4923b352f2 refactor(yingdao/XQ0011): 重构考勤月报封存检查模块,拆分统一数据层
1.  新增seal_data_export.py统一处理考勤封存数据拉取、白名单筛选与导出
2.  移除unsealed_check.py与working_days_shift_check.py的直连接口逻辑,改为复用预处理数据
3.  统一XQ0007 OA社保申请导出筛选条件为ge(包含当月1号)并更新文档
4.  新增客服评价聚合分类需求文档
5.  移除闲置的XQ0011占位文档
6.  优化排班异常检查脚本,新增汇总群聊推送功能
2026-09-08 11:22:30 +08:00

292 lines
12 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-07
@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。)
输出:
在职天数排班异常_{月份}_{时间戳}.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.1.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 load_seal_rows # noqa: E402
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
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_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] = []
for code, rec in seal_map.items():
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
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({
"37工号": code,
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
"月报检查月份": ym,
"异常类型": ABNORMAL_TYPE,
"在职天数": wd,
"应勤工作日": int(work),
"休息天": int(rest),
"差值": diff,
"所属单位": _text(rec.get(SEAL_UNIT_FIELD)),
**{f"第{chn}级部门": _text(rec.get(f)) for chn, f in zip(
["一", "二", "三", "四", "五"], SEAL_DEPT_FIELDS)},
})
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
# 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()