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"] = "通过"
|
||||
|
||||
Reference in New Issue
Block a user