Files
37duAutomation/yingdao/XQ0011 考勤月报封存检查/working_days_shift_check.py
T
puddy ea92c62bb9 feat(XQ0011考勤检查): 新增2个封存检查脚本与接口文档
1. 新增unsealed_check.py:实现考勤月报未封存名单检查
2. 新增working_days_shift_check.py:实现在职天数排班校验检查
3. 更新aa.md:更新考勤封存接口的请求地址、参数与完整字段定义
2026-09-01 00:00:31 +08:00

456 lines
19 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-08-31
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
数据来源(考勤封存接口直取,对应 aa.md / aa.json):
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,pageSize ≤ 500,
base_code 留空 = 全集团批量。分页拉取当月全集团封存数据,拉取即保存 Excel 供复用。
- 每员工一条封存记录,检查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。)
输出:
1) 在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查);
2) 考勤封存数据_{月份}_{时间戳}.xlsx 当月全集团封存原始数据(供检查2~5等复用)。
依赖安装(启动校验:必须预先装齐):
pip install requests pandas openpyxl
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
环境变量(可选):
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
@Version: 1.1.0
"""
# ==================== 标准库导入 ====================
import json
import os
import time
import traceback
from datetime import date, datetime, timedelta
from typing import Dict, List, Optional, Tuple
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
try:
import requests
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
"请先执行安装:\n pip install requests pandas openpyxl\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()
# ==================== 共享路径 & 常量配置 ====================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
HR_BASE_URL = "https://hr.37du.co"
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
PAGE_MAX_SIZE = 500
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"] # 一~五级部门
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头)
CN_FIELD_MAP: Dict[str, str] = {
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
"_年度福利假天": "kq_stat_leave_day_num24",
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
"员工状态": "staff_status", "在职状态": "person_status_name",
}
# 输出列(对应需求文档检查1输出字段)
OUTPUT_COLUMNS = [
"37工号", "姓名", "月报检查月份", "异常类型",
"在职天数", "应勤工作日", "休息天", "差值",
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
]
# ==================== HR 登录态(共享 cookies) ====================
class HRSessionExpiredError(Exception):
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
def _load_shared_hr_cookies():
if not os.path.exists(SHARED_HR_COOKIE_FILE):
return None
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
return json.load(f) or None
def _ensure_hr_cookies():
if _load_shared_hr_cookies():
return True
raise RuntimeError(
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
def build_hr_session():
_ensure_hr_cookies()
cookies = _load_shared_hr_cookies()
if not cookies:
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
def hr_request_json(session, method, url, params, label, timeout=20):
resp = session.request(method.upper(), url, data=params, timeout=timeout)
resp.raise_for_status()
text = resp.text or ""
if not text or not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
return resp.json()
def fetch_cur_user_info(session):
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
def _relogin_get_user_id():
"""登录态失效后:重建会话 → 重新获取 userId。"""
_ensure_hr_cookies()
session = build_hr_session()
info = fetch_cur_user_info(session)
return session, _clean(info.get("userId"))
# ==================== 考勤封存接口(aa.md:getPageAjaxList.mc + leave_wage_SelectV2) ====================
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
"""请求单页考勤封存数据。
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
"""
params = {
"tree_code": "cq37du",
"user_id": user_id,
"sqlId": SEAL_SQL_ID,
"commonQuery": "",
"commonQueryStr": "",
"dept_org_name": "",
"confirm_state": "",
"person_status": "",
"identity": "",
"staff_status": "",
"orgAlias": "",
"dept_ids": "",
"post_type": "1",
"custom_dept_ids": "",
"custom_dept_names": "",
"STAFF_ID": "",
"sealOrgAlias": "",
"seal_dept_stru_id": "",
"kqDataOperatorName": "",
"kqDataOperatorId": "",
"base_code": "",
"staff_name": "",
"yearmonth": yearmonth,
"kq_data_state": "",
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
all_rows: List[dict] = []
page_no = 1
while True:
try:
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
except HRSessionExpiredError:
logger.warning("考勤封存登录态过期,自动补登录后续抓")
session, user_id = _relogin_get_user_id()
data = fetch_seal_page(session, user_id, yearmonth, 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 _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 _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
列顺序不变,保证保存的封存数据信息不丢失。
"""
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
return frame.rename(columns=rename)
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}"
yearmonth = ym.replace("-", "")
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
# 1. 拉取当月全集团考勤封存数据(base_code 留空批量)
session = build_hr_session()
user_id = _clean(fetch_cur_user_info(session).get("userId"))
if not user_id:
raise RuntimeError("获取当前用户 userId 失败")
seal_rows = fetch_all_seal(session, user_id, yearmonth)
if not seal_rows:
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
seal_map = _build_seal_map(seal_rows)
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
# 2. 保存原始封存数据(供检查2~5复用)
os.makedirs(SAVE_DIR, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
raw_path = os.path.join(SAVE_DIR, f"考勤封存数据_{ym}_{ts}.xlsx")
if seal_rows:
_rename_columns_cn(pd.DataFrame(seal_rows), CN_FIELD_MAP).to_excel(raw_path, index=False)
logger.info("原始封存数据已保存:%s(%d 行)", raw_path, len(seal_rows))
# 3. 逐人检查
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))
# 4. 导出异常名单
save_path = os.path.join(SAVE_DIR, f"在职天数排班异常_{ym}_{ts}.xlsx")
pd.DataFrame(abnormal if abnormal else [],
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
return abnormal
def main() -> None:
"""影刀入口。"""
try:
rows = run_working_days_shift_check()
logger.info("=" * 60)
logger.info("【检查1 在职天数是否均排班验证完成】")
logger.info(" 检查月份:默认上月 | 异常人数:%d", len(rows))
logger.info(" 输出目录:%s", SAVE_DIR)
logger.info("=" * 60)
except Exception as e:
logger.error("检查1执行失败:%s", e)
raise
if __name__ == "__main__":
main()