# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.roster.roster_query @FileName: roster_query.py @Author: 小布丁 @CreateTime: 2026-08-26 @Description: 花名册共享查询模块 —— 根据员工工号查询: 1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个); 2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单; 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。 两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。 @Version: 1.2.0 使用方式(库函数,参数直接传): from app.service.hrbp.ehr.roster.roster_query import ( find_store_manager, find_store_manager_batch, find_hr_personnel, find_hr_personnel_batch) - find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"} - find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]} - 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...} """ import numbers import os import sys from pathlib import Path # ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ---- def _find_project_root() -> str: for parent in Path(__file__).resolve().parents: if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file(): return str(parent) return str(Path(__file__).resolve().parents[5]) _root = _find_project_root() if _root not in sys.path: sys.path.insert(0, _root) try: import pandas as pd except ImportError as _import_err: raise RuntimeError( "缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n" f"缺失依赖详情: {_import_err}" ) from app.utils.logger import get_logger # noqa: E402 logger = get_logger(__name__) # ==================== 路径 & 常量配置 ==================== # 默认花名册路径(告知书制作与下发) DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 花名册字段列名(与 aa.md 字段一致) COL_NAME = "姓名" # 姓名 COL_CODE = "工号" # 工号 COL_DEPT2 = "二级部门" # 二级部门(经营中心) COL_DEPT4 = "四级部门" # 四级部门 COL_POSITION = "岗位" # 岗位 # 岗位关键字(岗位字段包含对应关键字即视为该岗位) MANAGER_KEYWORD = "店长" # 店长岗位关键字 HR_KEYWORD = "人事" # 人事岗位关键字 DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记 # 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单 DEPT2_HR_OVERRIDE = { "石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}], } # ==================== 工具函数 ==================== def _to_text(value): """将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。 整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。 """ if value is None: return None try: if pd.isna(value): return None except (TypeError, ValueError): pass if isinstance(value, numbers.Integral): return str(int(value)) if isinstance(value, numbers.Real): f = float(value) if f.is_integer(): return str(int(f)) return str(value) def _read_roster(roster_path): """读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。 Args: roster_path: 花名册文件路径 Returns: pd.DataFrame Raises: FileNotFoundError: 文件不存在 ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位) """ roster_path = os.path.abspath(roster_path) if not os.path.exists(roster_path): raise FileNotFoundError(f"花名册文件不存在:{roster_path}") # 先不设表头读取前几行,定位含「工号」字段的表头行 probe = pd.read_excel(roster_path, header=None, nrows=10) header_row = None for idx in range(len(probe)): if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any(): header_row = idx break if header_row is None: raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}") df = pd.read_excel(roster_path, header=header_row) required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION) missing = [c for c in required if c not in df.columns] if missing: raise ValueError(f"花名册缺少必需列:{missing}({roster_path})") return df def _prepare_df(df): """统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。""" df = df.copy() df[COL_CODE] = df[COL_CODE].map(_to_text) return df[df[COL_CODE].notna()] # ==================== 核心查询 ==================== def _find_store_manager_in_df(df, code): """在已读取的花名册 DataFrame 中查询店长(不读文件)。""" # 1. 校验工号是否存在 row = df[df[COL_CODE] == code] if row.empty: logger.warning("工号不存在:%s", code) return {"success": False, "error": f"工号不存在:{code}", "manager_code": None, "manager_name": None} # 2. 根据工号查四级部门 dept4 = _to_text(row.iloc[0][COL_DEPT4]) # 3. 无四级部门 -> 返回查询失败、空结果 if not dept4: logger.warning("员工(工号 %s)无四级部门", code) return {"success": False, "error": f"员工(工号 {code})无四级部门", "manager_code": None, "manager_name": None} # 4. 在该四级部门内找岗位包含「店长」的人 candidates = df[ (df[COL_DEPT4].map(_to_text) == dept4) & (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False)) ] if candidates.empty: logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code) return {"success": False, "error": f"四级部门「{dept4}」内未找到店长", "manager_code": None, "manager_name": None} # 5. 命中多个时取第一个(按花名册行序) first = candidates.iloc[0] manager_code = _to_text(first[COL_CODE]) manager_name = _to_text(first[COL_NAME]) or "" logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)", code, dept4, manager_name, manager_code) return {"success": True, "error": None, "manager_code": manager_code, "manager_name": manager_name} def _find_hr_personnel_in_df(df, code): """在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。""" # 1. 校验工号是否存在 row = df[df[COL_CODE] == code] if row.empty: logger.warning("工号不存在:%s", code) return {"success": False, "error": f"工号不存在:{code}", "dept": None, "personnel": []} # 2. 校验二级部门 dept2 = _to_text(row.iloc[0][COL_DEPT2]) or "" # 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册) if dept2 in DEPT2_HR_OVERRIDE: personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]] logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel)) return {"success": True, "error": None, "dept": dept2, "personnel": personnel} if DEPT2_MARK not in dept2: logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK) return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」", "dept": dept2 or None, "personnel": []} # 3. 查询该经营中心下岗位包含「人事」的所有名单 candidates = df[ (df[COL_DEPT2].map(_to_text) == dept2) & (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False)) ] personnel = [ {"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""} for _, r in candidates.iterrows() ] logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel)) return {"success": True, "error": None, "dept": dept2, "personnel": personnel} def _error_result(code, e): """读取花名册失败时的统一错误结果(店长/人事两种结构)。""" return { "store": {"success": False, "error": str(e), "manager_code": None, "manager_name": None}, "hr": {"success": False, "error": str(e), "dept": None, "personnel": []}, } def find_store_manager(code, roster_path=None): """根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。 Args: code: 员工工号(str 或 int,如 "37036835" / 37036835) roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH Returns: dict: success: bool 是否查询成功 error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常) manager_code: str|None 店长工号 manager_name: str|None 店长姓名 """ roster_path = roster_path or DEFAULT_ROSTER_PATH code = _to_text(code) if not code: return {"success": False, "error": f"工号为空:{code!r}", "manager_code": None, "manager_name": None} try: df = _prepare_df(_read_roster(roster_path)) except Exception as e: logger.error("读取花名册失败:%s", e) return _error_result(code, e)["store"] return _find_store_manager_in_df(df, code) def find_store_manager_batch(codes, roster_path=None): """批量查询多个工号的店长(花名册只读一次)。 Args: codes: 工号列表(str/int) roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH Returns: dict: {工号: find_store_manager 的返回结果, ...} """ roster_path = roster_path or DEFAULT_ROSTER_PATH try: df = _prepare_df(_read_roster(roster_path)) except Exception as e: logger.error("读取花名册失败:%s", e) err = _error_result(None, e)["store"] return {_to_text(c): dict(err) for c in codes} return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes} def find_hr_personnel(code, roster_path=None): """根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。 Args: code: 员工工号(str 或 int) roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH Returns: dict: success: bool 是否查询成功 error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常) dept: str|None 二级部门(经营中心) personnel: list 人事名单 [{"工号": str, "姓名": str}, ...] """ roster_path = roster_path or DEFAULT_ROSTER_PATH code = _to_text(code) if not code: return {"success": False, "error": f"工号为空:{code!r}", "dept": None, "personnel": []} try: df = _prepare_df(_read_roster(roster_path)) except Exception as e: logger.error("读取花名册失败:%s", e) return _error_result(code, e)["hr"] return _find_hr_personnel_in_df(df, code) def find_hr_personnel_batch(codes, roster_path=None): """批量查询多个工号所在经营中心的人事名单(花名册只读一次)。 Args: codes: 工号列表(str/int) roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH Returns: dict: {工号: find_hr_personnel 的返回结果, ...} """ roster_path = roster_path or DEFAULT_ROSTER_PATH try: df = _prepare_df(_read_roster(roster_path)) except Exception as e: logger.error("读取花名册失败:%s", e) err = _error_result(None, e)["hr"] return {_to_text(c): dict(err) for c in codes} return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}