1. 新增unsealed_check.py:实现考勤月报未封存名单检查 2. 新增working_days_shift_check.py:实现在职天数排班校验检查 3. 更新aa.md:更新考勤封存接口的请求地址、参数与完整字段定义
452 lines
17 KiB
Python
452 lines
17 KiB
Python
# -*- 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() |