feat: 新增花名册查询导出、电子签状态补全与会话自愈能力
1. 新增OA电子签相关工具函数:补全签署状态、会话失效自愈、附件下载重试 2. 新增EHR花名册查询、导出、字典翻译全套API 3. 重构离职电子签审批流程,适配接口变更,补全电子签状态与附件源 4. 新增数据字典缓存与编码翻译能力
This commit is contained in:
@@ -125,6 +125,64 @@ ORG_QUERY_BASE_PARAMS = {
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 员工花名册(实时数据查询接口,纯 API 版) ----------
|
||||
# 花名册台账实时数据查询(与组织维护 queryRealTimeData 同模式),返回 JSON(count/datas/pageCount)
|
||||
ROSTER_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ROSTER_TABLE_ID = "assemble-hr_staff_base"
|
||||
ROSTER_ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
|
||||
# 花名册查询默认条件(等价抓包串:主职 in (1) + 在职状态 in (1),即「在职主职在职人员」),
|
||||
# 需要查离职等其它状态时在调用方覆盖 conditions
|
||||
ROSTER_QUERY_CONDITIONS = [
|
||||
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", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ROSTER_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": ROSTER_TABLE_ID,
|
||||
"rosterId": ROSTER_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
# 由 ehr / oa 两系统统一引用,避免 oa 反向依赖 ehr。需要时从此处 import:
|
||||
# from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
|
||||
@@ -24,6 +24,16 @@ from app.service.hrbp.ehr.common.hr_api.attendance_stat import (
|
||||
fetch_all_attendance_stat,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.org import fetch_org_page, fetch_all_orgs, to_org_rows
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
fetch_roster_page,
|
||||
fetch_all_rosters,
|
||||
to_roster_rows,
|
||||
build_leave_conditions,
|
||||
build_in_service_conditions,
|
||||
fetch_roster_code_dicts,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import get_code_dicts, code_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_export import export_common_list, export_roster_excel
|
||||
|
||||
__all__ = [
|
||||
# base
|
||||
@@ -62,4 +72,17 @@ __all__ = [
|
||||
"fetch_org_page",
|
||||
"fetch_all_orgs",
|
||||
"to_org_rows",
|
||||
# roster
|
||||
"fetch_roster_page",
|
||||
"fetch_all_rosters",
|
||||
"to_roster_rows",
|
||||
"build_leave_conditions",
|
||||
"build_in_service_conditions",
|
||||
"fetch_roster_code_dicts",
|
||||
# code_dict
|
||||
"get_code_dicts",
|
||||
"code_to_name",
|
||||
# roster_export
|
||||
"export_common_list",
|
||||
"export_roster_excel",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: code_dict.py
|
||||
@FileName 备注: HR 平台通用数据字典接口(PtCodeTypeValue.mc),供各业务模块翻译编码字段。
|
||||
codeType 为「表名.字段名」格式(如 COMMON.SEX / WAGE.BANKTYPE),
|
||||
支持 codeType 参数逗号分隔批量查询;返回 {codeType: {code: [名称, ...]}}。
|
||||
本地缓存统一存放,默认 7 天过期(与 bank_dict 一致)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import BANK_DICT_URL
|
||||
from app.service.hrbp.common.hr_session import hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 字典缓存文件({codeType: {code: name}}),7 天过期
|
||||
_CODE_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60
|
||||
_CODE_DICT_FILE = os.path.join(get_sessions_dir(), "code_dicts.json")
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
"""读取本地字典缓存,异常返回空 dict。"""
|
||||
try:
|
||||
with open(_CODE_DICT_FILE, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_cache(maps: dict) -> None:
|
||||
"""写入本地字典缓存。"""
|
||||
os.makedirs(os.path.dirname(_CODE_DICT_FILE), exist_ok=True)
|
||||
with open(_CODE_DICT_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(maps, f, ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def _parse_items(raw) -> dict:
|
||||
"""将接口返回的字典项转换为 {code: 名称}。
|
||||
|
||||
兼容两种返回形态:
|
||||
- list[dict]: [{"code": "1", "name": "男", ...}, ...]
|
||||
- dict: {"1": ["男", ...], ...}(键值对形态)
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
return {str(code): (item[0] if isinstance(item, (list, tuple)) and item else "")
|
||||
for code, item in raw.items()}
|
||||
result = {}
|
||||
for item in raw or []:
|
||||
code = item.get("code", "")
|
||||
result[str(code)] = item.get("name", "")
|
||||
return result
|
||||
|
||||
|
||||
def get_code_dicts(session, code_types, force_refresh: bool = False) -> dict:
|
||||
"""批量获取数据字典(优先本地缓存,缺失/过期才请求接口)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
code_types: codeType 列表,如 ["COMMON.SEX", "COMMON.NATION"]
|
||||
force_refresh: True 强制重新请求接口刷新
|
||||
|
||||
Returns:
|
||||
{codeType: {code: 名称}} 字典(未命中的 codeType 值为空 dict)
|
||||
"""
|
||||
cache = {} if force_refresh else _load_cache()
|
||||
need = [ct for ct in code_types
|
||||
if ct not in cache or not isinstance(cache.get(ct), dict)]
|
||||
|
||||
# 缓存命中校验:文件整体过期时间(mtime)
|
||||
if need and not force_refresh and os.path.exists(_CODE_DICT_FILE):
|
||||
if time.time() - os.path.getmtime(_CODE_DICT_FILE) <= _CODE_DICT_EXPIRE_SEC:
|
||||
# 文件未过期但缺 key -> 记为空字典,避免反复请求不存在的类型
|
||||
for ct in need:
|
||||
cache.setdefault(ct, {})
|
||||
need = [ct for ct in need if not cache.get(ct)]
|
||||
|
||||
if need:
|
||||
payload = {
|
||||
"codeType": ",".join(need),
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = hr_request_json(session, "POST", BANK_DICT_URL, payload, "数据字典", timeout=30)
|
||||
for ct in need:
|
||||
raw = (resp.get("result") or {}).get(ct) or resp.get(ct)
|
||||
cache[ct] = _parse_items(raw) if raw else {}
|
||||
_save_cache(cache)
|
||||
logger.info("数据字典远程拉取完成:%s", {ct: len(cache[ct]) for ct in need})
|
||||
|
||||
return {ct: cache.get(ct, {}) for ct in code_types}
|
||||
|
||||
|
||||
def code_to_name(code, code_map: dict) -> Any:
|
||||
"""按字典映射翻译编码;未命中返回原值(None/空串原样返回)。"""
|
||||
if code is None or code == "":
|
||||
return code
|
||||
return code_map.get(str(code).strip(), code)
|
||||
@@ -0,0 +1,289 @@
|
||||
# -*- 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
|
||||
@@ -0,0 +1,177 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: roster_export.py
|
||||
@Description: 花名册异步导出(服务端生成 Excel,替代浏览器下载导出)。
|
||||
链路:访问台账页面绑定会话 -> ws/bridge 注册会话到 WS 容器 ->
|
||||
WebSocket 订阅主题(HR_DEFINED_HMC_EXPORT) -> POST exportCommonListData 提交任务 ->
|
||||
接收 WS 进度推送至 "--end--|文件路径" -> GET tempFile.mc 下载 Excel。
|
||||
服务端负责全部字典翻译(星级/参保类型/职衔/职级等),与页面导出结果一致。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import websocket
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.common_query import encode_common_query
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
ROSTER_ROSTER_ID,
|
||||
ROSTER_QUERY_BASE_PARAMS,
|
||||
ROSTER_QUERY_CONDITIONS,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
build_in_service_conditions,
|
||||
get_date_params,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_template import ROSTER_TEMPLATE_FILTERS
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 异步导出 WebSocket 主题与相关 URL(redseaWs.js 逻辑的服务端约定)
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
PAGE_URL = (f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ROSTER_ID}/getCustomCommonList.mc")
|
||||
EXPORT_URL = (f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ROSTER_ID}/exportCommonListData.mc")
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
|
||||
def _bind_session(session) -> None:
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise RuntimeError(f"ws/bridge 会话注册失败:{r.text[:100]}")
|
||||
|
||||
|
||||
def export_common_list(
|
||||
session,
|
||||
output_path: str,
|
||||
export_name: str = "员工基础信息",
|
||||
export_filters: Optional[str] = None,
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
progress_interval: int = 0,
|
||||
timeout: int = 300,
|
||||
) -> str:
|
||||
"""异步导出台账 Excel(服务端生成并翻译字典),下载保存到 output_path。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
output_path: Excel 保存路径
|
||||
export_name: 导出模板名(对应页面自定义导出模板)
|
||||
export_filters: 导出字段串(逗号分隔);None 则按模板名查 ROSTER_TEMPLATE_FILTERS
|
||||
conditions: 查询条件列表;None 使用默认在职条件
|
||||
progress_interval: 进度日志打印间隔(每 N 条打印一次,0 不打印中间进度)
|
||||
timeout: 等待导出完成的超时秒数
|
||||
|
||||
Returns:
|
||||
output_path(导出成功)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 提交导出失败 / 超时未收到文件地址 / 下载失败
|
||||
"""
|
||||
if export_filters is None:
|
||||
export_filters = ROSTER_TEMPLATE_FILTERS.get(export_name)
|
||||
if not export_filters:
|
||||
raise ValueError(f"未知导出模板:{export_name},且未提供 export_filters")
|
||||
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(
|
||||
conditions if conditions is not None else ROSTER_QUERY_CONDITIONS)
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": export_name, "exportFilters": export_filters},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(%s)", export_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url: Optional[str] = None
|
||||
deadline = time.time() + timeout
|
||||
ws.settimeout(timeout)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if progress_interval and txt.startswith("正在生成"):
|
||||
try:
|
||||
if int("".join(filter(str.isdigit, txt))) % progress_interval == 0:
|
||||
logger.info("导出进度:%s", txt)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({timeout}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("Excel 已保存:%s(%d 字节)", output_path, len(dl.content))
|
||||
return output_path
|
||||
|
||||
|
||||
# 便捷封装:在职人员按模板导出
|
||||
def export_roster_excel(
|
||||
session,
|
||||
output_path: str,
|
||||
template: str = "员工基础信息",
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
) -> str:
|
||||
"""按模板导出花名册 Excel(默认在职人员,conditions 可传离职等条件)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
output_path: Excel 保存路径
|
||||
template: 模板名(ROSTER_TEMPLATE_FILTERS 的键)
|
||||
conditions: 查询条件;None 使用默认在职条件
|
||||
"""
|
||||
return export_common_list(
|
||||
session, output_path,
|
||||
export_name=template,
|
||||
export_filters=ROSTER_TEMPLATE_FILTERS.get(template),
|
||||
conditions=conditions if conditions is not None else build_in_service_conditions(),
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: roster_template.py
|
||||
@Description: 花名册自定义导出模板的字段串(exportFilters),顺序与页面导出模板列顺序一致。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_BASIC = ",".join([
|
||||
"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_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"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", # 证件号
|
||||
])
|
||||
|
||||
# 模板名 -> exportFilters 字段串
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"员工基础信息": ROSTER_TEMPLATE_FILTERS_BASIC,
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
Reference in New Issue
Block a user