feat(XQ0011考勤检查): 新增2个封存检查脚本与接口文档
1. 新增unsealed_check.py:实现考勤月报未封存名单检查 2. 新增working_days_shift_check.py:实现在职天数排班校验检查 3. 更新aa.md:更新考勤封存接口的请求地址、参数与完整字段定义
This commit is contained in:
@@ -0,0 +1,452 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: unsealed_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-08-31
|
||||
@Description: 考勤月报封存检查 - 检查5「未封存名单」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
|
||||
考勤月报封存记录;有在职记录但无封存记录者输出异常名单,异常类型 = 「考勤月报未封存,请处理」。
|
||||
|
||||
数据来源:
|
||||
1) 在职记录(花名册):由「37du花名册导出」共享指令导出到固定路径,本脚本只读取。
|
||||
导出参数:在职状态 = 在职 + 离职(离职需设置离职时间范围 = 检查月月初 至今天),
|
||||
模板 = 员工基础信息。这样才能把「检查月内仍在职 / 检查月内离职」的人全部覆盖到。
|
||||
2) 考勤月报封存记录:考勤封存接口直取(对应 aa.md / aa.json)。
|
||||
接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查5):
|
||||
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
|
||||
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
|
||||
- 有在职记录但工号不在当月封存记录集合里 → 异常。
|
||||
|
||||
输出:
|
||||
未封存名单_{月份}_{时间戳}.xlsx 异常名单(含 37工号/姓名/月报检查月份/异常类型/所属单位/一~五级部门)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json);
|
||||
2. 需先运行「37du花名册导出」指令导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_unsealed_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_unsealed_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
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()
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception as e:
|
||||
print("写入影刀全局变量 %s 失败(非影刀环境属正常):%s", name, e)
|
||||
|
||||
|
||||
# ==================== 日志(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()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_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_unsealed_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
# 花名册固定路径:由「37du花名册导出」共享指令导出(在职 + 离职,离职时间范围 = 检查月月初至今)
|
||||
DEFAULT_ROSTER_PATH = os.getenv("monthly_unsealed_roster_path") or r"D:\资料\人资\考勤异常\员工花名册.xlsx"
|
||||
|
||||
# 异常类型(对应需求文档检查5)
|
||||
ABNORMAL_TYPE = "考勤月报未封存,请处理"
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册字段(与「37du花名册导出」指令导出的列名一致)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_DEPT_COLS = ["一级部门", "二级部门", "三级部门", "四级部门", "五级部门"]
|
||||
ROSTER_JOIN_COL = "入职时间"
|
||||
ROSTER_LEAVE_COL = "离职时间"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段)
|
||||
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():
|
||||
_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):
|
||||
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 ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)[:10]
|
||||
if not s:
|
||||
return None
|
||||
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 _seal_code_set(rows: List[dict]) -> Set[str]:
|
||||
"""取当月封存记录的全部工号集合。"""
|
||||
codes: Set[str] = set()
|
||||
for rec in rows:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
codes.add(code)
|
||||
break
|
||||
return codes
|
||||
|
||||
|
||||
# ==================== 花名册在职判定 ====================
|
||||
def _load_roster(roster_path: str) -> "pd.DataFrame":
|
||||
"""读取花名册(由「37du花名册导出」指令导出,表头在第 1 行)。"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先在影刀流程中拖入「37du花名册导出」指令导出花名册"
|
||||
f"(在职状态=在职+离职,离职时间范围=检查月月初至今,模板=员工基础信息),再运行本流程;"
|
||||
"或通过 roster_path 参数指定已有花名册文件。")
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _in_month(join: Optional[date], leave: Optional[date], first: date, last: date) -> bool:
|
||||
"""判断员工检查月是否在职:入职 ≤ 月末 且(未离职 或 离职 ≥ 月初)。"""
|
||||
if join is None or join > last:
|
||||
return False
|
||||
if leave is None or leave >= first:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_unsealed_rows(df, seal_codes: Set[str], ym: str, first: date, last: date) -> List[dict]:
|
||||
"""遍历花名册,找出检查月在职但无封存记录的员工,返回名单行列表。"""
|
||||
abnormal: List[dict] = []
|
||||
seen: Set[str] = set()
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seen:
|
||||
continue # 花名册在职/离职同一工号可能多行,取一行即可
|
||||
seen.add(code)
|
||||
join = _parse_date(row.get(ROSTER_JOIN_COL))
|
||||
leave = _parse_date(row.get(ROSTER_LEAVE_COL))
|
||||
if not _in_month(join, leave, first, last):
|
||||
continue # 检查月不在职(尚未入职或已离职早于月初)
|
||||
if code in seal_codes:
|
||||
continue # 已有封存记录,正常
|
||||
abnormal.append({
|
||||
"37工号": code,
|
||||
"姓名": _clean(row.get(ROSTER_NAME_COL)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"所属单位": _clean(row.get(ROSTER_UNIT_COL)),
|
||||
**{f"第{chn}级部门": _clean(row.get(c)) for chn, c in zip(
|
||||
["一", "二", "三", "四", "五"], ROSTER_DEPT_COLS)},
|
||||
})
|
||||
return abnormal
|
||||
|
||||
|
||||
def run_unsealed_check(roster_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查5「未封存名单」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。
|
||||
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("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读花名册(在职记录)
|
||||
df = _load_roster(roster_path)
|
||||
|
||||
# 2. 拉取当月全集团考勤封存数据(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)
|
||||
seal_codes = _seal_code_set(seal_rows)
|
||||
logger.info("考勤封存记录共 %d 人:%s", len(seal_codes), ym)
|
||||
|
||||
# 3. 找出在册未封存
|
||||
abnormal = _build_unsealed_rows(df, seal_codes, ym, first, last)
|
||||
logger.info("检查5命中异常 %d 人(在册未封存)", len(abnormal))
|
||||
|
||||
# 4. 导出异常名单
|
||||
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,可选字段:
|
||||
roster_path(花名册文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
roster_path = args.get("roster_path") or (
|
||||
os.getenv("monthly_unsealed_roster_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_unsealed_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_unsealed_check(roster_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查5 考勤月报未封存名单完成】")
|
||||
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("检查5执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
import sys
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,456 @@
|
||||
# -*- 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()
|
||||
Reference in New Issue
Block a user