1. 新增OA电子签相关工具函数:补全签署状态、会话失效自愈、附件下载重试 2. 新增EHR花名册查询、导出、字典翻译全套API 3. 重构离职电子签审批流程,适配接口变更,补全电子签状态与附件源 4. 新增数据字典缓存与编码翻译能力
290 lines
12 KiB
Python
290 lines
12 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.ehr.common.hr_api
|
||
@FileName: roster.py
|
||
@Description: 员工花名册台账实时查询接口(纯 API 版,替代浏览器下载)。
|
||
与组织维护 org.py 同模式:queryRealTimeData.mc 分页查询;
|
||
commonQuery 由 common_query 自实现加密构造。
|
||
模板列映射对齐页面自定义导出模板:「员工基础信息」「雇主险增减员导出模板」。
|
||
@Version: 1.0.0
|
||
"""
|
||
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
from app.utils.logger import get_logger
|
||
from app.service.hrbp.ehr.common.common_query import build_condition, encode_common_query
|
||
from app.service.hrbp.ehr.common.config import (
|
||
ROSTER_QUERY_URL,
|
||
ROSTER_QUERY_BASE_PARAMS,
|
||
ROSTER_QUERY_CONDITIONS,
|
||
PAGE_MAX_SIZE,
|
||
)
|
||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||
from app.service.hrbp.ehr.common.hr_api.code_dict import code_to_name, get_code_dicts
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
# 在职状态编码(已通过抓包实证:在职抓包串 queryValue=1,离职抓包串 queryValue=2)
|
||
PERSON_STATUS_MAP = {"1": "在职", "2": "离职"}
|
||
|
||
# 字典字段 -> codeType(来源:花名册页面源码内嵌的字典定义,已实测接口可查)
|
||
ROSTER_CODE_TYPE_MAP = {
|
||
"hr_staff_base.sex": "COMMON.SEX", # 性别
|
||
"hr_staff_base.nation": "COMMON.NATION", # 民族
|
||
"hr_staff_base.identity": "COMMON.IDENTITY", # 用工类型
|
||
"hr_staff_base.marriage": "COMMON.MARRIAGE", # 婚姻状况
|
||
"hr_staff_base.from_nation": "COMMON.FROMNATION", # 国籍
|
||
"hr_staff_base.highedu": "HR_RECRUIT_EDU.EDUCATION", # 最高学历
|
||
}
|
||
|
||
# 需去掉时分秒的日期字段
|
||
_DATE_FIELDS = {"hr_staff_base.join_date", "hr_staff_base.leaveOffice_date",
|
||
"hr_staff_base.Regular_Time", "hr_staff_base.pre_correction_date"}
|
||
|
||
# ---------- 模板列映射(field, 列名),顺序与页面自定义导出模板一致 ----------
|
||
# 「员工基础信息」模板(31 列 + 序号,与抓包 exportFilters 完全一致)
|
||
ROSTER_FIELD_MAP_BASIC = [
|
||
("hr_staff_base.staff_name", "姓名"),
|
||
("hr_staff_base.base_code", "工号"),
|
||
("hr_staff_base.idCard", "证件号"),
|
||
("hr_staff_base.join_date", "入职时间"),
|
||
("hr_staff_base.leaveOffice_date", "离职时间"),
|
||
("pt_staff_stru.BELONG_UNIT_ORG_NAME", "所属单位"),
|
||
("pt_staff_stru.DEPT_ORG_NAME", "所属部门"),
|
||
("pt_staff_stru.DEPT_ORG_ONE", "一级部门"),
|
||
("pt_staff_stru.DEPT_ORG_TWO", "二级部门"),
|
||
("pt_staff_stru.DEPT_ORG_THREE", "三级部门"),
|
||
("pt_staff_stru.DEPT_ORG_FOUR", "四级部门"),
|
||
("pt_staff_stru.DEPT_ORG_FIVE", "五级部门"),
|
||
("pt_staff_stru.POST_ORG_NAME", "岗位"),
|
||
("hr_staff_base_ext.ext_technician_code", "技师工号"),
|
||
("hr_staff_base_ext.ext_star_level", "星级"),
|
||
("pt_staff_stru.first_type_id", "职位序列"),
|
||
("pt_staff_stru.POST_LEVEL_ID", "职衔"),
|
||
("pt_staff_stru.PT_POST_GRADE_ID", "职级"),
|
||
("pt_post_level.ext_grade_name", "职等"),
|
||
("hr_staff_base.mobile_phone", "手机号码"),
|
||
("hr_staff_base.person_status", "在职状态"),
|
||
("hr_staff_base_ext.ext_insurance_type", "参保类型"),
|
||
("pt_staff_stru.ORG_FULL_PATH", "组织全路径"),
|
||
("hr_staff_base.nation", "民族"),
|
||
("hr_staff_base.sex", "性别"),
|
||
("hr_staff_base.age", "年龄"),
|
||
("hr_staff_base.period", "试用期限(月)"),
|
||
("hr_staff_base.pre_correction_date", "试用期结束日期"),
|
||
("hr_staff_base_ext.ext_trans_type", "上下班交通方式"),
|
||
("hr_staff_base_ext.ext_recruit_way", "招聘渠道"),
|
||
("hr_staff_base.identity", "用工类型"),
|
||
]
|
||
|
||
# 「雇主险增减员导出模板」(14 列 + 序号,无三级/五级部门,顺序按模板)
|
||
ROSTER_FIELD_MAP_EMPLOYER = [
|
||
("pt_staff_stru.BELONG_UNIT_ORG_NAME", "所属单位"),
|
||
("pt_staff_stru.DEPT_ORG_ONE", "一级部门"),
|
||
("pt_staff_stru.DEPT_ORG_TWO", "二级部门"),
|
||
("pt_staff_stru.DEPT_ORG_FOUR", "四级部门"),
|
||
("hr_staff_base.base_code", "工号"),
|
||
("hr_staff_base.age", "年龄"),
|
||
("hr_staff_base.sex", "性别"),
|
||
("pt_staff_stru.POST_ORG_NAME", "岗位"),
|
||
("pt_staff_stru.first_type_id", "职位序列"),
|
||
("hr_staff_base_ext.ext_insurance_type", "参保类型"),
|
||
("hr_staff_base_ext.ext_trans_type", "上下班交通方式"),
|
||
("hr_staff_base.join_date", "入职时间"),
|
||
("hr_staff_base.staff_name", "姓名"),
|
||
("hr_staff_base.idCard", "证件号"),
|
||
]
|
||
|
||
# 模板名 -> 列映射
|
||
ROSTER_TEMPLATE_FIELD_MAPS = {
|
||
"员工基础信息": ROSTER_FIELD_MAP_BASIC,
|
||
"雇主险增减员导出模板": ROSTER_FIELD_MAP_EMPLOYER,
|
||
}
|
||
|
||
|
||
def get_date_params() -> Dict[str, str]:
|
||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月),与页面请求一致。"""
|
||
now = datetime.now()
|
||
year, month, day = now.year, now.month, now.day
|
||
|
||
# 上月(本月 1 号减一天即上月最后一天)
|
||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||
|
||
return {
|
||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||
"currentMonth": f"{year}{month:02d}",
|
||
"currentMonthBar": f"{year}-{month:02d}",
|
||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||
"curYearFirstMon": f"{year}01",
|
||
"curYearFirstMonBar": f"{year}-01",
|
||
}
|
||
|
||
|
||
def build_leave_conditions(leave_start: str, leave_end: str) -> List[Dict[str, str]]:
|
||
"""构造「离职人员」查询条件:person_status in (2) + 离职时间区间(等价页面离职筛选抓包串)。
|
||
|
||
Args:
|
||
leave_start: 离职开始日期,如 "2026-08-01"
|
||
leave_end: 离职结束日期,如 "2026-08-31"
|
||
|
||
Returns:
|
||
查询条件列表(可传给 fetch_roster_page / fetch_all_rosters 的 conditions)
|
||
"""
|
||
return [
|
||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||
query_text="1", left_bracket="(", right_bracket=")",
|
||
input_type="select"),
|
||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||
query_text="2", left_bracket="(", right_bracket=")",
|
||
input_type="multipleSelect"),
|
||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||
left_bracket="(", input_type="date"),
|
||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||
right_bracket=")", input_type="date"),
|
||
]
|
||
|
||
|
||
def build_in_service_conditions() -> List[Dict[str, str]]:
|
||
"""构造「在职人员」查询条件(主职 + person_status in (1),即默认抓包条件)。"""
|
||
return [dict(c) for c in ROSTER_QUERY_CONDITIONS]
|
||
|
||
|
||
def fetch_roster_page(
|
||
session,
|
||
page_no: int = 1,
|
||
page_size: int = PAGE_MAX_SIZE,
|
||
conditions: Optional[List[Dict[str, str]]] = None,
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
请求单页花名册数据。
|
||
|
||
Args:
|
||
session: 已登录的 requests.Session 对象
|
||
page_no: 页码(从 1 开始)
|
||
page_size: 每页条数(最大 500)
|
||
conditions: 查询条件列表;None 使用默认在职条件(ROSTER_QUERY_CONDITIONS)
|
||
|
||
Returns:
|
||
接口返回的 JSON 字典(datas 为花名册明细数组,count 总条数,pageCount 总页数)
|
||
|
||
Raises:
|
||
RuntimeError: 请求失败或响应异常
|
||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||
"""
|
||
params = ROSTER_QUERY_BASE_PARAMS.copy()
|
||
params["commonQuery"] = encode_common_query(
|
||
conditions if conditions is not None else ROSTER_QUERY_CONDITIONS)
|
||
params.update(get_date_params())
|
||
params.update({
|
||
"pageNo": str(page_no),
|
||
"pageSize": str(page_size),
|
||
"start": str((page_no - 1) * page_size),
|
||
"_t": str(int(time.time() * 1000)),
|
||
})
|
||
return hr_request_json(session, "POST", ROSTER_QUERY_URL, params, "员工花名册")
|
||
|
||
|
||
def fetch_all_rosters(
|
||
session,
|
||
conditions: Optional[List[Dict[str, str]]] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""
|
||
分页抓取全部花名册数据(默认在职人员,可传 conditions 查离职等)。
|
||
|
||
Args:
|
||
session: 已登录的 requests.Session 对象
|
||
conditions: 查询条件列表;None 使用默认在职条件
|
||
|
||
Returns:
|
||
花名册明细列表(接口 datas 字段内容)
|
||
|
||
Raises:
|
||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||
"""
|
||
all_rows: List[Dict[str, Any]] = []
|
||
page_no = 1
|
||
while True:
|
||
try:
|
||
data = fetch_roster_page(session, page_no, PAGE_MAX_SIZE, conditions)
|
||
except HRSessionExpiredError:
|
||
logger.warning("员工花名册 HR 登录态过期,重新登录后续抓")
|
||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||
session = refresh_hr_session()
|
||
data = fetch_roster_page(session, page_no, PAGE_MAX_SIZE, conditions)
|
||
|
||
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 = data.get("count", 0)
|
||
total_page = data.get("pageCount", 0)
|
||
logger.info("员工花名册已抓取 %d/%d 页,累计 %d/%d 条",
|
||
page_no, total_page, len(all_rows), total)
|
||
if page_no >= total_page:
|
||
break
|
||
page_no += 1
|
||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||
return all_rows
|
||
|
||
|
||
def fetch_roster_code_dicts(session, force_refresh: bool = False) -> Dict[str, Dict[str, str]]:
|
||
"""拉取花名册所需全部数据字典(带本地缓存),返回 {接口字段: {code: 名称}}。
|
||
|
||
Args:
|
||
session: 已登录的 requests.Session 对象
|
||
force_refresh: True 强制刷新缓存
|
||
"""
|
||
maps = get_code_dicts(session, list(ROSTER_CODE_TYPE_MAP.values()), force_refresh)
|
||
return {field: maps[ct] for field, ct in ROSTER_CODE_TYPE_MAP.items()}
|
||
|
||
|
||
def to_roster_rows(
|
||
datalist: List[Dict[str, Any]],
|
||
template: str = "员工基础信息",
|
||
code_dicts: Optional[Dict[str, Dict[str, str]]] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""将接口原始记录转换为指定模板列顺序的字典列表(含序号列)。
|
||
|
||
Args:
|
||
datalist: fetch_all_rosters / fetch_roster_page 返回的 datas 原始记录列表
|
||
template: 模板名(ROSTER_TEMPLATE_FIELD_MAPS 的键),默认「员工基础信息」
|
||
code_dicts: 字典映射 {接口字段: {code: 名称}}(fetch_roster_code_dicts 返回值),
|
||
提供时性别/民族/用工类型等编码字段翻译为文字;缺省保留原始编码
|
||
|
||
Returns:
|
||
按模板列顺序组织好的字典列表(首列为序号)
|
||
|
||
Raises:
|
||
ValueError: 模板名不存在
|
||
"""
|
||
field_map = ROSTER_TEMPLATE_FIELD_MAPS.get(template)
|
||
if field_map is None:
|
||
raise ValueError(f"未知花名册模板:{template}(可选:{list(ROSTER_TEMPLATE_FIELD_MAPS)})")
|
||
code_dicts = code_dicts or {}
|
||
|
||
rows: List[Dict[str, Any]] = []
|
||
for i, r in enumerate(datalist, 1):
|
||
row: Dict[str, Any] = {"序号": i}
|
||
for key, name in field_map:
|
||
value = r.get(key)
|
||
if key == "hr_staff_base.person_status":
|
||
value = PERSON_STATUS_MAP.get(str(value), value)
|
||
elif key in code_dicts:
|
||
value = code_to_name(value, code_dicts[key])
|
||
elif key in _DATE_FIELDS and value:
|
||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||
row[name] = value
|
||
rows.append(row)
|
||
return rows
|