新增考勤月报封存检查的完整校验逻辑: 1. 新增延时加班验证脚本,检查经营系管理岗违规领取延时加班补贴 2. 新增全勤验证脚本,校验月中晋升及异常考勤仍标记全勤的情况 3. 新增封存值最新校验脚本,对比封存数据与实时统计数据差异 4. 新增出勤排休验证脚本,校验出勤天数和休息天数是否符合排班方案 5. 更新aa.md文档,补充全部6项检查规则和接口说明 6. 删除冗余的aa.json测试文件
469 lines
19 KiB
Python
469 lines
19 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: attendance_rest_check.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-09-18
|
||
@Description: 考勤月报封存检查 - 检查2「出勤及排休天数验证」(影刀单文件,自包含)。
|
||
根据排班方案关联的应勤天方案:
|
||
实际出勤天不能超过应勤天;
|
||
正休不能超过标准“当月天数-应勤天”。
|
||
命中任一即输出异常名单。
|
||
|
||
数据来源:
|
||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表。
|
||
用到的封存字段:
|
||
kq_stat_cal_ext19 实际出勤天日
|
||
kq_stat_cal_ext9 休息天(正休)
|
||
2) 排班数据:rf_p_kq_count_SelectBanci(不传工号 = 全集团批量返回),每条记录
|
||
带逐日 {日期}_team_name(班组/方案名,如"集团本部职能(单双休+法定)");
|
||
一个员工当月取「出现次数最多的 team_name」(换方案口径)。
|
||
3) 应勤天方案:getPageAjax/sql_kq_team_minyq_plan(aa.md 提供),每个方案带
|
||
plan_name(如"职能人员出勤方案(单双休+法定)")与 month_01~12 各月应勤天。
|
||
team_name ↔ plan_name 按「括号内特征」匹配(如 单双休+法定 / 固休4天 / 固休)。
|
||
已按 aa.json 样例验证:李丹丹 team_name"集团本部职能(单双休+法定)"匹配
|
||
z-1"职能人员出勤方案(单双休+法定)",month_09=23,与排班 total_day=23 一致。
|
||
|
||
输出:
|
||
出勤排休验证异常_{月份}_{时间戳}.xlsx 异常名单(含 应勤天/实际出勤天/正休/标准 便于排查)。
|
||
|
||
依赖安装(启动校验:必须预先装齐):
|
||
pip install requests pandas openpyxl python-dotenv
|
||
|
||
运行前置:
|
||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json),
|
||
本模块运行时直连 排班接口 + 应勤天方案接口 拉取实时数据。
|
||
|
||
环境变量(可选):
|
||
monthly_arc_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||
@Version: 1.0.0
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
import traceback
|
||
from collections import Counter
|
||
from datetime import date, datetime
|
||
from typing import Dict, List, Optional, Tuple
|
||
|
||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理 + HR 会话,本模块复用)
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
from seal_data_export import ( # noqa: E402
|
||
SHARED_HR_COOKIE_FILE, HR_BASE_URL, GET_CUR_USER_INFO_URL,
|
||
PAGE_MAX_SIZE, HRSessionExpiredError,
|
||
build_hr_session, hr_request_json, fetch_cur_user_info,
|
||
_relogin_get_user_id, _clean, load_seal_rows,
|
||
)
|
||
|
||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||
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_arc_save_dir") or r"D:\资料\人资\考勤异常"
|
||
|
||
# 排班接口(aa.json 样例:一条记录 = 一个员工在查询范围内的全部排班,逐日带 {日期}_team_name)
|
||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||
SHIFT_SQL_ID = "kq_count_SelectBanci"
|
||
|
||
# 应勤天方案接口(aa.md 提供;aa.json 为返回样例:datas 每条含 plan_name + month_01~12)
|
||
PLAN_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/sql_kq_team_minyq_plan/CoreRequest.mc"
|
||
PLAN_SQL = "sql_kq_team_minyq_plan"
|
||
|
||
# 异常类型
|
||
ABNORMAL_TYPE_OVER_WORK = "出勤天数超过应勤天"
|
||
ABNORMAL_TYPE_OVER_REST = "正休天数超过标准"
|
||
|
||
# 封存字段(aa.md 列定义)
|
||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||
SEAL_ACTUAL_WORK_FIELD = "kq_stat_cal_ext19" # 实际出勤天日
|
||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # 休息天(正休)
|
||
|
||
# 输出列(对应需求文档异常名单字段,附 应勤天/实际出勤天/正休/标准 便于排查)
|
||
OUTPUT_COLUMNS = [
|
||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||
"应勤天", "实际出勤天", "正休", "正休标准", "异常明细",
|
||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||
]
|
||
|
||
|
||
# ==================== 通用工具 ====================
|
||
def _num(v) -> float:
|
||
try:
|
||
return float(_clean(v))
|
||
except (TypeError, ValueError):
|
||
return 0.0
|
||
|
||
|
||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||
if month == 1:
|
||
return year - 1, 12
|
||
return year, month - 1
|
||
|
||
|
||
def _month_days(ym: str) -> int:
|
||
y, m = int(ym[:4]), int(ym[5:7])
|
||
return pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||
|
||
|
||
def _plan_feature(name: str) -> str:
|
||
"""提取方案/班组名括号内特征(如"集团本部职能(单双休+法定)"→"单双休+法定")。"""
|
||
name = _clean(name)
|
||
if not name:
|
||
return ""
|
||
# 取最后一个括号(半角/全角均可)
|
||
m = re.search(r"[((]([^))]+)[))]\s*$", name)
|
||
return m.group(1).strip() if m else name
|
||
|
||
|
||
# ==================== 应勤天方案接口(getPageAjax/sql_kq_team_minyq_plan) ====================
|
||
def fetch_plan_page(session, year, page_no=1, page_size=100):
|
||
"""请求单页应勤天方案。datas 每条含 plan_name/plan_code/month_01~12(各月应勤天)。"""
|
||
params = {
|
||
"in_use": "",
|
||
"start": str((page_no - 1) * page_size),
|
||
"sortType": "desc",
|
||
"sortName": "operate_time",
|
||
"pageNo": page_no,
|
||
"pageSize": page_size,
|
||
"struTreeCode": "cq37du",
|
||
"root_id": "cq37du",
|
||
"belong_year": str(year),
|
||
"is_show_parent": "0",
|
||
"commonQuery": "[]",
|
||
"plan_name": "",
|
||
}
|
||
return hr_request_json(session, "POST", PLAN_URL, params, "应勤天方案")
|
||
|
||
|
||
def fetch_all_plans(session, year: int) -> List[dict]:
|
||
"""分页抓取指定年份全部应勤天方案。"""
|
||
all_rows: List[dict] = []
|
||
page_no = 1
|
||
while True:
|
||
try:
|
||
data = fetch_plan_page(session, year, page_no, 100)
|
||
except HRSessionExpiredError:
|
||
logger.warning("应勤天方案登录态过期,自动补登录后续抓")
|
||
session, user_id = _relogin_get_user_id()
|
||
data = fetch_plan_page(session, year, page_no, 100)
|
||
if data.get("state") != "1":
|
||
logger.error("应勤天方案第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||
break
|
||
page_list = data.get("datas", []) or []
|
||
if not page_list:
|
||
logger.info("应勤天方案无更多数据")
|
||
break
|
||
all_rows.extend(page_list)
|
||
total_page = data.get("pageCount", 0)
|
||
logger.info("应勤天方案已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||
if page_no >= total_page:
|
||
break
|
||
page_no += 1
|
||
time.sleep(0.2)
|
||
return all_rows
|
||
|
||
|
||
# ==================== 排班接口(rf_p_kq_count_SelectBanci,不传工号 = 全集团批量) ====================
|
||
def fetch_shift_page(session, user_id, begin_date, end_date,
|
||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||
"""请求单页全集团排班数据(base_code 留空 = 不过滤,返回全部员工当月排班)。"""
|
||
params = {
|
||
"treecode": treecode,
|
||
"user_id": user_id,
|
||
"sqlId": SHIFT_SQL_ID,
|
||
"commonQuery": "",
|
||
"commonQueryStr": "",
|
||
"staff_ids": "",
|
||
"person_status": "1,4",
|
||
"post_no": "",
|
||
"post_type": "1",
|
||
"post_level": "",
|
||
"identity": "",
|
||
"showType": "1",
|
||
"dateType": "1",
|
||
"begin": begin_date,
|
||
"end": end_date,
|
||
"bc_date": begin_date,
|
||
"base_code": "",
|
||
"staff_name": "",
|
||
"start": str((page_no - 1) * page_size),
|
||
"sortType": "",
|
||
"sortName": "",
|
||
"pageNo": page_no,
|
||
"pageSize": page_size,
|
||
}
|
||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||
|
||
|
||
def fetch_all_shift(session, user_id, begin_date, end_date) -> List[dict]:
|
||
"""分页抓取全集团当月排班数据(登录态失效自动补登后续抓)。"""
|
||
all_rows: List[dict] = []
|
||
page_no = 1
|
||
while True:
|
||
try:
|
||
data = fetch_shift_page(session, user_id, begin_date, end_date,
|
||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||
except HRSessionExpiredError:
|
||
logger.warning("排班登录态过期,自动补登录后续抓")
|
||
session, user_id = _relogin_get_user_id()
|
||
data = fetch_shift_page(session, user_id, begin_date, end_date,
|
||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||
if data.get("state") != "1":
|
||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||
break
|
||
page_list = data.get("datas", []) or []
|
||
if not page_list:
|
||
logger.info("排班无更多数据")
|
||
break
|
||
all_rows.extend(page_list)
|
||
total_page = data.get("pageCount", 0)
|
||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||
if page_no >= total_page:
|
||
break
|
||
page_no += 1
|
||
time.sleep(0.2)
|
||
return all_rows
|
||
|
||
|
||
def _staff_main_team(row: dict) -> str:
|
||
"""统计单条排班记录内逐日 {日期}_team_name 出现最多的值(换方案口径:取当月出现最多的)。"""
|
||
counter: Counter = Counter()
|
||
for key, val in row.items():
|
||
if isinstance(key, str) and key.endswith("_team_name"):
|
||
name = _clean(val)
|
||
if name and name != "休息":
|
||
counter[name] += 1
|
||
if not counter:
|
||
return ""
|
||
return counter.most_common(1)[0][0]
|
||
|
||
|
||
# ==================== 主流程 ====================
|
||
def _build_abnormal(code: str, rec: dict, ym: str, abnormal_type: str,
|
||
detail: str, extra: Dict[str, object]) -> dict:
|
||
"""构造异常名单行(统一字段)。"""
|
||
row = {
|
||
"37工号": code,
|
||
"姓名": _clean(rec.get("staff_name")),
|
||
"月报检查月份": ym,
|
||
"异常类型": abnormal_type,
|
||
"应勤天": extra.get("yq_day", ""),
|
||
"实际出勤天": extra.get("actual_day", ""),
|
||
"正休": extra.get("rest_day", ""),
|
||
"正休标准": extra.get("rest_standard", ""),
|
||
"异常明细": detail,
|
||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||
}
|
||
for chn, f in zip(
|
||
["一", "二", "三", "四", "五"],
|
||
["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"]):
|
||
row[f"第{chn}级部门"] = _clean(rec.get(f))
|
||
return row
|
||
|
||
|
||
def run_attendance_rest_check(month: str = None) -> List[dict]:
|
||
"""执行检查2「出勤及排休天数验证」,返回异常名单行列表(并写 Excel 留档)。
|
||
|
||
Args:
|
||
month: 检查月份 "YYYY-MM",默认上月。
|
||
|
||
Returns:
|
||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||
"""
|
||
today = date.today()
|
||
if month:
|
||
try:
|
||
month_days = _month_days(month)
|
||
except (ValueError, IndexError, TypeError):
|
||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||
ym = month
|
||
else:
|
||
py, pm = _prev_month(today.year, today.month)
|
||
ym = f"{py:04d}-{pm:02d}"
|
||
month_days = _month_days(ym)
|
||
year = int(ym[:4])
|
||
begin_date = f"{ym}-01"
|
||
end_date = f"{ym}-{month_days:02d}"
|
||
logger.info("===== 检查2「出勤及排休天数验证」月份:%s(%s ~ %s,自然天数 %d) =====",
|
||
ym, begin_date, end_date, month_days)
|
||
|
||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||
seal_rows = load_seal_rows(ym)
|
||
if not seal_rows:
|
||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||
seal_map: Dict[str, dict] = {}
|
||
for rec in seal_rows:
|
||
code = ""
|
||
for f in SEAL_CODE_FIELDS:
|
||
code = _clean(rec.get(f))
|
||
if code:
|
||
break
|
||
if code:
|
||
seal_map.setdefault(code, rec)
|
||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||
|
||
# 2. 拉取应勤天方案(plan_name → 当月应勤天)
|
||
session = build_hr_session()
|
||
user_id = _clean(fetch_cur_user_info(session).get("userId")) # 登录态校验 + 取 user_id(排班接口复用)
|
||
if not user_id:
|
||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||
plans = fetch_all_plans(session, year)
|
||
if not plans:
|
||
raise RuntimeError(f"未拉取到 {year} 年应勤天方案,请确认方案接口已配置。")
|
||
# 特征 → {plan_name, yq_day}
|
||
plan_by_feature: Dict[str, dict] = {}
|
||
for plan in plans:
|
||
feature = _plan_feature(_clean(plan.get("plan_name")))
|
||
if not feature:
|
||
continue
|
||
yq_day = _num(plan.get(f"month_{ym[5:7]:>02}"))
|
||
if yq_day > 0:
|
||
plan_by_feature[feature] = {
|
||
"plan_name": _clean(plan.get("plan_name")),
|
||
"plan_code": _clean(plan.get("plan_code")),
|
||
"yq_day": yq_day,
|
||
}
|
||
logger.info("应勤天方案加载完成:%d 条,命中特征 %d 个(%s)",
|
||
len(plans), len(plan_by_feature), ym)
|
||
|
||
# 3. 拉取全集团排班 → 工号 → 当月出现最多的 team_name
|
||
shift_rows = fetch_all_shift(session, user_id, begin_date, end_date)
|
||
staff_team: Dict[str, str] = {}
|
||
no_team_cnt = 0
|
||
for row in shift_rows:
|
||
code = _clean(row.get("base_code"))
|
||
if not code:
|
||
continue
|
||
team = _staff_main_team(row)
|
||
if not team:
|
||
no_team_cnt += 1
|
||
continue
|
||
staff_team[code] = team
|
||
logger.info("排班加载完成:%d 人带方案,%d 人无方案(跳过)", len(staff_team), no_team_cnt)
|
||
|
||
# 4. 逐人校验:实际出勤天≤应勤天;正休≤当月天数-应勤天
|
||
abnormal: List[dict] = []
|
||
no_plan_match = 0
|
||
for code, rec in seal_map.items():
|
||
team = staff_team.get(code)
|
||
if not team:
|
||
continue # 排班无方案(无排班/全休息),跳过不误报
|
||
feature = _plan_feature(team)
|
||
plan = plan_by_feature.get(feature)
|
||
if not plan:
|
||
no_plan_match += 1
|
||
logger.debug("工号 %s 方案「%s」未匹配到应勤天方案特征,跳过", code, team)
|
||
continue
|
||
yq_day = plan["yq_day"]
|
||
actual_day = _num(rec.get(SEAL_ACTUAL_WORK_FIELD))
|
||
rest_day = _num(rec.get(SEAL_REST_FIELD))
|
||
rest_standard = month_days - yq_day
|
||
plan_desc = f"{plan['plan_code']} {plan['plan_name']}(特征「{feature}」)"
|
||
if actual_day > yq_day:
|
||
abnormal.append(_build_abnormal(
|
||
code, rec, ym, ABNORMAL_TYPE_OVER_WORK,
|
||
f"排班方案{plan_desc},应勤天{yq_day:g},实际出勤{actual_day:g},超出{actual_day - yq_day:g}天",
|
||
{"yq_day": yq_day, "actual_day": actual_day,
|
||
"rest_day": rest_day, "rest_standard": rest_standard}))
|
||
if rest_day > rest_standard:
|
||
abnormal.append(_build_abnormal(
|
||
code, rec, ym, ABNORMAL_TYPE_OVER_REST,
|
||
f"排班方案{plan_desc},正休{rest_day:g}天超过标准{rest_standard:g}天(当月{month_days}天-应勤{yq_day:g}天),超出{rest_day - rest_standard:g}天",
|
||
{"yq_day": yq_day, "actual_day": actual_day,
|
||
"rest_day": rest_day, "rest_standard": rest_standard}))
|
||
logger.info("检查2 校验完成:异常 %d 条,方案未匹配跳过 %d 人",
|
||
len(abnormal), no_plan_match)
|
||
|
||
# 5. 导出异常名单
|
||
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_arc_month") or sys_argv_if(2)
|
||
try:
|
||
rows = run_attendance_rest_check(month)
|
||
logger.info("=" * 60)
|
||
logger.info("【检查2 出勤及排休天数验证完成】")
|
||
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:
|
||
if "正被占用" in str(e):
|
||
logger.error("=========== 提醒 ===========")
|
||
logger.error(str(e))
|
||
return {"success": False, "message": str(e)}
|
||
logger.error("检查2执行失败:%s\n%s", e, traceback.format_exc())
|
||
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()
|