feat(xq0011): 支持检查项选择并增加岗位等核心字段到异常名单

This commit is contained in:
2026-09-29 08:47:27 +08:00
parent 87f995ca47
commit f8f108af5d
100 changed files with 11920 additions and 1121 deletions
@@ -11,6 +11,8 @@
"""
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
@@ -19,13 +21,18 @@ 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 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
@@ -218,16 +225,6 @@ def _seal_path(save_dir: str, 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]:
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
@@ -268,6 +265,9 @@ def _load_roster_maps(roster_path: str) -> Tuple[Dict[str, dict], Set[str]]:
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
@@ -301,21 +301,45 @@ DEPT_ORG_FIELDS = ("DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
def enrich_dept_fields(target: dict, code: str, rec: dict = None,
roster_path: str = None) -> dict:
"""异常名单行回填「所属单位 + 一级~五级部门」:优先花名册(按工号),兜底封存记录字段。
"""异常名单行回填「所属单位 + 一级~五级部门 + 岗位 + 入职/离职时间」:
优先花名册(按工号),兜底封存记录字段。
Args:
target: 待回填的行 dict(就地修改并返回)。
code: 37工号。
rec: 封存记录行(兜底部门来源),可为 None。
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["入职时间"] = info.get("入职时间") or _clean(rec.get("join_date"))
# 离职时间以封存记录为准(封存的是检查月当月实际状态):存在离职后又复职的员工,
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底
target["离职时间"] = _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]:
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
@@ -356,7 +380,7 @@ def export_seal_data(month: str = None, save_dir: str = None) -> List[dict]:
os.makedirs(save_dir, exist_ok=True)
path = _seal_path(save_dir, ym)
try:
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
_write_seal_rows_lowmem(filtered, path)
except PermissionError:
raise RuntimeError(
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
@@ -376,6 +400,10 @@ def load_seal_rows(month: str = None, save_dir: str = None) -> List[dict]:
"""
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(
@@ -395,5 +423,137 @@ def load_seal_rows(month: str = None, save_dir: str = None) -> List[dict]:
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