chore: 清理废弃插件与冗余文档,重构项目目录结构
1. 删除旧版xq0031_xq0032插件的冗余UI源码与配置文件 2. 迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录 3. 清理过期的需求列表、评分文档与流程底稿 4. 更新.gitignore匹配规则,适配新的目录结构
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""临时验证:技师岗/黄泥磅 是否在考勤方案列表中存在。验证后删除。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import (
|
||||
HR_BASE_URL, build_hr_session, hr_request_json, fetch_cur_user_info, _clean,
|
||||
)
|
||||
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
BASE = {
|
||||
"struTreeCode": "cq37du",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rule_name": "", "dk_num_type": "", "type": "", "containLower": "",
|
||||
"team_name": "", "work_date_name": "", "paiban_type": "",
|
||||
"IN_USE": "1", "start": "0", "sortType": "desc",
|
||||
"sortName": "t.operate_time", "pageNo": "1", "pageSize": "50",
|
||||
}
|
||||
|
||||
|
||||
def probe(label, **overrides):
|
||||
params = dict(BASE)
|
||||
params.update(overrides)
|
||||
d = hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
data = d.get("data") or {}
|
||||
lst = data.get("list") or []
|
||||
print(f"--- {label}: total={data.get('total')}")
|
||||
for x in lst:
|
||||
print(" ", _clean(x.get("teamName")))
|
||||
|
||||
|
||||
session = build_hr_session()
|
||||
fetch_cur_user_info(session)
|
||||
|
||||
probe("team_name=技师岗", team_name="技师岗")
|
||||
probe("team_name=黄泥磅", team_name="黄泥磅")
|
||||
probe("team_name=技师", team_name="技师")
|
||||
@@ -0,0 +1,608 @@
|
||||
# -*- 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) 应勤天(aa.md 三连接口,全量缓存避免逐人查询):
|
||||
a) 查询所有考勤方案 rf_p_kq_team_ajax_list → 每个 team 的 teamId/teamName;
|
||||
b) 按 teamId 查方案扩展表 rf_s_kq_team_extend_table_select → ext_minyq_plan_id;
|
||||
c) 按 teamId 查应勤天方案 rf_s_kq_team_minyq_plan_up_query_all(组织级全量方案,
|
||||
任意 teamId 返回一致,只查一次缓存),按 minyq_plan_id == ext_minyq_plan_id
|
||||
过滤,取 month_XX 当月应勤天。
|
||||
员工 排班 team_name ↔ 考勤方案 teamName 精确匹配。
|
||||
「排班方案 → 当月应勤天」映射结果做 1 天文件缓存:当天首次运行拉取并落盘,
|
||||
同一天后续运行直接读缓存;次日自动失效重新拉取,避免方案改动后误用旧数据。
|
||||
4) 技师(排班方案名含「技师岗」):固定按 8 天休息,不查询应勤天方案。
|
||||
|
||||
输出:
|
||||
出勤排休验证异常_{月份}_{时间戳}.xlsx 异常名单(含 应勤天/实际出勤天/正休/标准 便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json),
|
||||
本模块运行时直连 排班接口 + 应勤天方案接口 拉取实时数据。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_arc_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_arc_cache_dir 应勤天方案缓存目录(默认 %LOCALAPPDATA%\\37duAutomation\\cache)
|
||||
@Version: 1.1.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, _APP_DATA_DIR,
|
||||
build_hr_session, hr_request_json, fetch_cur_user_info,
|
||||
_relogin_get_user_id, _clean, enrich_dept_fields, 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:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 应勤天方案缓存:排班方案 → 当月应勤天 映射结果缓存 1 天(当天复用,次日失效重拉)。
|
||||
# 与共享登录态同放 AppData 根(%LOCALAPPDATA%\37duAutomation\cache),不污染报告输出目录。
|
||||
TEAM_PLAN_CACHE_DIR = os.getenv("monthly_arc_cache_dir") or os.path.join(_APP_DATA_DIR, "cache")
|
||||
|
||||
# 排班接口(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:查询所有考勤方案,data.list 每条含 teamId/teamName)
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
TEAM_PAGE_SIZE = 50
|
||||
|
||||
# 方案查询接口(aa.md:按 teamId 查扩展表,取 ext_minyq_plan_id)
|
||||
TEAM_EXTEND_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_extend_table_select/redApiExec.mc"
|
||||
|
||||
# 应勤天方案接口(aa.md:按 teamId 查组织级全量方案,任意 teamId 返回一致,按 minyq_plan_id 过滤)
|
||||
TEAM_PLAN_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_minyq_plan_up_query_all/redApiExec.mc"
|
||||
|
||||
# 技师固定正休标准(排班方案名含「技师岗」,不查询应勤天方案,固定按 8 天休息)
|
||||
TECHNICIAN_KEYWORD = "技师岗"
|
||||
TECHNICIAN_REST_STANDARD = 8
|
||||
|
||||
# 异常类型(固定几种,便于筛选;详细说明一律放「异常明细」列)
|
||||
ABNORMAL_TYPE_OVER_WORK = "出勤天数超过应勤天"
|
||||
ABNORMAL_TYPE_OVER_REST = "正休天数超过标准"
|
||||
ABNORMAL_TYPE_NO_PLAN = "排班方案未匹配应勤天"
|
||||
|
||||
# 封存字段(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
|
||||
|
||||
|
||||
# ==================== 考勤方案 → 应勤天接口(aa.md 三连接口) ====================
|
||||
def fetch_team_page(session, page_no=1, page_size=TEAM_PAGE_SIZE):
|
||||
"""请求单页考勤方案列表。data.list 每条含 teamId/teamName 等。"""
|
||||
params = {
|
||||
"struTreeCode": "cq37du",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rule_name": "", "dk_num_type": "", "type": "", "containLower": "",
|
||||
"team_name": "", "work_date_name": "", "paiban_type": "",
|
||||
"IN_USE": "1", "start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc", "sortName": "t.operate_time",
|
||||
"pageNo": page_no, "pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
|
||||
|
||||
def fetch_all_teams(session) -> List[dict]:
|
||||
"""分页抓取全部考勤方案(aa.md:rf_p_kq_team_ajax_list,全集团 177 个)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_team_page(session, page_no)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤方案登录态过期,自动补登录后续抓")
|
||||
session, _ = _relogin_get_user_id()
|
||||
data = fetch_team_page(session, page_no)
|
||||
if data.get("code") != 200:
|
||||
logger.error("考勤方案第 %d 页请求失败:%s", page_no, data.get("message"))
|
||||
break
|
||||
body = data.get("data") or {}
|
||||
page_list = body.get("list") or []
|
||||
if not page_list:
|
||||
logger.info("考勤方案无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = body.get("pageCount") or 1
|
||||
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 fetch_team_extend(session, team_id: str) -> str:
|
||||
"""按 teamId 查方案扩展表,返回 ext_minyq_plan_id(无则空串)。"""
|
||||
data = hr_request_json(session, "POST", TEAM_EXTEND_URL,
|
||||
{"team_id": team_id}, "方案查询")
|
||||
if data.get("code") != 200:
|
||||
return ""
|
||||
rows = data.get("data") or []
|
||||
if not rows:
|
||||
return ""
|
||||
return _clean(rows[0].get("ext_minyq_plan_id"))
|
||||
|
||||
|
||||
def fetch_team_plans(session, team_id: str) -> List[dict]:
|
||||
"""按 teamId 查应勤天方案(组织级全量方案,任意 teamId 返回一致)。"""
|
||||
data = hr_request_json(session, "POST", TEAM_PLAN_URL, {
|
||||
"rootId": "cq37du", "STRU_TREE_CODE": "cq37du",
|
||||
"teamId": team_id, "is_show_parent": "0",
|
||||
}, "应勤天方案")
|
||||
if data.get("code") != 200:
|
||||
return []
|
||||
return data.get("data") or []
|
||||
|
||||
|
||||
def build_team_plan_map(session, teams: List[dict], ym: str) -> Dict[str, dict]:
|
||||
"""全量缓存 考勤方案 → 当月应勤天(teamName → {yq_day, plan_code, plan_name})。
|
||||
|
||||
流程(aa.md):
|
||||
1) 应勤天方案按任意 teamId 查一次全量缓存(组织级方案一致),按 minyq_plan_id 索引;
|
||||
2) 逐个 teamId 查方案扩展表拿 ext_minyq_plan_id,再取对应方案当月应勤天。
|
||||
"""
|
||||
if not teams:
|
||||
return {}
|
||||
# 1) 应勤天方案全量缓存(取前几个 team 直到拉到方案)
|
||||
plans: List[dict] = []
|
||||
for team in teams[:5]:
|
||||
plans = fetch_team_plans(session, _clean(team.get("teamId")))
|
||||
if plans:
|
||||
break
|
||||
if not plans:
|
||||
raise RuntimeError("未拉取到应勤天方案,请确认方案接口已配置。")
|
||||
plan_by_id = {_clean(p.get("minyq_plan_id")): p for p in plans
|
||||
if _clean(p.get("minyq_plan_id"))}
|
||||
logger.info("应勤天方案全量缓存:%d 个(%s)", len(plan_by_id), ym)
|
||||
month_key = f"month_{ym[5:7]:>02}"
|
||||
# 2) 逐个 team 查扩展表 → ext_minyq_plan_id → 当月应勤天
|
||||
team_map: Dict[str, dict] = {}
|
||||
miss_ext = miss_plan = 0
|
||||
for team in teams:
|
||||
team_id = _clean(team.get("teamId"))
|
||||
team_name = _clean(team.get("teamName"))
|
||||
if not team_id or not team_name:
|
||||
continue
|
||||
try:
|
||||
ext_plan_id = fetch_team_extend(session, team_id)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("方案查询登录态过期,自动补登录后续抓")
|
||||
session, _ = _relogin_get_user_id()
|
||||
ext_plan_id = fetch_team_extend(session, team_id)
|
||||
except Exception:
|
||||
logger.error("方案查询异常 teamId=%s,跳过", team_id)
|
||||
continue
|
||||
if not ext_plan_id:
|
||||
miss_ext += 1
|
||||
continue
|
||||
plan = plan_by_id.get(ext_plan_id)
|
||||
if not plan:
|
||||
miss_plan += 1
|
||||
continue
|
||||
yq_day = _num(plan.get(month_key))
|
||||
if yq_day <= 0:
|
||||
continue
|
||||
team_map[team_name] = {
|
||||
"yq_day": yq_day,
|
||||
"plan_code": _clean(plan.get("plan_code")),
|
||||
"plan_name": _clean(plan.get("plan_name")),
|
||||
"ext_minyq_plan_id": ext_plan_id,
|
||||
"team_id": team_id,
|
||||
}
|
||||
time.sleep(0.1)
|
||||
logger.info("考勤方案应勤天缓存完成:%d/%d 个 team(无方案 %d、方案未匹配 %d)",
|
||||
len(team_map), len(teams), miss_ext, miss_plan)
|
||||
return team_map
|
||||
|
||||
|
||||
# ==================== 应勤天方案 1 天文件缓存(当天复用,次日失效重拉) ====================
|
||||
def _team_plan_cache_path(ym: str) -> str:
|
||||
"""应勤天方案缓存文件路径(按检查月份区分,因应勤天随月份变化)。"""
|
||||
return os.path.join(TEAM_PLAN_CACHE_DIR, f"应勤天方案缓存_{ym}.json")
|
||||
|
||||
|
||||
def _load_team_plan_cache(cache_path: str, ym: str) -> Optional[Dict[str, dict]]:
|
||||
"""读取并校验应勤天方案缓存:仅「同月份且 cached_at 为今天」才复用。"""
|
||||
if not os.path.exists(cache_path):
|
||||
return None
|
||||
try:
|
||||
with open(cache_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except (OSError, ValueError) as e:
|
||||
logger.warning("应勤天方案缓存读取失败(%s),重新拉取", e)
|
||||
return None
|
||||
if data.get("month") != ym or data.get("cached_at") != date.today().isoformat():
|
||||
return None
|
||||
team_map = data.get("teams") or {}
|
||||
if not team_map:
|
||||
return None
|
||||
logger.info("命中应勤天方案缓存(%s 生成,当天有效):%d 个考勤方案",
|
||||
data["cached_at"], len(team_map))
|
||||
return team_map
|
||||
|
||||
|
||||
def _save_team_plan_cache(cache_path: str, ym: str, team_map: Dict[str, dict]) -> None:
|
||||
"""写入应勤天方案缓存(覆盖式,记录生成日期;写失败不影响本次检查)。"""
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
payload = {"month": ym, "cached_at": date.today().isoformat(), "teams": team_map}
|
||||
try:
|
||||
with open(cache_path, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, indent=2)
|
||||
logger.info("应勤天方案缓存已写入(%s):%s", ym, cache_path)
|
||||
except OSError as e:
|
||||
logger.warning("应勤天方案缓存写入失败(%s),不影响本次检查", e)
|
||||
|
||||
|
||||
def load_team_plan_cached(session, ym: str) -> Dict[str, dict]:
|
||||
"""取 排班方案 → 当月应勤天 映射(带 1 天文件缓存)。
|
||||
|
||||
当天缓存命中直接复用(跳过 考勤方案列表/方案扩展/应勤天方案 三连接口);
|
||||
缓存缺失或过期(超过当天)重新拉取并覆盖写入。
|
||||
"""
|
||||
cache_path = _team_plan_cache_path(ym)
|
||||
cached = _load_team_plan_cache(cache_path, ym)
|
||||
if cached is not None:
|
||||
return cached
|
||||
teams = fetch_all_teams(session)
|
||||
if not teams:
|
||||
raise RuntimeError("未拉取到考勤方案列表,请确认方案接口已配置。")
|
||||
team_map = build_team_plan_map(session, teams, ym)
|
||||
_save_team_plan_cache(cache_path, ym, team_map)
|
||||
return team_map
|
||||
|
||||
|
||||
# ==================== 排班接口(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,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
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)
|
||||
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. 拉取全部考勤方案 → 应勤天(aa.md 三连接口,全量缓存避免逐人查询;
|
||||
# 映射结果带 1 天文件缓存,当天首次运行拉取,后续运行直接读缓存)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId")) # 登录态校验 + 取 user_id(排班接口复用)
|
||||
if not user_id:
|
||||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||||
team_plan = load_team_plan_cached(session, 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. 逐人校验:技师固定正休≤8天;其余 实际出勤天≤应勤天、正休≤当月天数-应勤天
|
||||
abnormal: List[dict] = []
|
||||
no_plan_match = 0
|
||||
tech_cnt = 0
|
||||
for code, rec in seal_map.items():
|
||||
team = staff_team.get(code)
|
||||
if not team:
|
||||
continue # 排班无方案(无排班/全休息),跳过不误报
|
||||
actual_day = _num(rec.get(SEAL_ACTUAL_WORK_FIELD))
|
||||
rest_day = _num(rec.get(SEAL_REST_FIELD))
|
||||
# 技师:固定按 8 天休息,只查正休
|
||||
if TECHNICIAN_KEYWORD in team:
|
||||
tech_cnt += 1
|
||||
if rest_day > TECHNICIAN_REST_STANDARD:
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_OVER_REST,
|
||||
f"技师排班方案「{team}」,固定正休{TECHNICIAN_REST_STANDARD}天,"
|
||||
f"实际正休{rest_day:g}天,超出{rest_day - TECHNICIAN_REST_STANDARD:g}天",
|
||||
{"yq_day": "", "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": TECHNICIAN_REST_STANDARD}))
|
||||
continue
|
||||
info = team_plan.get(team)
|
||||
if not info:
|
||||
no_plan_match += 1
|
||||
logger.warning("工号 %s 排班方案「%s」未匹配到应勤天方案,输出异常", code, team)
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_NO_PLAN,
|
||||
f"排班方案「{team}」未匹配到应勤天方案,请核对",
|
||||
{"yq_day": "", "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": ""}))
|
||||
continue
|
||||
yq_day = info["yq_day"]
|
||||
rest_standard = month_days - yq_day
|
||||
plan_desc = f"{info['plan_code']} {info['plan_name']}(方案「{team}」)"
|
||||
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 人,方案未匹配异常 %d 人",
|
||||
len(abnormal), tech_cnt, 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,366 @@
|
||||
# -*- 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 enrich_dept_fields, 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:
|
||||
"""构造异常名单行(统一字段,部门由花名册回填)。"""
|
||||
row = {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": abnormal_type,
|
||||
"异常明细": detail,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
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,387 @@
|
||||
# -*- 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 (
|
||||
build_hr_session, enrich_dept_fields, 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(rec: dict, ym: str, detail: str) -> dict:
|
||||
"""构造异常名单行(37工号取封存记录工号,部门由花名册回填)。"""
|
||||
code = _clean(rec.get("base_code")) or _clean(rec.get("seal_base_code"))
|
||||
row = {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"异常明细": detail,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
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(rec, ym, "实时统计记录缺失,无法确认封存为最新值"))
|
||||
continue
|
||||
diffs = _compare_fields(rec, stat_rec)
|
||||
if not diffs:
|
||||
continue
|
||||
diff_cnt += 1
|
||||
abnormal.append(_build_abnormal(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,232 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: monthly_report_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-21
|
||||
@UpdateTime: 2026-09-21
|
||||
@Description: 考勤月报封存检查 - 汇总执行与单工作簿输出(影刀单文件,自包含)。
|
||||
依次运行检查1~检查6,将各异常名单合并写入一个 Excel 工作簿(每个检查一个 sheet),
|
||||
并生成「汇总」sheet 概览各检查异常人数。各检查模块仍保留独立输出文件,便于单独排查。
|
||||
|
||||
运行前置:需先运行「seal_data_export.py」导出当月预处理封存表,并完成
|
||||
「37du花名册导出」「37du调动台账导出」(统一输出到 D:\\资料\\人资\\考勤月报封存检查)。
|
||||
|
||||
输出:
|
||||
考勤月报封存检查_{月份}_{时间戳}.xlsx 单工作簿(汇总 + 检查1~6 共 7 个 sheet)
|
||||
|
||||
环境变量(可选):
|
||||
monthly_report_save_dir 汇总工作簿输出目录(默认 D:\\资料\\人资\\考勤月报封存检查)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Callable, Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 同目录模块引入(各检查模块,复用其 run_* 与输出列定义) ====================
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from working_days_shift_check import ( # noqa: E402
|
||||
run_working_days_shift_check, OUTPUT_COLUMNS as COL_CHECK1,
|
||||
)
|
||||
from attendance_rest_check import ( # noqa: E402
|
||||
run_attendance_rest_check, OUTPUT_COLUMNS as COL_CHECK2,
|
||||
)
|
||||
from latest_seal_check import ( # noqa: E402
|
||||
run_latest_seal_check, OUTPUT_COLUMNS as COL_CHECK3,
|
||||
)
|
||||
from full_attendance_check import ( # noqa: E402
|
||||
run_full_attendance_check, OUTPUT_COLUMNS as COL_CHECK4,
|
||||
)
|
||||
from unsealed_check import ( # noqa: E402
|
||||
run_unsealed_check, OUTPUT_COLUMNS as COL_CHECK5,
|
||||
)
|
||||
from overtime_compensation_check import ( # noqa: E402
|
||||
run_overtime_compensation_check, OUTPUT_COLUMNS as COL_CHECK6,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
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_report_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 检查元信息:(编号, sheet 名, 异常类型标签, run 函数, 输出列)
|
||||
CHECK_META: List[Tuple[str, str, str, Callable, List[str]]] = [
|
||||
("检查1", "检查1-在职天数排班异常", "在职天数 ≠ 应勤工作日 + 休息天",
|
||||
run_working_days_shift_check, COL_CHECK1),
|
||||
("检查2", "检查2-出勤及排休天数异常", "出勤/正休天数与应勤天标准不符",
|
||||
run_attendance_rest_check, COL_CHECK2),
|
||||
("检查3", "检查3-封存非最新值", "考勤封存非最新值,请重新封存",
|
||||
run_latest_seal_check, COL_CHECK3),
|
||||
("检查4", "检查4-全勤验证异常", "晋升当月要求全勤 / 迟到早退",
|
||||
run_full_attendance_check, COL_CHECK4),
|
||||
("检查5", "检查5-未封存名单", "考勤月报未封存,请处理",
|
||||
run_unsealed_check, COL_CHECK5),
|
||||
("检查6", "检查6-延时加班异常", "经营系管理岗不应享受延时加班,请核对",
|
||||
run_overtime_compensation_check, COL_CHECK6),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def run_all_checks(month: str = None) -> Dict[str, object]:
|
||||
"""依次运行检查1~6,返回各检查异常名单行列表(每项含编号/sheet/类型/行列表)。"""
|
||||
ym = _normalize_month(month)
|
||||
logger.info("===== 考勤月报封存检查(汇总)月份:%s =====", ym)
|
||||
results: List[dict] = []
|
||||
total = 0
|
||||
for no, sheet_name, label, run_fn, _cols in CHECK_META:
|
||||
try:
|
||||
rows = run_fn(month=ym)
|
||||
except Exception as e:
|
||||
logger.error("%s 执行失败:%s\n%s", no, e, traceback.format_exc())
|
||||
rows = []
|
||||
results.append({
|
||||
"no": no,
|
||||
"sheet_name": sheet_name,
|
||||
"label": label,
|
||||
"rows": rows,
|
||||
})
|
||||
total += len(rows)
|
||||
logger.info("%s 完成:异常 %d 人", no, len(rows))
|
||||
return {"ym": ym, "results": results, "total": total}
|
||||
|
||||
|
||||
def write_workbook(result: Dict[str, object]) -> str:
|
||||
"""将各检查异常名单写入单工作簿(汇总 + 每检查一个 sheet)。"""
|
||||
ym = result["ym"]
|
||||
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")
|
||||
# 汇总 sheet 行
|
||||
summary_rows = [{
|
||||
"序号": i + 1,
|
||||
"检查编号": it["no"],
|
||||
"异常类型": it["label"],
|
||||
"异常人数": len(it["rows"]),
|
||||
} for i, it in enumerate(result["results"])]
|
||||
summary_rows.append({
|
||||
"序号": len(summary_rows) + 1,
|
||||
"检查编号": "合计",
|
||||
"异常类型": "",
|
||||
"异常人数": result["total"],
|
||||
})
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary_rows).to_excel(
|
||||
writer, sheet_name="汇总", index=False)
|
||||
for it, (_, _, _, _, cols) in zip(result["results"], CHECK_META):
|
||||
rows = it["rows"]
|
||||
sheet_name = it["sheet_name"]
|
||||
if not rows:
|
||||
# 空结果也保留 sheet,便于人工核对
|
||||
pd.DataFrame(columns=cols).to_excel(
|
||||
writer, sheet_name=sheet_name, index=False)
|
||||
continue
|
||||
pd.DataFrame(rows, columns=cols).to_excel(
|
||||
writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("汇总工作簿已保存:%s(共 %d 人异常)", save_path, result["total"])
|
||||
return save_path
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_report_month") or (sys_argv_if(2))
|
||||
try:
|
||||
result = run_all_checks(month)
|
||||
save_path = write_workbook(result)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤月报封存检查汇总完成】")
|
||||
logger.info(" 检查月份:%s | 异常总人数:%d", result["ym"], result["total"])
|
||||
logger.info(" 汇总工作簿:%s", save_path)
|
||||
logger.info(" 各检查异常人数:%s", "、".join(
|
||||
f"{it['no']}:{len(it['rows'])}" for it in result["results"]))
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": result["total"],
|
||||
"detail": {it["no"]: len(it["rows"]) for it in result["results"]},
|
||||
"path": save_path}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("汇总检查执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,301 @@
|
||||
# -*- 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 enrich_dept_fields, 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(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"延时加班补贴小时": ot_hour,
|
||||
}, code, rec, roster_path))
|
||||
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()
|
||||
@@ -0,0 +1,531 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from functools import lru_cache
|
||||
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()
|
||||
|
||||
|
||||
# ==================== 日志(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_seal_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册(员工基础信息导出)路径 & 列(供:①剔除名单 ②异常名单 1-5 级部门回填)
|
||||
ROSTER_DEFAULT_PATH = os.getenv("monthly_seal_roster_path") or r"D:\资料\人资\考勤月报封存检查\员工花名册.xlsx"
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_DEPT_COLS = ("一级部门", "二级部门", "三级部门", "四级部门", "五级部门")
|
||||
# 一级部门等于该值的员工不参与本检查(花名册口径,整月剔除)
|
||||
EXCLUDE_FIRST_DEPT = "职业技术培训学校"
|
||||
# 一级部门为空 = 直属单位根节点的高管(未挂具体部门树),不参与本检查
|
||||
EXCLUDE_EMPTY_FIRST_DEPT = True
|
||||
|
||||
# 中文导出列 → 接口字段(来源: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",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 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 workflows/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 ""
|
||||
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 _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _seal_path(ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(SAVE_DIR, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
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 _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get(SEAL_UNIT_FIELD)) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
def _rec_code(rec: dict) -> str:
|
||||
"""封存记录工号(base_code 优先,seal_base_code 兜底)。"""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
c = _clean(rec.get(f))
|
||||
if c:
|
||||
return c
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 花名册:剔除名单 & 工号→1-5级部门 缓存 ====================
|
||||
@lru_cache(maxsize=4)
|
||||
def _load_roster_maps(roster_path: str) -> Tuple[Dict[str, dict], Set[str]]:
|
||||
"""读取花名册(当日全量导出,在职+离职)→ (工号→所属单位/1-5级部门 映射, 剔除工号集合)。
|
||||
|
||||
剔除口径(不参与本检查):
|
||||
1) 一级部门 = EXCLUDE_FIRST_DEPT(职业技术培训学校);
|
||||
2) 一级部门为空 = 直属单位根节点的高管(未挂具体部门树),同样不参与检查。
|
||||
同一工号可能多行(在职/离职并存),后读取的行覆盖先前的行。
|
||||
花名册缺失时返回空映射与空集合,不影响检查主流程(仅部门回填为空、不剔除)。
|
||||
"""
|
||||
if not roster_path or not os.path.exists(roster_path):
|
||||
logger.warning("花名册不存在,跳过部门回填与学校剔除:%s", roster_path)
|
||||
return {}, set()
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
dept_map: Dict[str, dict] = {}
|
||||
excluded: Set[str] = set()
|
||||
school_n = exec_n = 0
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code:
|
||||
continue
|
||||
info = {
|
||||
"所属单位": _clean(row.get(ROSTER_UNIT_COL)),
|
||||
**{c: _clean(row.get(c)) for c in ROSTER_DEPT_COLS},
|
||||
}
|
||||
dept_map[code] = info
|
||||
if _clean(row.get(ROSTER_DEPT_COLS[0])) == EXCLUDE_FIRST_DEPT:
|
||||
excluded.add(code)
|
||||
school_n += 1
|
||||
elif EXCLUDE_EMPTY_FIRST_DEPT and not _clean(row.get(ROSTER_DEPT_COLS[0])):
|
||||
excluded.add(code) # 部门树为空的高管,不参与检查
|
||||
exec_n += 1
|
||||
logger.info("花名册读取完成:%s(%d 人,剔除「%s」%d 人 + 高管 %d 人)",
|
||||
roster_path, len(dept_map), EXCLUDE_FIRST_DEPT, school_n, exec_n)
|
||||
return dept_map, excluded
|
||||
|
||||
|
||||
def load_roster_dept_map(roster_path: str = None) -> Dict[str, dict]:
|
||||
"""工号 → {所属单位, 一级部门~五级部门} 映射(进程内按路径缓存,一次读取)。"""
|
||||
dept_map, _ = _load_roster_maps(roster_path or ROSTER_DEFAULT_PATH)
|
||||
return dept_map
|
||||
|
||||
|
||||
def load_excluded_codes(roster_path: str = None) -> Set[str]:
|
||||
"""一级部门 = 职业技术培训学校 的剔除工号集合。"""
|
||||
_, excluded = _load_roster_maps(roster_path or ROSTER_DEFAULT_PATH)
|
||||
return set(excluded)
|
||||
|
||||
|
||||
DEPT_CN_ORDER = ("一", "二", "三", "四", "五")
|
||||
DEPT_ORG_FIELDS = ("DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE")
|
||||
|
||||
|
||||
def enrich_dept_fields(target: dict, code: str, rec: dict = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""异常名单行回填「所属单位 + 一级~五级部门」:优先花名册(按工号),兜底封存记录字段。
|
||||
|
||||
Args:
|
||||
target: 待回填的行 dict(就地修改并返回)。
|
||||
code: 37工号。
|
||||
rec: 封存记录行(兜底部门来源),可为 None。
|
||||
"""
|
||||
info = load_roster_dept_map(roster_path).get(code) or {}
|
||||
rec = rec or {}
|
||||
target["所属单位"] = info.get("所属单位") or _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
for chn, cn, f in zip(DEPT_CN_ORDER, ROSTER_DEPT_COLS, DEPT_ORG_FIELDS):
|
||||
target[cn] = info.get(cn) or _clean(rec.get(f))
|
||||
return target
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 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}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 2.1 花名册剔除:一级部门 = 职业技术培训学校 的不参与本检查
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(filtered)
|
||||
filtered = [rec for rec in filtered if _rec_code(rec) not in excluded]
|
||||
logger.info("花名册剔除不参与人员(「%s」/高管):%d 人 → %d 人",
|
||||
EXCLUDE_FIRST_DEPT, before, len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
path = _seal_path(ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
# 兜底剔除(防止历史封存表未做学校剔除):一级部门 = 职业技术培训学校 的工号
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(rows)
|
||||
rows = [r for r in rows if _rec_code(r) not in excluded]
|
||||
if len(rows) != before:
|
||||
logger.warning("读取封存表后按花名册剔除不参与人员(「%s」/高管)%d 人:%d → %d",
|
||||
EXCLUDE_FIRST_DEPT, before - len(rows), before, len(rows))
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), 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("封存数据导出失败:%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,324 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: unsealed_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查5「未封存名单」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
|
||||
考勤月报封存记录;有在职记录但无封存记录者输出异常名单,异常类型 = 「考勤月报未封存,请处理」。
|
||||
|
||||
数据来源:
|
||||
1) 在职记录(花名册):由「37du花名册导出」共享指令导出到固定路径,本脚本只读取。
|
||||
导出参数:在职状态 = 在职 + 离职(离职需设置离职时间范围 = 检查月月初 至今天),
|
||||
模板 = 员工基础信息。这样才能把「检查月内仍在职 / 检查月内离职」的人全部覆盖到。
|
||||
口径与封存表保持一致:仅检查所属单位白名单单位员工
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部)。
|
||||
2) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查5):
|
||||
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
|
||||
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
|
||||
- 仅统计所属单位在白名单内的员工;
|
||||
- 有在职记录但工号不在当月封存记录集合里 → 异常。
|
||||
|
||||
输出:
|
||||
未封存名单_{月份}_{时间戳}.xlsx 异常名单(含 37工号/姓名/月报检查月份/异常类型/所属单位/一~五级部门)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du花名册导出」指令导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_unsealed_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_unsealed_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import ( # noqa: E402
|
||||
SEAL_UNIT_WHITELIST, enrich_dept_fields, load_excluded_codes, 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_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工号", "姓名", "月报检查月份", "异常类型",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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,
|
||||
roster_path: str = None) -> List[dict]:
|
||||
"""遍历花名册,找出检查月在职、所属单位在白名单内但无封存记录的员工,返回名单行列表。
|
||||
|
||||
与封存预处理口径一致:一级部门 = 职业技术培训学校 的员工不参与本检查,直接剔除。
|
||||
"""
|
||||
abnormal: List[dict] = []
|
||||
seen: Set[str] = set()
|
||||
excluded = load_excluded_codes(roster_path)
|
||||
excluded_n = 0
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seen:
|
||||
continue # 花名册在职/离职同一工号可能多行,取一行即可
|
||||
seen.add(code)
|
||||
unit = _clean(row.get(ROSTER_UNIT_COL))
|
||||
if unit not in SEAL_UNIT_WHITELIST:
|
||||
continue # 与封存表预处理口径一致:仅检查白名单单位员工
|
||||
if code in excluded:
|
||||
excluded_n += 1
|
||||
continue # 一级部门 = 职业技术培训学校,不参与本检查
|
||||
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(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _clean(row.get(ROSTER_NAME_COL)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
}, code, None, roster_path))
|
||||
if excluded_n:
|
||||
logger.info("检查5 剔除「职业技术培训学校」%d 人", excluded_n)
|
||||
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}"
|
||||
logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读花名册(在职记录)
|
||||
df = _load_roster(roster_path)
|
||||
|
||||
# 2. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
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, roster_path)
|
||||
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,288 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: working_days_shift_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
|
||||
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
|
||||
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
|
||||
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
|
||||
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx。
|
||||
- 本模块只读取该预处理封存表,不再直连接口。
|
||||
- 每员工一条封存记录,检查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。)
|
||||
|
||||
输出:
|
||||
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.1.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 enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\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()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
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"] # 一~五级部门
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _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}"
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%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. 逐人检查
|
||||
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(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"在职天数": wd,
|
||||
"应勤工作日": int(work),
|
||||
"休息天": int(rest),
|
||||
"差值": diff,
|
||||
}, code, rec))
|
||||
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
|
||||
|
||||
# 3. 导出异常名单
|
||||
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_wd_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_working_days_shift_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查1 在职天数是否均排班验证完成】")
|
||||
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:
|
||||
logger.error("检查1执行失败:%s", e)
|
||||
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()
|
||||
Reference in New Issue
Block a user