feat(XQ0011考勤月报封存检查): 新增5项考勤封存检查脚本及文档
新增考勤月报封存检查的完整校验逻辑: 1. 新增延时加班验证脚本,检查经营系管理岗违规领取延时加班补贴 2. 新增全勤验证脚本,校验月中晋升及异常考勤仍标记全勤的情况 3. 新增封存值最新校验脚本,对比封存数据与实时统计数据差异 4. 新增出勤排休验证脚本,校验出勤天数和休息天数是否符合排班方案 5. 更新aa.md文档,补充全部6项检查规则和接口说明 6. 删除冗余的aa.json测试文件
This commit is contained in:
@@ -1,177 +0,0 @@
|
||||
{
|
||||
"attributeMap" : null,
|
||||
"count" : 1,
|
||||
"datas" : [ {
|
||||
"ORG_FULL_PATH" : "集团-金色印象事业部-第二大区-金色印象长沙经营中心-第三片区-八一路行政会馆-服务组",
|
||||
"person_status" : "2",
|
||||
"IDCARD" : "511823200909152619",
|
||||
"base_code" : "37036650",
|
||||
"POST_NO" : "287",
|
||||
"BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469",
|
||||
"BELONG_UNIT_ORG_NAME" : "金色印象事业部",
|
||||
"POST_ALIAS" : "服务员",
|
||||
"POST_ORG_NAME" : "服务员",
|
||||
"staff_id" : "9bbaec51-f4aa-4271-bb75-44583d510331",
|
||||
"staff_name" : "李俊熙",
|
||||
"DEPT_STRU_ID" : "57fab6e7-c7fd-4ffa-ac1a-0a085a05f7de",
|
||||
"DEPT_ORG_NAME" : "服务组",
|
||||
"POST_ALIAS_NAME" : "服务员",
|
||||
"leave_type" : "17",
|
||||
"DEPT_ORG_ONE" : "第二大区",
|
||||
"DEPT_ORG_TWO" : "金色印象长沙经营中心",
|
||||
"DEPT_ORG_THREE" : "第三片区",
|
||||
"DEPT_ORG_FOUR" : "八一路行政会馆",
|
||||
"DEPT_ORG_FIVE" : "服务组",
|
||||
"dept_one" : null,
|
||||
"dept_two" : null,
|
||||
"vacation_type_name" : "特殊事假",
|
||||
"time_unit" : "天",
|
||||
"start_time" : "2026-08-30 10:00:00",
|
||||
"end_time" : "2026-08-30 19:00:00",
|
||||
"leave_num" : "1",
|
||||
"leave_reason" : "处理个人事务",
|
||||
"status" : "005",
|
||||
"leave_hours" : "",
|
||||
"leave_days" : "1.00",
|
||||
"businessKey" : "bpmc6afb65ed9a14078a467c0045994ad3e",
|
||||
"process_id" : "dc63c919-04db-4fa1-9f6d-0eaa76037f90",
|
||||
"form_id" : "399b1612-d410-4a59-86cb-b5260b933232",
|
||||
"source" : "1",
|
||||
"leave_id" : "bpmc6afb65ed9a14078a467c0045994ad3e",
|
||||
"operat_time" : "2026-09-01 21:11:56",
|
||||
"apply_time" : "2026-09-01 16:24:55",
|
||||
"leave_hours_ori" : "0",
|
||||
"leave_days_ori" : "1",
|
||||
"begin_date" : "2026-08-30",
|
||||
"begin_other_name" : "1",
|
||||
"end_date" : "2026-08-30",
|
||||
"end_other_name" : "2",
|
||||
"if_other_name_open" : "1",
|
||||
"begin_date_other_name" : "2026-08-30 上半段",
|
||||
"end_date_other_name" : "2026-08-30 下半段",
|
||||
"operat_user_id" : "fdb2e691-1f5c-46f1-b2b4-d69987a4ac96",
|
||||
"operat_user_name" : "谌超",
|
||||
"processing_reason" : null,
|
||||
"remark" : null,
|
||||
"kqext_create_user_id" : null,
|
||||
"kqext_create_time" : null,
|
||||
"kqext_operator_id" : null,
|
||||
"kqext_operate_time" : null,
|
||||
"hrext_hsb_ext_speciality" : null,
|
||||
"hrext_ext_technician_code" : "",
|
||||
"hrext_ext_cal_person2" : "",
|
||||
"hrext_ext_call_phone2" : "",
|
||||
"hrext_ext_star_level" : "正式",
|
||||
"hrext_ext_rehiring_reason_type" : "",
|
||||
"hrext_ext_staff_type" : "门店服务岗",
|
||||
"hrext_ext_insurance_type" : "雇主险",
|
||||
"hrext_ext_recruit_way" : "其它",
|
||||
"hrext_ext_call_relationship2" : "",
|
||||
"hrext_ext_is_CRBT_open" : "",
|
||||
"hrext_ext_dept_principal" : "",
|
||||
"hrext_ext_yb_pay_year" : "",
|
||||
"hrext_ext_Have_worked" : "",
|
||||
"hrext_ext_family_join" : "否",
|
||||
"hrext_ext_criminal_record" : "否",
|
||||
"hrext_ext_infectious_disease" : "否",
|
||||
"hrext_ext_References" : "",
|
||||
"hrext_ext_References_phone" : "",
|
||||
"hrext_ext_References_outside" : "",
|
||||
"hrext_ext_outside_References_phone" : "",
|
||||
"hrext_ext_is_dormitory" : "是",
|
||||
"hrext_ext_process_approval_status" : "已审批",
|
||||
"hrext_ext_trans_type" : "其他"
|
||||
} ],
|
||||
"pageSize" : 15,
|
||||
"start" : 0,
|
||||
"pageNo" : 1,
|
||||
"pageCount" : 1,
|
||||
"allDatas" : {
|
||||
"#result-set-1" : [ {
|
||||
"ORG_FULL_PATH" : "集团-金色印象事业部-第二大区-金色印象长沙经营中心-第三片区-八一路行政会馆-服务组",
|
||||
"person_status" : "2",
|
||||
"IDCARD" : "511823200909152619",
|
||||
"base_code" : "37036650",
|
||||
"POST_NO" : "287",
|
||||
"BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469",
|
||||
"BELONG_UNIT_ORG_NAME" : "金色印象事业部",
|
||||
"POST_ALIAS" : "服务员",
|
||||
"POST_ORG_NAME" : "服务员",
|
||||
"staff_id" : "9bbaec51-f4aa-4271-bb75-44583d510331",
|
||||
"staff_name" : "李俊熙",
|
||||
"DEPT_STRU_ID" : "57fab6e7-c7fd-4ffa-ac1a-0a085a05f7de",
|
||||
"DEPT_ORG_NAME" : "服务组",
|
||||
"POST_ALIAS_NAME" : "服务员",
|
||||
"leave_type" : "17",
|
||||
"DEPT_ORG_ONE" : "第二大区",
|
||||
"DEPT_ORG_TWO" : "金色印象长沙经营中心",
|
||||
"DEPT_ORG_THREE" : "第三片区",
|
||||
"DEPT_ORG_FOUR" : "八一路行政会馆",
|
||||
"DEPT_ORG_FIVE" : "服务组",
|
||||
"dept_one" : null,
|
||||
"dept_two" : null,
|
||||
"vacation_type_name" : "特殊事假",
|
||||
"time_unit" : "天",
|
||||
"start_time" : "2026-08-30 10:00:00",
|
||||
"end_time" : "2026-08-30 19:00:00",
|
||||
"leave_num" : "1",
|
||||
"leave_reason" : "处理个人事务",
|
||||
"status" : "005",
|
||||
"leave_hours" : "",
|
||||
"leave_days" : "1.00",
|
||||
"businessKey" : "bpmc6afb65ed9a14078a467c0045994ad3e",
|
||||
"process_id" : "dc63c919-04db-4fa1-9f6d-0eaa76037f90",
|
||||
"form_id" : "399b1612-d410-4a59-86cb-b5260b933232",
|
||||
"source" : "1",
|
||||
"leave_id" : "bpmc6afb65ed9a14078a467c0045994ad3e",
|
||||
"operat_time" : "2026-09-01 21:11:56",
|
||||
"apply_time" : "2026-09-01 16:24:55",
|
||||
"leave_hours_ori" : "0",
|
||||
"leave_days_ori" : "1",
|
||||
"begin_date" : "2026-08-30",
|
||||
"begin_other_name" : "1",
|
||||
"end_date" : "2026-08-30",
|
||||
"end_other_name" : "2",
|
||||
"if_other_name_open" : "1",
|
||||
"begin_date_other_name" : "2026-08-30 上半段",
|
||||
"end_date_other_name" : "2026-08-30 下半段",
|
||||
"operat_user_id" : "fdb2e691-1f5c-46f1-b2b4-d69987a4ac96",
|
||||
"operat_user_name" : "谌超",
|
||||
"processing_reason" : null,
|
||||
"remark" : null,
|
||||
"kqext_create_user_id" : null,
|
||||
"kqext_create_time" : null,
|
||||
"kqext_operator_id" : null,
|
||||
"kqext_operate_time" : null,
|
||||
"hrext_hsb_ext_speciality" : null,
|
||||
"hrext_ext_technician_code" : "",
|
||||
"hrext_ext_cal_person2" : "",
|
||||
"hrext_ext_call_phone2" : "",
|
||||
"hrext_ext_star_level" : "正式",
|
||||
"hrext_ext_rehiring_reason_type" : "",
|
||||
"hrext_ext_staff_type" : "门店服务岗",
|
||||
"hrext_ext_insurance_type" : "雇主险",
|
||||
"hrext_ext_recruit_way" : "其它",
|
||||
"hrext_ext_call_relationship2" : "",
|
||||
"hrext_ext_is_CRBT_open" : "",
|
||||
"hrext_ext_dept_principal" : "",
|
||||
"hrext_ext_yb_pay_year" : "",
|
||||
"hrext_ext_Have_worked" : "",
|
||||
"hrext_ext_family_join" : "否",
|
||||
"hrext_ext_criminal_record" : "否",
|
||||
"hrext_ext_infectious_disease" : "否",
|
||||
"hrext_ext_References" : "",
|
||||
"hrext_ext_References_phone" : "",
|
||||
"hrext_ext_References_outside" : "",
|
||||
"hrext_ext_outside_References_phone" : "",
|
||||
"hrext_ext_is_dormitory" : "是",
|
||||
"hrext_ext_process_approval_status" : "已审批",
|
||||
"hrext_ext_trans_type" : "其他"
|
||||
} ]
|
||||
},
|
||||
"url" : null,
|
||||
"state" : "1",
|
||||
"meg" : "",
|
||||
"des" : "",
|
||||
"viewMapper" : null
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
# -*- 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()
|
||||
@@ -0,0 +1,370 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: full_attendance_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查5「全勤验证」(影刀单文件,自包含)。
|
||||
月中晋升职能或管理岗,或存在迟到早退异常仍被标记全勤的,输出异常名单。
|
||||
|
||||
判定口径(对应需求文档 aa.md 检查⑤):
|
||||
规则A「月中途晋升,不享受全勤」:
|
||||
调动台账月中途(检查月内)从 门店服务序列/门店技师序列 调动到
|
||||
职能系专业序列/职能系管理序列/经营系管理序列 的,且封存「是否全勤」=1 → 异常;
|
||||
规则B「存在考勤异常,不享受全勤」:
|
||||
封存存在迟到或早退异常次数(迟到次数+早退次数>0)、且「是否全勤」=1 → 异常。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
检查5用到的封存字段(aa.md 列定义):
|
||||
kq_stat_cal_ext43 是否全勤
|
||||
迟到:kq_stat_cal_ext60/61/62(30分钟内/30~60/60~120)
|
||||
早退:kq_stat_cal_ext51/52/53(30分钟内/30~60/60~120)
|
||||
2) 调动台账:由「37du调动台账导出」共享指令(纯接口版 transfer_roster_export_api.py,
|
||||
模板=排班异常识别导出)导出到固定路径,本模块只读取。表头在第 2 行(header=1)。
|
||||
检查5用到的台账列:工号 / 调动时间 / 原职位序列 / 现职位序列。
|
||||
|
||||
输出:
|
||||
全勤验证异常_{月份}_{时间戳}.xlsx 异常名单(含异常明细便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du调动台账导出」(模板=排班异常识别导出,
|
||||
调动时间范围 = 检查月月初 ~ 检查月月末)导出调动台账到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_fa_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_fa_transfer_path 调动台账文件路径
|
||||
(默认 D:\\资料\\人资\\排班异常识别\\调动台账.xlsx)
|
||||
@Version: 1.0.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:
|
||||
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_fa_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
# 调动台账固定路径:由「37du调动台账导出」共享指令导出(模板=排班异常识别导出)
|
||||
DEFAULT_TRANSFER_PATH = (os.getenv("monthly_fa_transfer_path")
|
||||
or r"D:\资料\人资\排班异常识别\调动台账.xlsx")
|
||||
|
||||
# 异常类型(对应需求文档检查5 规则A/B)
|
||||
ABNORMAL_TYPE_PROMOTION = "月中途晋升,不享受全勤"
|
||||
ABNORMAL_TYPE_LATE_EARLY = "存在考勤异常,不享受全勤"
|
||||
|
||||
# 调动识别:原职位序列命中「门店系」(晋升起点)
|
||||
PRE_SEQ_KEYWORDS = ("门店服务序列", "门店技师序列")
|
||||
# 现职位序列命中「职能/经营系管理、专业」(晋升终点)
|
||||
NOW_SEQ_KEYWORDS = ("职能系专业序列", "职能系管理序列", "经营系管理序列")
|
||||
|
||||
# 封存记录工号字段 & 是否全勤 / 迟到 / 早退字段(aa.md 列定义)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_FULL_ATT_FIELD = "kq_stat_cal_ext43" # 是否全勤
|
||||
SEAL_LATE_FIELDS = ("kq_stat_cal_ext60", "kq_stat_cal_ext61", "kq_stat_cal_ext62")
|
||||
SEAL_EARLY_FIELDS = ("kq_stat_cal_ext51", "kq_stat_cal_ext52", "kq_stat_cal_ext53")
|
||||
|
||||
# 调动台账列(与「37du调动台账导出」指令导出的列名一致)
|
||||
TRANSFER_CODE_COL = "工号"
|
||||
TRANSFER_DATE_COL = "调动时间"
|
||||
TRANSFER_PRE_SEQ_COL = "原职位序列"
|
||||
TRANSFER_NOW_SEQ_COL = "现职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段,附 异常明细 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
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 _hit_keywords(value: str, keywords: Tuple[str, ...]) -> bool:
|
||||
"""字段值是否命中任一关键词(子串匹配)。"""
|
||||
return any(key in value for key in keywords)
|
||||
|
||||
|
||||
# ==================== 调动台账读取 ====================
|
||||
def _load_transfer_rows(transfer_path: str) -> List[dict]:
|
||||
"""读取调动台账(37du调动台账导出,表头在第 2 行 header=1),返回记录行列表。"""
|
||||
transfer_path = transfer_path or DEFAULT_TRANSFER_PATH
|
||||
if not os.path.exists(transfer_path):
|
||||
raise RuntimeError(
|
||||
f"未找到调动台账文件:{transfer_path}\n"
|
||||
"请先在影刀流程中拖入「37du调动台账导出」指令导出调动台账"
|
||||
"(模板=排班异常识别导出,调动时间范围=检查月月初~月末),再运行本流程;"
|
||||
"或通过 transfer_path 参数指定已有调动台账文件。")
|
||||
df = pd.read_excel(transfer_path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
for col in (TRANSFER_CODE_COL, TRANSFER_DATE_COL,
|
||||
TRANSFER_PRE_SEQ_COL, TRANSFER_NOW_SEQ_COL):
|
||||
if col not in df.columns:
|
||||
raise RuntimeError(
|
||||
f"调动台账缺少「{col}」列:{transfer_path}\n"
|
||||
"请使用模板「排班异常识别导出」导出。")
|
||||
rows = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取调动台账:%s,共 %d 行", transfer_path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 封存数据索引 ====================
|
||||
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 = _clean(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _count_abnormal(rec: dict, fields: Tuple[str, ...]) -> float:
|
||||
"""统计迟到/早退次数合计。"""
|
||||
return sum(_num(rec.get(f)) for f in fields)
|
||||
|
||||
|
||||
def _build_abnormal(code: str, rec: dict, ym: str, abnormal_type: str, detail: str) -> dict:
|
||||
"""构造异常名单行(统一字段)。"""
|
||||
return {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": abnormal_type,
|
||||
"异常明细": detail,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
**{f"第{chn}级部门": _clean(rec.get(f)) for chn, f in zip(
|
||||
["一", "二", "三", "四", "五"],
|
||||
["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"])},
|
||||
}
|
||||
|
||||
|
||||
def run_full_attendance_check(transfer_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查5「全勤验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账文件路径,默认 DEFAULT_TRANSFER_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}"
|
||||
logger.info("===== 检查5「全勤验证」月份:%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. 读取调动台账
|
||||
transfer_rows = _load_transfer_rows(transfer_path)
|
||||
|
||||
# 3. 规则A:月中途晋升(门店系 → 职能/经营系),且全勤=1
|
||||
abnormal: List[dict] = []
|
||||
promotion_cnt = 0
|
||||
for row in transfer_rows:
|
||||
code = _clean(row.get(TRANSFER_CODE_COL))
|
||||
move_day = _parse_date(row.get(TRANSFER_DATE_COL))
|
||||
if not code or not move_day:
|
||||
continue
|
||||
if not (first <= move_day <= last):
|
||||
continue # 非检查月内的调动,跳过
|
||||
pre_seq = _clean(row.get(TRANSFER_PRE_SEQ_COL))
|
||||
now_seq = _clean(row.get(TRANSFER_NOW_SEQ_COL))
|
||||
if not _hit_keywords(pre_seq, PRE_SEQ_KEYWORDS):
|
||||
continue # 晋升起点非门店服务/技师序列
|
||||
if not _hit_keywords(now_seq, NOW_SEQ_KEYWORDS):
|
||||
continue # 晋升终点非职能/经营系管理、专业序列
|
||||
rec = seal_map.get(code)
|
||||
if not rec:
|
||||
continue # 无封存记录(未封存场景由检查4负责),跳过
|
||||
if _num(rec.get(SEAL_FULL_ATT_FIELD)) != 1:
|
||||
continue # 非全勤,正常
|
||||
promotion_cnt += 1
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_PROMOTION,
|
||||
f"调动时间{move_day},原职位序列:{pre_seq},现职位序列:{now_seq}"))
|
||||
logger.info("检查5 规则A 命中异常 %d 人(月中途晋升且全勤=1)", promotion_cnt)
|
||||
|
||||
# 4. 规则B:存在迟到/早退异常次数,且全勤=1
|
||||
late_early_cnt = 0
|
||||
for code, rec in seal_map.items():
|
||||
if _num(rec.get(SEAL_FULL_ATT_FIELD)) != 1:
|
||||
continue # 非全勤,正常
|
||||
late = _count_abnormal(rec, SEAL_LATE_FIELDS)
|
||||
early = _count_abnormal(rec, SEAL_EARLY_FIELDS)
|
||||
if late + early == 0:
|
||||
continue # 无迟到早退,正常
|
||||
late_early_cnt += 1
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_LATE_EARLY,
|
||||
f"迟到次数合计{late:g},早退次数合计{early:g}"))
|
||||
logger.info("检查5 规则B 命中异常 %d 人(有迟到早退且全勤=1)", late_early_cnt)
|
||||
|
||||
# 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,可选字段:
|
||||
transfer_path(调动台账文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
transfer_path = args.get("transfer_path") or (
|
||||
os.getenv("monthly_fa_transfer_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_fa_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_full_attendance_check(transfer_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,390 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: latest_seal_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查3「封存值是否为最新值」(影刀单文件,自包含)。
|
||||
考勤月报封存页面「对比」检索对比差异值是否全部为空,若有异常值则输出异常名单。
|
||||
|
||||
判定口径(对应需求文档 aa.md 检查③):
|
||||
对比「考勤封存值」与「实时统计值」两套数据的考勤指标字段,逐字段比较数值;
|
||||
任一字段存在差异(非空差异)→ 异常,异常类型「考勤封存非最新值,请重新封存」。
|
||||
|
||||
数据来源:
|
||||
1) 封存值(对比左列):考勤月报封存记录,由 seal_data_export.py 导出并预处理
|
||||
(所属单位白名单筛选),保存为固定路径 考勤封存数据_{月份}.xlsx,
|
||||
本模块只读取该预处理封存表,不再直连接口。
|
||||
2) 实时值(对比右列):POST https://hr.37du.co/RedseaPlatform/getPageAjax/
|
||||
kq_count_leave_StatV2/CoreRequest.mc
|
||||
参数 begin/end 日期范围 + staff_ids 留空 = 全集团批量实时统计(count=8215),
|
||||
按所属单位白名单筛选后与本表逐员工比对。
|
||||
两接口返回均为 kq_stat_* 系列字段,同一员工以 staff_id(辅以工号)匹配。
|
||||
|
||||
对比字段(页面「对比」展示字段,中文标签 → 接口字段,来源 aa.md 封存页列定义):
|
||||
实际出勤天日 ext19 / _在职应勤工作日 month_yq_work_day_in / 休息天 ext9 /
|
||||
旷工天数 ext39 / 漏打卡次数 ext8 / _特别福利假天 leave_day_num23 /
|
||||
_年度福利假天 leave_day_num24 / 年假天 leave_day_num1 / _病假天 leave_day_num4 /
|
||||
_产假天 leave_day_num5 / _事假天 leave_day_num9 / _普通事假天 leave_day_num16 /
|
||||
_特殊事假天 leave_day_num17 / _小时特假小时 leave_hour_num18 /
|
||||
_普通事假(晚/高峰)天 leave_day_num19 / _普通事假(早/中)天 leave_day_num20 /
|
||||
_工作日加班转补贴小时 ps_bt_hour / 法定节假日加班转补贴天 ext69 /
|
||||
休息日加班转补贴天 ext44 / 当月未休调休天 ext63 / 迟到 ext60/61/62 /
|
||||
早退 ext51/52/53 / 连班次数 ext40 / 是否未休小时特假 ext42 / 是否全勤 ext43。
|
||||
|
||||
输出:
|
||||
封存值校验异常_{月份}_{时间戳}.xlsx 异常名单(含异常明细:差异字段清单便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_ls_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
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
|
||||
build_hr_session, fetch_cur_user_info, hr_request_json, load_seal_rows,
|
||||
SEAL_UNIT_WHITELIST, _clean,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
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_ls_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 实时统计接口(对比右侧):不传 staff_ids = 全集团批量实时统计
|
||||
STAT_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/kq_count_leave_StatV2/CoreRequest.mc"
|
||||
STAT_PAGE_SIZE = 500
|
||||
|
||||
# 异常类型(对应需求文档检查3)
|
||||
ABNORMAL_TYPE = "考勤封存非最新值,请重新封存"
|
||||
|
||||
# 封存记录主键字段(实时侧同名匹配)
|
||||
SEAL_STAFF_ID_FIELD = "staff_id"
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 页面「对比」展示字段:中文标签 → 接口字段(来源:aa.md 封存页列定义 / CN_FIELD_MAP)
|
||||
COMPARE_FIELDS: List[Tuple[str, str]] = [
|
||||
("实际出勤天日", "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_num23"),
|
||||
("_年度福利假天", "kq_stat_leave_day_num24"),
|
||||
("年假天", "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_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"),
|
||||
]
|
||||
|
||||
# 输出列(对应需求文档检查3输出字段,附 异常明细 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _num(v) -> float:
|
||||
"""数值归一化:空/None → 0.0;数值字符串 → float。"""
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return 0.0
|
||||
try:
|
||||
return float(s)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _num_eq(a, b) -> bool:
|
||||
"""两字段值是否相等(数值口径:空/None 视为 0,浮点容差)。"""
|
||||
return abs(_num(a) - _num(b)) < 1e-9
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# ==================== 实时统计值拉取(StatV2,全集团批量分页) ====================
|
||||
def fetch_stat_all(session, user_id: str, ym: str, begin: date, end: date) -> List[dict]:
|
||||
"""分页拉取某月实时统计值(StatV2,staff_ids 留空 = 全集团批量)。
|
||||
|
||||
返回所有非白名单过滤前的实时统计记录行(按所属单位白名单在调用方筛选)。
|
||||
"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"treecode": "cq37du",
|
||||
"begin": begin.isoformat(),
|
||||
"end": end.isoformat(),
|
||||
"staff_ids": "",
|
||||
"type": "1",
|
||||
"start": str((page_no - 1) * STAT_PAGE_SIZE),
|
||||
"pageSize": str(STAT_PAGE_SIZE),
|
||||
"start_Time": ym,
|
||||
}
|
||||
data = hr_request_json(session, "POST", STAT_URL, params, "实时统计(StatV2)")
|
||||
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 _build_stat_map(stat_rows: List[dict]) -> Dict[str, dict]:
|
||||
"""实时统计记录索引:优先 staff_id,缺失时用工号归一化兜底。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in stat_rows:
|
||||
key = _clean(rec.get("staff_id"))
|
||||
if not key:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
key = _clean(rec.get(f))
|
||||
if key:
|
||||
break
|
||||
if key:
|
||||
mapping.setdefault(key, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def _record_key(rec: dict) -> str:
|
||||
"""封存记录主键(staff_id 优先,工号兜底,与实时索引同口径)。"""
|
||||
key = _clean(rec.get(SEAL_STAFF_ID_FIELD))
|
||||
if not key:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
key = _clean(rec.get(f))
|
||||
if key:
|
||||
break
|
||||
return key
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _compare_fields(seal_rec: dict, stat_rec: dict) -> List[str]:
|
||||
"""逐字段对比封存值与实时值,返回差异明细(空列表 = 全部一致)。"""
|
||||
diffs: List[str] = []
|
||||
for label, field in COMPARE_FIELDS:
|
||||
v_seal = seal_rec.get(field)
|
||||
v_stat = stat_rec.get(field) if stat_rec else None
|
||||
if _num_eq(v_seal, v_stat):
|
||||
continue
|
||||
diffs.append(f"{label}[{field}]:封存{_clean(v_seal) or 0} → 实时{_clean(v_stat) or 0}")
|
||||
return diffs
|
||||
|
||||
|
||||
def _build_abnormal(code: str, rec: dict, ym: str, detail: str) -> dict:
|
||||
"""构造异常名单行(统一字段)。"""
|
||||
return {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"异常明细": detail,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
**{f"第{chn}级部门": _clean(rec.get(f)) for chn, f in zip(
|
||||
["一", "二", "三", "四", "五"],
|
||||
["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"])},
|
||||
}
|
||||
|
||||
|
||||
def run_latest_seal_check(month: str = None) -> List[dict]:
|
||||
"""执行检查3「封存值是否为最新值」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
begin, end = _month_range(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}"
|
||||
begin, end = _month_range(ym)
|
||||
logger.info("===== 检查3「封存值是否为最新值」月份:%s(%s ~ %s) =====", ym, begin, end)
|
||||
|
||||
# 1. 读取预处理封存表(封存值,已按所属单位白名单筛选)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
logger.info("封存值加载完成,共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 拉取当月实时统计值(StatV2 全集团批量)→ 白名单筛选 → 按员工建立索引
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
stat_all = fetch_stat_all(session, user_id, ym, begin, end)
|
||||
stat_whitelist = [r for r in stat_all
|
||||
if _clean(r.get("BELONG_UNIT_ORG_NAME")) in SEAL_UNIT_WHITELIST]
|
||||
stat_map = _build_stat_map(stat_whitelist)
|
||||
logger.info("实时统计全集团 %d 人 → 白名单单位 %d 人", len(stat_all), len(stat_whitelist))
|
||||
|
||||
# 3. 逐员工对比 封存值 vs 实时值,有差异 → 异常
|
||||
abnormal: List[dict] = []
|
||||
diff_cnt = miss_cnt = 0
|
||||
for rec in seal_rows:
|
||||
code = _record_key(rec)
|
||||
if not code:
|
||||
continue
|
||||
stat_rec = stat_map.get(code)
|
||||
if stat_rec is None:
|
||||
# 实时统计记录缺失:对比差异非空,视为封存非最新值
|
||||
miss_cnt += 1
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, "实时统计记录缺失,无法确认封存为最新值"))
|
||||
continue
|
||||
diffs = _compare_fields(rec, stat_rec)
|
||||
if not diffs:
|
||||
continue
|
||||
diff_cnt += 1
|
||||
abnormal.append(_build_abnormal(code, rec, ym, ";".join(diffs)))
|
||||
logger.info("检查3 命中异常 %d 人(差异字段 %d 人 + 实时记录缺失 %d 人)",
|
||||
len(abnormal), diff_cnt, miss_cnt)
|
||||
|
||||
# 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,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_ls_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_latest_seal_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查3 封存值校验完成】")
|
||||
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("检查3执行失败:%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()
|
||||
@@ -0,0 +1,306 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: overtime_compensation_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查6「延时加班验证」(影刀单文件,自包含)。
|
||||
经营系管理岗不享受延时加班:识别职位序列为「经营系管理序列」的员工,若考勤封存页面
|
||||
字段「_工作日加班转补贴小时」(kq_stat_ps_bt_hour)为非零值,则输出异常名单,
|
||||
异常类型 = 「经营系管理岗不应享受延时加班,请核对」。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
2) 职位序列(识别经营系管理序列):花名册「员工基础信息」模板导出(37du花名册导出,
|
||||
纯接口版 roster_export_api.py),其中含「职位序列」列(pt_staff_stru.first_type_id),
|
||||
本模块按工号 join 取职位序列。花名册路径默认与检查5一致,可独立配置。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查6):
|
||||
- 逐条封存记录,按工号从花名册取职位序列;
|
||||
- 职位序列命中「经营系管理序列」且「_工作日加班转补贴小时」非零(>0)→ 异常;
|
||||
- 花名册查不到职位序列的员工跳过(无法判断序列,不误报)。
|
||||
|
||||
输出:
|
||||
延时加班异常_{月份}_{时间戳}.xlsx 异常名单(含延时加班补贴小时便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du花名册导出」(模板=员工基础信息)导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_otc_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_otc_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Set, 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:
|
||||
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_otc_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
# 花名册固定路径:由「37du花名册导出」共享指令导出(模板=员工基础信息,含职位序列列)
|
||||
DEFAULT_ROSTER_PATH = os.getenv("monthly_otc_roster_path") or r"D:\资料\人资\考勤异常\员工花名册.xlsx"
|
||||
|
||||
# 异常类型(对应需求文档检查6)
|
||||
ABNORMAL_TYPE = "经营系管理岗不应享受延时加班,请核对"
|
||||
|
||||
# 命中职位序列(经营系管理序列不享受延时加班)
|
||||
TARGET_SEQUENCES: Tuple[str, ...] = ("经营系管理序列",)
|
||||
|
||||
# 封存记录工号字段 & 加班转补贴小时字段(aa.md:_工作日加班转补贴小时)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_OT_HOUR_FIELD = "kq_stat_ps_bt_hour"
|
||||
|
||||
# 花名册字段(与「37du花名册导出」指令导出的列名一致,员工基础信息模板含职位序列列)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_SEQ_COL = "职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查6输出字段,附 延时加班补贴小时 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"延时加班补贴小时",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _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 _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_seq_map(roster_path: str) -> Dict[str, str]:
|
||||
"""读取花名册,建立 工号→职位序列 映射(同一工号多行取第一个非空序列)。"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先在影刀流程中拖入「37du花名册导出」指令导出花名册"
|
||||
"(模板=员工基础信息,需包含「职位序列」列),再运行本流程;"
|
||||
"或通过 roster_path 参数指定已有花名册文件。")
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
if ROSTER_SEQ_COL not in df.columns:
|
||||
raise RuntimeError(
|
||||
f"花名册缺少「{ROSTER_SEQ_COL}」列:{roster_path}\n"
|
||||
"请使用模板「员工基础信息」导出(含职位序列列)。")
|
||||
seq_map: Dict[str, str] = {}
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seq_map:
|
||||
continue
|
||||
seq_map[code] = _clean(row.get(ROSTER_SEQ_COL))
|
||||
logger.info("已读取花名册职位序列:%s,共 %d 人", roster_path, len(seq_map))
|
||||
return seq_map
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _is_target_sequence(seq: str) -> bool:
|
||||
"""职位序列是否命中目标序列(经营系管理序列)。"""
|
||||
return any(key in seq for key in TARGET_SEQUENCES)
|
||||
|
||||
|
||||
def run_overtime_compensation_check(roster_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查6「延时加班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
logger.info("===== 检查6「延时加班验证」月份:%s =====", ym)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 读取花名册职位序列映射(工号→职位序列)
|
||||
seq_map = _load_roster_seq_map(roster_path)
|
||||
|
||||
# 3. 逐人检查:经营系管理序列 且 延时加班补贴小时非零
|
||||
abnormal: List[dict] = []
|
||||
no_seq_cnt = 0
|
||||
for rec in seal_rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if not code:
|
||||
continue
|
||||
seq = seq_map.get(code, "")
|
||||
if not seq:
|
||||
no_seq_cnt += 1
|
||||
continue # 花名册查不到职位序列,无法判断序列,不误报
|
||||
if not _is_target_sequence(seq):
|
||||
continue # 非经营系管理序列,正常
|
||||
ot_hour = _num(rec.get(SEAL_OT_HOUR_FIELD))
|
||||
if ot_hour == 0:
|
||||
continue # 无延时加班补贴小时,正常
|
||||
abnormal.append({
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"延时加班补贴小时": ot_hour,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
**{f"第{chn}级部门": _clean(rec.get(f)) for chn, f in zip(
|
||||
["一", "二", "三", "四", "五"],
|
||||
["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"])},
|
||||
})
|
||||
logger.info("检查6命中异常 %d 人(经营系管理岗有延时加班补贴);花名册无职位序列跳过 %d 人",
|
||||
len(abnormal), no_seq_cnt)
|
||||
|
||||
# 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_otc_roster_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_otc_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_overtime_compensation_check(roster_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查6 延时加班验证完成】")
|
||||
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("检查6执行失败:%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()
|
||||
Reference in New Issue
Block a user