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,
|
||||
}
|
||||
@@ -77,7 +77,10 @@ LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_reco
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件。
|
||||
# 注意:该接口要求有效 EHR 会话(hr.37du.co),会话失效时返回登录页 HTML 或
|
||||
# "外部用户未登录,无法访问",而非报错状态码;前端"在线预览"走的是
|
||||
# PtFjk.mc?method=fjkViewPageDown(返回 HTML 预览页),RPA 下载不使用该地址
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 附件默认保存目录
|
||||
ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件"
|
||||
@@ -88,6 +91,18 @@ FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 离职电子签签章附件默认保存目录
|
||||
RESIGN_ATTACHMENT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
|
||||
# 电子签真实签署状态查询接口(hr 域名,按 main_id 即合同业务主键查询):
|
||||
# is_initiate_sign 是否已发起电子签(hr_staff_contract.is_initiate_sign)
|
||||
# sign_status_yg 员工签署状态(esign_sigin_state)
|
||||
# sign_status_qy 企业签署状态(esign_sigin_state)
|
||||
# file 签章附件 fileId 串(",id1,id2",逗号分隔、可能带前导逗号)。
|
||||
# 接口变更后表单 getBusinessDate 的 contract_file 已恒为空串,
|
||||
# 附件 fileId 只能从本字段的签署记录中获取
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
)
|
||||
|
||||
# ---------- 加班审批规则常量 ----------
|
||||
# 正常上班时间 T 兜底值:所有用到上班时间的地方(区间合规的加班开始时间、弹性到岗
|
||||
# 兑换的次日上班时间、请假覆盖判断的早上上班时间等)都优先取排班开始时间
|
||||
|
||||
@@ -22,7 +22,10 @@ from app.service.hrbp.oa.common.oa_api.flow import (
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
get_fjk_file_list,
|
||||
download_attachment,
|
||||
get_contract_sign_status,
|
||||
enrich_form_sign_status,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.attendance import (
|
||||
get_attendance_daily,
|
||||
@@ -51,7 +54,10 @@ __all__ = [
|
||||
"get_wf_activity_by_task_id",
|
||||
"extract_form_id",
|
||||
"get_business_data",
|
||||
"get_fjk_file_list",
|
||||
"download_attachment",
|
||||
"get_contract_sign_status",
|
||||
"enrich_form_sign_status",
|
||||
"get_attendance_daily",
|
||||
"fetch_leave_record_page",
|
||||
"get_leave_records",
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.service.hrbp.oa.common.config import (
|
||||
WORKFORM_ENGINE_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
ATTACHMENT_SAVE_DIR,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
@@ -127,16 +128,55 @@ def get_business_data(
|
||||
return result
|
||||
|
||||
|
||||
# ==================== EHR 会话失效自愈 ====================
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 OA 侧会话校验检测不到——
|
||||
# 表现为附件清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp) -> bool:
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp) -> bool:
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url: str) -> bool:
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_fjk_file_list(
|
||||
session: SessionPage,
|
||||
file_ids: str,
|
||||
detail_url: str = None,
|
||||
) -> list:
|
||||
"""
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单(接口见 aa.md)。
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
附件清单(jsonList),每项含 id/fileName/fileSuffix/herfUrl/fileSize 等;
|
||||
@@ -150,15 +190,26 @@ def get_fjk_file_list(
|
||||
return []
|
||||
data = {"ids": ",".join(ids)}
|
||||
logger.info("查询附件清单: ids=%s", ids)
|
||||
json_data = oa_request_json(session, "POST", FJK_BY_IDS_URL, data, "getFjkByIds")
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data=data)
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
json_data = resp.json()
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def download_attachment(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据附件 fileId 从 OA 下载请假单据附件,支持多附件(逗号分隔多个 fileId)。
|
||||
@@ -167,6 +218,7 @@ def download_attachment(
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_id: 附件 fileId 或逗号分隔的多个 fileId(表单 result.file 字段值)
|
||||
save_dir: 保存目录(默认 downloads)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
成功保存的文件路径;多附件或下载失败时返回逗号拼接的相对路径列表
|
||||
@@ -180,7 +232,7 @@ def download_attachment(
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir)
|
||||
path = _download_one(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
@@ -192,9 +244,12 @@ def _download_one(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
if not file_id:
|
||||
return None
|
||||
@@ -202,15 +257,21 @@ def _download_one(
|
||||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载附件: fileId=%s", file_id)
|
||||
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
return None
|
||||
|
||||
if not resp or resp.status_code != 200:
|
||||
logger.warning("附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id)
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
@@ -248,3 +309,82 @@ def _download_one(
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态
|
||||
|
||||
|
||||
def get_contract_sign_status(session: SessionPage, contract_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询电子签真实签署状态。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
"contract_id": contract_id,
|
||||
"inParamFormId": "",
|
||||
"colCode": "main_id",
|
||||
})
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("签署状态查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"签署状态查询接口状态码异常: {resp.status_code}")
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"签署状态查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
# 业务层执行异常(如该合同无电子签记录,服务端存储过程报错):稳定可复现,
|
||||
# 重试无意义,按"查不到状态"处理——返回空状态,由校验归为"未完成"(不管)
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, json_data.get("meg"))
|
||||
return {
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data: Dict[str, Any], session: SessionPage) -> Dict[str, Any]:
|
||||
"""
|
||||
把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口,把真实状态写回这三个字段,供后续校验使用。
|
||||
接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
(",id1,id2" 格式,get_fjk_file_list 按逗号拆分可容忍前导逗号)。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
|
||||
@@ -27,25 +27,28 @@ def download_contract_files(
|
||||
session,
|
||||
contract_file: str,
|
||||
save_dir: str = RESIGN_ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
下载离职电子签签章附件(解除确认书/报酬支付确认)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
contract_file: getBusinessData 返回的 contract_file 字段(逗号分隔多个 fileId)
|
||||
contract_file: getBusinessData 返回的 contract_file 字段(逗号分隔多个 fileId);
|
||||
接口变更后该字段恒为空,需由 enrich_form_sign_status 从签署记录 file 字段补全
|
||||
save_dir: 保存目录(默认离职电子签签章附件目录)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
{文件名: 本地路径};无附件或全部失败返回空 dict(不抛异常)。
|
||||
"""
|
||||
files = get_fjk_file_list(session, contract_file)
|
||||
files = get_fjk_file_list(session, contract_file, detail_url=detail_url)
|
||||
saved: Dict[str, str] = {}
|
||||
for f in files:
|
||||
fid = (f.get("id") or "").strip()
|
||||
if not fid:
|
||||
continue
|
||||
path = download_attachment(session, fid, save_dir)
|
||||
path = download_attachment(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved[f.get("fileName") or fid] = path
|
||||
if not saved:
|
||||
|
||||
@@ -23,6 +23,7 @@ from app.service.hrbp.oa.resign_e_sign.parser import (
|
||||
)
|
||||
from app.service.hrbp.oa.resign_e_sign.downloads import download_contract_files
|
||||
from app.service.hrbp.oa.resign_e_sign.verify_docs import verify_resign_docs
|
||||
from app.service.hrbp.oa.common.oa_api.flow import enrich_form_sign_status
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -50,6 +51,12 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
校验结果,包含审批决策及详细信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
# 电子签三状态(ext_*)表单里恒为空串,需按 main_id 调签署状态查询接口补全;
|
||||
# 同时接口变更后表单 contract_file 恒为空串,附件 fileId 也由该步骤从签署记录补全
|
||||
try:
|
||||
enrich_form_sign_status(form_data, session)
|
||||
except Exception as e:
|
||||
logger.warning("补全电子签签署状态失败[%s]: %s", doc.get("title", ""), e)
|
||||
resign_info = parse_resign_e_sign_form(form_data)
|
||||
|
||||
is_initiate = form_data.get("ext_is_initiate_sign")
|
||||
@@ -75,7 +82,10 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
# 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。
|
||||
verify_result = None
|
||||
try:
|
||||
files = download_contract_files(session, form_data.get("contract_file"))
|
||||
files = download_contract_files(
|
||||
session, form_data.get("contract_file"),
|
||||
detail_url=doc.get("detail_url"),
|
||||
)
|
||||
if files:
|
||||
result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items())
|
||||
# 文书核验:解析 PDF,比对日期/离职原因与表单字段
|
||||
@@ -86,14 +96,20 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
else:
|
||||
# 兜底:三状态均已完成却拿不到附件(接口异常/签署记录缺失),按失败处理,
|
||||
# 避免"已完成却无附件"被混入常规"未完成"而漏查
|
||||
result["签章附件"] = "无(未查询到签章附件)"
|
||||
verify_result = {"is_pass": False, "msg": "未查询到签章附件,无法核验文书"}
|
||||
result["文书核验"] = verify_result
|
||||
result["decision"] = "失败"
|
||||
result["note"] = "电子签三状态均已完成,但未查询到签章附件,无法核验文书,需人工排查"
|
||||
logger.warning("三状态已完成但未查询到签章附件[%s]: contract_file=%s",
|
||||
doc.get("title", ""), form_data.get("contract_file"))
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e)
|
||||
result["签章附件"] = f"下载失败: {e}"
|
||||
verify_result = {"is_pass": False, "msg": f"签章附件下载失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
result["decision"] = "失败"
|
||||
result["note"] = f"电子签三状态均已完成,但签章附件下载失败,需人工排查: {e}"
|
||||
return result
|
||||
|
||||
if verify_result is not None and verify_result.get("is_pass"):
|
||||
result["decision"] = "通过"
|
||||
|
||||
@@ -72,9 +72,12 @@ TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_TYPE = "13"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
# 附件清单查询接口(见 aa.md):按 ids(逗号分隔 fileId)查附件元信息(fileName/herfUrl 等)
|
||||
# 附件清单查询接口:按 ids(逗号分隔 fileId)查附件元信息(fileName/herfUrl 等)
|
||||
FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 附件下载接口:按 fileId 下载
|
||||
# 附件下载接口:按 fileId 下载(返回 PDF 流 + Content-Disposition)。
|
||||
# 注意:该接口要求有效 EHR 会话(hr.37du.co),会话失效时返回登录页 HTML 或
|
||||
# "外部用户未登录,无法访问",而非报错状态码;前端"在线预览"走的是
|
||||
# PtFjk.mc?method=fjkViewPageDown(返回 HTML 预览页),RPA 下载不使用该地址
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 离职电子签签章附件(解除确认书/报酬支付确认)默认保存目录
|
||||
CONTRACT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
@@ -346,6 +349,9 @@ def get_business_data(session, business_key, form_id):
|
||||
# is_initiate_sign 是否已发起电子签(hr_staff_contract.is_initiate_sign)
|
||||
# sign_status_yg 员工签署状态(esign_sigin_state)
|
||||
# sign_status_qy 企业签署状态(esign_sigin_state)
|
||||
# file 签章附件 fileId 串(",id1,id2",逗号分隔、可能带前导逗号)。
|
||||
# 接口变更后表单 getBusinessDate 的 contract_file 已恒为空串,
|
||||
# 附件 fileId 只能从本字段的签署记录中获取
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
@@ -360,7 +366,8 @@ def get_contract_sign_status(session, contract_id):
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...}
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
@@ -389,6 +396,7 @@ def get_contract_sign_status(session, contract_id):
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
@@ -396,6 +404,7 @@ def get_contract_sign_status(session, contract_id):
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
@@ -412,6 +421,12 @@ def enrich_form_sign_status(form_data, session):
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
# 接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
# (",id1,id2" 格式,get_contract_files 按逗号拆分可容忍前导逗号)
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
|
||||
|
||||
@@ -1062,38 +1077,89 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
# ==================== 签章附件下载 ====================
|
||||
# 电子签全部完成后,按 getBusinessData 的 contract_file(逗号分隔 fileId)调 getFjkByIds
|
||||
# 获取附件清单(解除确认书/报酬支付确认等),再逐个经 fjkFileDownload.mob 下载到本地。
|
||||
def get_contract_files(session, contract_file):
|
||||
"""按 contract_file(逗号分隔 fileId)调 getFjkByIds 查询签章附件清单(见 aa.md)。"""
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 is_session_valid 检测不到——
|
||||
# 表现为清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp):
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp):
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url):
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_contract_files(session, contract_file, detail_url=None):
|
||||
"""按 contract_file(逗号分隔 fileId)调 getFjkByIds 查询签章附件清单。
|
||||
|
||||
会话失效时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
ids = [x.strip() for x in str(contract_file).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
session.post(FJK_BY_IDS_URL, data={"ids": ",".join(ids)})
|
||||
resp = session.response
|
||||
if not resp or resp.status_code != 200:
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data={"ids": ",".join(ids)})
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
return resp.json().get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口状态码异常: {resp.status_code if resp else '无响应'}"
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
json_data = resp.json()
|
||||
return json_data.get("jsonList") or []
|
||||
|
||||
|
||||
def _download_contract_file(session, file_id, save_dir):
|
||||
"""下载单个签章附件 fileId(fjkFileDownload.mob),返回本地路径;失败返回 None。"""
|
||||
def _download_contract_file(session, file_id, save_dir, detail_url=None):
|
||||
"""下载单个签章附件 fileId(fjkFileDownload.mob),返回本地路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
from urllib.parse import unquote
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
download_url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载签章附件: fileId=%s", file_id)
|
||||
try:
|
||||
session.get(download_url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("签章附件请求失败(fileId=%s): %s", file_id, e)
|
||||
return None
|
||||
|
||||
if not resp or resp.status_code != 200:
|
||||
logger.warning("签章附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id)
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(download_url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("签章附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("签章附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
@@ -1138,15 +1204,18 @@ def _download_contract_file(session, file_id, save_dir):
|
||||
return path
|
||||
|
||||
|
||||
def download_contract_files(session, contract_file, save_dir=CONTRACT_SAVE_DIR):
|
||||
"""签完成后下载解除确认书/报酬支付确认,返回 {文件名: 本地路径};失败返回空 dict。"""
|
||||
files = get_contract_files(session, contract_file)
|
||||
def download_contract_files(session, contract_file, save_dir=CONTRACT_SAVE_DIR, detail_url=None):
|
||||
"""签完成后下载解除确认书/报酬支付确认,返回 {文件名: 本地路径};失败返回空 dict。
|
||||
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试。
|
||||
"""
|
||||
files = get_contract_files(session, contract_file, detail_url=detail_url)
|
||||
saved = {}
|
||||
for f in files:
|
||||
fid = (f.get("id") or "").strip()
|
||||
if not fid:
|
||||
continue
|
||||
path = _download_contract_file(session, fid, save_dir)
|
||||
path = _download_contract_file(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved[f.get("fileName") or fid] = path
|
||||
if not saved:
|
||||
@@ -1384,7 +1453,10 @@ def validate_doc(doc, session):
|
||||
# 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。
|
||||
verify_result = None
|
||||
try:
|
||||
files = download_contract_files(session, form_data.get("contract_file"))
|
||||
files = download_contract_files(
|
||||
session, form_data.get("contract_file"),
|
||||
detail_url=doc.get("detail_url"),
|
||||
)
|
||||
if files:
|
||||
result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items())
|
||||
# 文书核验:解析 PDF,比对日期/离职原因与表单字段
|
||||
@@ -1395,14 +1467,20 @@ def validate_doc(doc, session):
|
||||
verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
else:
|
||||
# 兜底:三状态均已完成却拿不到附件(接口异常/签署记录缺失),按失败处理,
|
||||
# 避免"已完成却无附件"被混入常规"未完成"而漏查
|
||||
result["签章附件"] = "无(未查询到签章附件)"
|
||||
verify_result = {"is_pass": False, "msg": "未查询到签章附件,无法核验文书"}
|
||||
result["文书核验"] = verify_result
|
||||
result["decision"] = "失败"
|
||||
result["note"] = "电子签三状态均已完成,但未查询到签章附件,无法核验文书,需人工排查"
|
||||
logger.warning("三状态已完成但未查询到签章附件[%s]: contract_file=%s",
|
||||
doc.get("title", ""), form_data.get("contract_file"))
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e)
|
||||
result["签章附件"] = f"下载失败: {e}"
|
||||
verify_result = {"is_pass": False, "msg": f"签章附件下载失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
result["decision"] = "失败"
|
||||
result["note"] = f"电子签三状态均已完成,但签章附件下载失败,需人工排查: {e}"
|
||||
return result
|
||||
|
||||
if verify_result is not None and verify_result.get("is_pass"):
|
||||
result["decision"] = "通过"
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
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"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"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": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
"员工基础信息": ",".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 列,无三级/五级部门,顺序按模板)
|
||||
"雇主险增减员导出模板": ",".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", # 证件号
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
|
||||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
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 _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||||
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", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||||
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 resolve_template_filters(session, template_name, user_id=None):
|
||||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||||
|
||||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
template_name: 模板名(对应模板列表的 ext1)
|
||||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||||
|
||||
Returns:
|
||||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||||
"""
|
||||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||||
try:
|
||||
# 1. 模板列表 -> 按名称匹配拿 id
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」(可选:%s),回退内置模板",
|
||||
template_name, [t.get("ext1") for t in templates])
|
||||
return None
|
||||
|
||||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(ROSTER_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 LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||||
|
||||
Returns:
|
||||
临时 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 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. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
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 txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}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)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态(与浏览器版输出规范一致)。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None, ttl=DEFAULT_TTL_SECONDS):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出),
|
||||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||||
不同模板导出到不同路径,不会互相复用。纯接口实现,无需浏览器。
|
||||
|
||||
Args:
|
||||
download_dir: 单状态临时文件目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||||
(默认 DEFAULT_STATUSES)
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None: # None 使用默认缓存有效期
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过接口导出
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s),临时目录:%s =====",
|
||||
template_name, statuses, leave_desc, download_dir)
|
||||
|
||||
session = _build_session()
|
||||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
# 合并所有花名册文件
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
|
||||
|
||||
def main(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template: 自定义导出模板名
|
||||
output_path / download_dir: 保存路径与临时下载目录
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||||
"""
|
||||
# 在职状态:兼容 str / list / 逗号分隔
|
||||
if isinstance(statuses, str):
|
||||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||||
elif statuses:
|
||||
statuses = [str(s) for s in statuses]
|
||||
else:
|
||||
statuses = list(DEFAULT_STATUSES)
|
||||
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
|
||||
try:
|
||||
save_path = export_roster(
|
||||
download_dir=download_dir, output_path=output_path,
|
||||
template_name=template, statuses=statuses,
|
||||
leave_start=leave_start, leave_end=leave_end)
|
||||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
statuses = ["在职"]
|
||||
leave_start = ""
|
||||
leave_end = ""
|
||||
template = "员工基础信息"
|
||||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||||
template=template, output_path=output_path)
|
||||
Reference in New Issue
Block a user