# -*- coding: utf-8 -*- """XQ0011 考勤月报封存检查 插件 - 封存数据导出与预处理(由影刀版 seal_data_export.py 移植)。 统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→ 保存为预处理后的封存表(固定路径)。检查1~6 一律通过本模块 load_seal_rows() 读取预处理封存表。 插件化改造点(与影刀版差异): 1. HR 会话/用户 ID 由底座 RunContext 注入(config 全局钩子),不再自行读 cookies 构建; 2. 登录态失效不再自动补登(插件无法自动登录),直接抛错提示重新登录; 3. 日志统一转发到 ctx.log(config.logger)。 """ import json import os import time from collections import Counter from datetime import date, datetime from functools import lru_cache from typing import Dict, List, Optional, Set, Tuple import pandas as pd from ..config import ( logger, require_session, require_user_id, set_roster_path, get_roster_path, get_seal_rows, set_seal_rows, CACHE_DIR, SESSIONS_DIR, HR_BASE_URL, GET_CUR_USER_INFO_URL, SEAL_URL, SEAL_SQL_ID, PAGE_MAX_SIZE, DEFAULT_SAVE_DIR, SEAL_UNIT_WHITELIST, SEAL_CODE_FIELDS, EXCLUDE_FIRST_DEPT, EXCLUDE_EMPTY_FIRST_DEPT, ROSTER_CODE_COL, ROSTER_UNIT_COL, ROSTER_DEPT_COLS, ROSTER_JOIN_COL, ROSTER_LEAVE_COL, ) # 花名册岗位列(异常名单岗位回填来源;「员工基础信息」模板含此列) ROSTER_POST_COL = "岗位" # 所属单位白名单 / 剔除口径 / 花名册列定义统一取自 config # 中文导出列 → 接口字段(来源: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 登录态(底座注入) ==================== class HRSessionExpiredError(Exception): """HR 登录态失效(接口返回非 JSON,被重定向到登录页)。""" 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 _expired_error(label): return RuntimeError( f"{label}:HR 登录态已失效,无法自动补登。请在插件界面重新完成 HR 登录后重试。") # ==================== 考勤封存接口(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: raise _expired_error("考勤封存") 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 import time 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 _num(v) -> float: try: return float(_clean(v)) except (TypeError, ValueError): return 0.0 def _text(v) -> str: return _clean(v) 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 _fmt_date(v) -> str: """日期格式化为 yyyy-mm-dd(如 2026-09-21 00:00:00 → 2026-09-21)。""" d = _parse_date(v) return d.isoformat() if d else _clean(v)[:10] 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 _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 _month_days(ym: str) -> int: y, m = int(ym[:4]), int(ym[5:7]) return pd.Timestamp(year=y, month=m, day=1).daysinmonth def _seal_path(save_dir: str, ym: str) -> str: """预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。""" return os.path.join(save_dir, f"考勤封存数据_{ym}.xlsx") # ==================== 预处理:所属单位白名单筛选 ==================== def _filter_by_unit(rows: List[dict]) -> List[dict]: """封存数据预处理:仅保留所属单位在白名单内的记录。""" return [rec for rec in rows if _clean(rec.get("BELONG_UNIT_ORG_NAME")) 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)), "岗位": _clean(row.get(ROSTER_POST_COL)), "入职时间": _clean(row.get(ROSTER_JOIN_COL)), "离职时间": _clean(row.get(ROSTER_LEAVE_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 get_roster_path()) return dept_map def load_excluded_codes(roster_path: str = None) -> Set[str]: """一级部门 = 职业技术培训学校 的剔除工号集合。""" _, excluded = _load_roster_maps(roster_path or get_roster_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")) target["岗位"] = info.get("岗位") or _clean(rec.get("POST_ALIAS_NAME")) target["入职时间"] = _fmt_date(info.get("入职时间") or _clean(rec.get("join_date"))) # 离职时间以封存记录为准(封存的是检查月当月实际状态):存在离职后又复职的员工, # 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底。 # 优先取「封存快照」离职时间 seal_leaveOffice_date(保留检查月离职日期), # 其次当前离职时间 leaveOffice_date,最后花名册。 target["离职时间"] = _fmt_date( _clean(rec.get("seal_leaveOffice_date")) or _clean(rec.get("leaveOffice_date")) or info.get("离职时间")) 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 _write_seal_rows_lowmem(rows: List[dict], path: str) -> None: """低内存写出封存表:openpyxl write_only 逐行写入原始记录。 全集团封存数据可达数万行 × 数十列,pd.DataFrame(...).to_excel() 的峰值内存 (DataFrame 拷贝 + openpyxl 全量 cell + zip 压缩缓冲)极易触发 MemoryError; 改以 write_only 流式逐行写出,内存占用与行数无关。 """ from openpyxl import Workbook wb = Workbook(write_only=True) ws = wb.create_sheet(title="封存数据") columns = list(rows[0].keys()) if rows else [] rename = {en: cn for cn, en in CN_FIELD_MAP.items() if en in columns} ws.append([rename.get(c, c) for c in columns]) for rec in rows: ws.append([rec.get(c, "") for c in columns]) wb.save(path) # ==================== 导出 / 读取 ==================== def export_seal_data(month: str = None, save_dir: str = None) -> List[dict]: """拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。 Args: month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。 save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。 Returns: 预处理后的封存记录行列表(接口原始字段名)。 """ ym = _normalize_month(month) yearmonth = ym.replace("-", "") save_dir = save_dir or DEFAULT_SAVE_DIR logger.info("===== 封存数据导出与预处理,月份:%s =====", ym) # 1. 拉取当月全集团封存数据(base_code 留空批量) session = require_session() user_id = require_user_id() 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(save_dir, ym) try: _write_seal_rows_lowmem(filtered, path) 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, save_dir: str = None) -> List[dict]: """读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。 Args: month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。 save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。 Returns: 预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。 """ ym = _normalize_month(month) save_dir = save_dir or DEFAULT_SAVE_DIR # 进程内缓存:run() 预处理阶段已预读(含剔除),检查1~6 复用,避免各自重复读大文件 cached = get_seal_rows() if cached is not None: return cached path = _seal_path(save_dir, ym) if not os.path.exists(path): raise RuntimeError( f"未找到预处理封存表:{path}\n" "请先执行插件(封存导出步骤)导出并预处理当月封存数据后再检查。") 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)) set_seal_rows(rows) logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows)) return rows # ==================== 排班预处理(工号 → 检查月最早排班日期,与花名册映射一致供各检查复用) ==================== SHIFT_SQL_ID = "kq_count_SelectBanci" SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc" 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: raise _expired_error("排班数据") 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_earliest_shift_map(shift_rows: List[dict]) -> Dict[str, date]: """从全集团排班记录构建 工号 → 检查月最早排班日期 映射。 排班记录一条 = 一个员工当月逐日排班,字段为 {YYYY-MM-DD}_team_name; 取首个非空且非「休息」的日期作为该员工当月最早排班日。 供检查1「二次入职」识别:花名册入职日期晚于最早排班日期 = 入职前已有排班 = 二次入职。 """ mapping: Dict[str, date] = {} for row in shift_rows: code = _clean(row.get("base_code")) if not code: continue earliest: Optional[date] = None for key, val in row.items(): if not (isinstance(key, str) and key.endswith("_team_name")): continue if not _clean(val) or _clean(val) == "休息": continue d = _parse_date(key[:10]) if d and (earliest is None or d < earliest): earliest = d if earliest: mapping[code] = earliest return mapping def load_shift_data(ym: str) -> Tuple[Dict[str, date], Dict[str, str]]: """预处理:一次拉取检查月全集团排班,产出两个映射(供检查1/2 直接消费,不再各自请求)。 Returns: (工号 → 检查月最早排班日期, 工号 → 当月出现最多的排班方案名)。 失败(登录态失效等)时抛错,由调用方(run 预处理)决定降级策略。 """ session = require_session() user_id = require_user_id() total_days = pd.Timestamp(year=int(ym[:4]), month=int(ym[5:7]), day=1).daysinmonth begin = f"{ym}-01" end = f"{ym}-{total_days:02d}" shift_rows = fetch_all_shift(session, user_id, begin, end) return build_earliest_shift_map(shift_rows), build_staff_team_map(shift_rows) def _shift_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_staff_team_map(shift_rows: List[dict]) -> Dict[str, str]: """从全集团排班记录构建 工号 → 当月出现最多的排班方案名 映射(检查2 用)。""" mapping: Dict[str, str] = {} for row in shift_rows: code = _clean(row.get("base_code")) if not code: continue team = _shift_main_team(row) if team: mapping[code] = team return mapping