447 lines
18 KiB
Python
447 lines
18 KiB
Python
# -*- 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 typing import Dict, List, Optional, 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')
|
||
|
||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||
if _ACCOUNT:
|
||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||
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")
|
||
|
||
# 中文导出列 → 接口字段(来源: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):
|
||
"""POST/GET 请求并校验返回 JSON;登录态失效抛 HRSessionExpiredError。
|
||
|
||
按项目规范做全局重试(最大 3 次,指数退避),仅在网络/服务端异常时重试;
|
||
登录态失效(HRSessionExpiredError)属确定性失败,直接抛出、不重试。
|
||
"""
|
||
last_exc = None
|
||
for attempt in range(1, 4):
|
||
try:
|
||
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}:登录态失效(返回非 JSON)")
|
||
return resp.json()
|
||
except HRSessionExpiredError:
|
||
raise
|
||
except Exception as e:
|
||
last_exc = e
|
||
if attempt < 3:
|
||
time.sleep(1.0 * (2 ** (attempt - 1)))
|
||
raise last_exc
|
||
|
||
|
||
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") or 0
|
||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据;
|
||
# 仅当 pageCount 存在且已到最后页,或返回行数不足一页时才结束分页。
|
||
if total_page and page_no >= total_page:
|
||
break
|
||
if len(page_list) < PAGE_MAX_SIZE:
|
||
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 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))
|
||
|
||
# 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")]
|
||
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()
|