refactor: 重构HRBP公共层与业务模块,整理废弃资源

1.  迁移并统一HR会话、配置、API等公共能力至hrbp/common层,实现ehr/oa模块复用
2.  删除captcha_debug调试用图片资源与旧session_manager文件
3.  重构考勤异常处理模块,补充分级逻辑与导出优化
4.  新增OA/HR多套API封装模块与配套文档
5.  移除旧通用接口规划文档,补充完整需求与开发文档
This commit is contained in:
2026-08-14 15:48:15 +08:00
parent 3a8571d995
commit 831845f970
57 changed files with 4276 additions and 1905 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

+7
View File
@@ -48,3 +48,10 @@ LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
# 查询加班记录接口(aa.md 提供,用于过滤虚假异常)
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
# 查询打卡记录接口(aa.md 提供,sqlId=kq_data_query,按 base_code 工号查原始打卡流水)
KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
# 假期类型编码映射已上移到 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
-818
View File
@@ -1,818 +0,0 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common
@FileName: hr_api.py
@Author: 小布丁
@CreateTime: 2026-08-05 23:52
@Description: HR 系统 API 模块,负责调用系统接口(工资卡等),供各业务模块复用
@Version: 2.0.0
"""
import json
import os
import time
from typing import Any, Dict, List
from app.common.app_paths import get_sessions_dir
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import (
WAGE_CARD_URL,
PAGE_MAX_SIZE,
GET_CUR_USER_INFO_URL,
ATTENDANCE_ABNORMAL_URL,
ATTENDANCE_ADJUST_URL,
SHIFT_URL,
LEAVE_URL,
OVERTIME_URL,
BANK_DICT_URL,
BANK_DICT_CODE_TYPE,
BANK_DICT_EXPIRE_SEC,
)
from app.service.hrbp.ehr.common.session_manager import build_hr_session
logger = get_logger(__name__)
class HRSessionExpiredError(Exception):
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
def _is_expired(text) -> bool:
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
return bool(text) and not text.lstrip().startswith(("{", "["))
# ---------- 银行卡(工资卡)信息查询接口 ----------
def fetch_wage_card_page(
session,
status: int,
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
leave_start: str = None,
leave_end: str = None,
) -> Dict[str, Any]:
"""
请求单页工资卡数据。
Args:
session: 已登录的 requests.Session 对象
status: 人员状态,1=在职 / 2=离职
page_no: 页码(从 1 开始)
page_size: 每页条数
leave_start / leave_end: 离职筛选时间范围 "YYYY-MM-DD"(status=2 时必填)
Returns:
接口返回的 JSON 字典
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
params = {
"start": (page_no - 1) * page_size,
"pageNo": page_no,
"pageSize": page_size,
"ftl_list_STRU_TREE_CODE": "cq37du",
"sortName": "hr_staff_wage_card.STAFF_NAME",
"sortType": "asc",
"commonQuery": "[]",
"person_status": status,
}
# 在职、离职参数区分
if status == 1:
params["leaveOffice_date"] = ""
elif leave_start and leave_end:
params["leaveOffice_date[0]"] = leave_start
params["leaveOffice_date[1]"] = leave_end
params["leaveOffice_date_start"] = leave_start
params["leaveOffice_date_end"] = leave_end
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("工资卡请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_all_wage_card(
session,
status: int,
status_name: str,
leave_start: str = None,
leave_end: str = None,
) -> List[Dict[str, Any]]:
"""
分页抓取指定人员类型(在职/离职)的全部工资卡数据。
Args:
session: 已登录的 requests.Session 对象
status: 人员状态,1=在职 / 2=离职
status_name: 人员类型文字(用于日志与数据标记)
leave_start / leave_end: 离职筛选时间范围(status=2 时必填)
Returns:
数据行列表(每条已附加「人员类型」字段)
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
except HRSessionExpiredError:
logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name)
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
session = refresh_hr_session()
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
if data.get("state") != "1":
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
break
page_list = data.get("datas", []) or []
if not page_list:
logger.info("【%s】无更多数据", status_name)
break
# 给每条数据增加人员类型标识
for item in page_list:
item["人员类型"] = status_name
all_rows.extend(page_list)
total = data.get("count", 0)
total_page = data.get("pageCount", 0)
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
status_name, page_no, total_page, len(all_rows), total)
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2) # 轻微限速,避免触发风控
return all_rows
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录
_BANK_DICT_CACHE_DIR = get_sessions_dir()
BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json")
BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json")
def _fetch_bank_dict(session=None):
"""远程调用接口获取银行字典,并写入本地缓存。
Returns:
(list[dict], dict[code->name])
"""
if session is None:
session = build_hr_session()
payload = {
"codeType": BANK_DICT_CODE_TYPE,
"inUse": "0,1,2",
"platformMode": "redseaPlatform",
}
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
if not resp:
raise RuntimeError("银行字典请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"银行字典接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,银行字典接口返回非 JSON 内容")
resp_json = resp.json()
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
for item in raw_list]
result_map = {item["code"]: item["name"] for item in result_list}
os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True)
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
json.dump(result_list, f, ensure_ascii=False, indent=2)
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
json.dump(result_map, f, ensure_ascii=False, indent=2)
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
return result_list, result_map
def _load_bank_dict_cache():
"""读取本地银行字典缓存,失败返回 (None, None)。"""
try:
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
lst = json.load(f)
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
mp = json.load(f)
return lst, mp
except Exception as e:
logger.warning("银行字典本地缓存读取失败:%s", e)
return None, None
def get_bank_dict(session=None, force_refresh: bool = False):
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
Args:
session: 可选的已登录 requests.Session;未提供时自动构建
force_refresh: True 强制重新调用接口
Returns:
(list版本, dict[code->name]版本)
"""
need_refresh = force_refresh
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
need_refresh = True
else:
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
need_refresh = True
if need_refresh:
try:
return _fetch_bank_dict(session)
except Exception as e:
logger.error("银行字典远程拉取失败:%s", e)
lst, mp = _load_bank_dict_cache()
if lst is not None:
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
return [], {}
lst, mp = _load_bank_dict_cache()
if lst is None:
# 缓存异常时重新拉取
return _fetch_bank_dict(session)
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
def bank_type_to_name(bank_type, bank_map) -> str:
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
if bank_type is None:
return ""
if isinstance(bank_type, float):
if bank_type != bank_type: # NaN
return ""
bank_type = str(int(bank_type))
elif isinstance(bank_type, int):
bank_type = str(bank_type)
else:
bank_type = str(bank_type).strip()
return bank_map.get(bank_type, "")
def adjust_abnormal(
session,
abnormal_ids,
type_code: int = 1,
) -> Dict[str, Any]:
"""
确认/调整考勤异常单据。
Args:
session: 已登录的 requests.Session 对象
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
type_code: 处理类型,1=自动确认异常(按接口约定)
Returns:
接口返回的 JSON 字典(state=1 表示处理成功)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
if isinstance(abnormal_ids, (list, tuple)):
ids = ",".join(str(i) for i in abnormal_ids)
else:
ids = str(abnormal_ids)
params = {"abnormalIds": ids, "type": type_code}
resp = session.post(ATTENDANCE_ADJUST_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("考勤异常确认请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"考勤异常确认接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,考勤异常确认接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"考勤异常确认接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
# ---------- 考勤异常查询接口 ----------
def fetch_cur_user_info(session) -> Dict[str, Any]:
"""
调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。
该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode):
- 正常返回 JSON(含 userId / rootId),说明 cookies 有效;
- 返回登录页等非 JSON 内容,说明登录态过期。
Returns:
接口返回的 JSON 字典(含 userId / rootId 等字段)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
resp = session.post(GET_CUR_USER_INFO_URL, timeout=20)
if not resp:
raise RuntimeError("获取当前用户信息失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"获取当前用户信息状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,getCurUserInfo 接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"获取当前用户信息返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_attendance_abnormal_page(
session,
user_id: str,
treecode: str,
begin_date: str,
end_date: str,
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页考勤异常数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月)
page_no: 页码(从 1 开始)
page_size: 每页条数
Returns:
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
params = {
"treecode": treecode,
"user_id": user_id,
"commonQuery": "",
"commonQueryStr": "",
"sqlId": "kq_count_abnormal_Select",
"redapiId": "rf_p_kq_count_abnormal_Select",
"treeCodeList": "",
"abnormal_type": "",
"base_code": "",
"join_date": "",
"join_date_end": end_date,
"person_status": "",
"staff_id": "",
"post_no": "",
"post_type": "1",
"period_order": "",
"identity_test": "",
"identity": "",
"sex": "",
"age": "",
"age_end": "",
"start_operat_time": "",
"end_operat_time": "",
"operator_username": "",
"operator_userid": "",
"is_adjusted": "",
"begin_date": begin_date,
"end_date": end_date,
"STAFF_NAME": "",
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "work_day",
"pageNo": page_no,
"pageSize": page_size,
}
resp = session.post(ATTENDANCE_ABNORMAL_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("考勤异常请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"考勤异常接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,考勤异常接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"考勤异常接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_all_attendance_abnormal(
session,
user_id: str,
treecode: str,
begin_date: str,
end_date: str,
) -> List[Dict[str, Any]]:
"""
分页抓取指定日期范围内的全部考勤异常数据。
Args:
session: 已登录的 requests.Session 对象
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
Returns:
异常明细列表(接口 datas 字段内容)
Raises:
HRSessionExpiredError: 登录态过期且重新登录后仍失败
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE
)
except HRSessionExpiredError:
logger.warning("考勤异常 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
session = refresh_hr_session()
# 重新登录后需重新获取 user_id / treecode
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
treecode = info.get("rootId", "")
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE
)
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_page = data.get("pageCount", 0)
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2) # 轻微限速,避免触发风控
return all_rows
# ---------- 查询排班接口(用于过滤虚假异常,暂未在主流程调用) ----------
def fetch_shift_page(
session,
user_id: str,
base_code: str,
begin_date: str,
end_date: str,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页排班数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为排班明细数组)
"""
params = {
"treecode": treecode,
"user_id": user_id,
"sqlId": "kq_count_SelectBanci",
"commonQuery": "",
"commonQueryStr": "",
"staff_ids": "",
"person_status": "1,4",
"post_no": "",
"post_type": "1",
"post_level": "",
"identity": "",
"showType": "1",
"dateType": "2",
"begin": begin_date,
"end": end_date,
"bc_date": begin_date,
"base_code": base_code,
"staff_name": "",
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": page_no,
"pageSize": page_size,
}
resp = session.post(SHIFT_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("排班请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"排班接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,排班接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"排班接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_all_shift(
session,
user_id: str,
base_code: str,
begin_date: str,
end_date: str,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部排班数据。"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_shift_page(
session, user_id, base_code, begin_date, end_date,
treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("排班 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_shift_page(
session, user_id, base_code, begin_date, end_date,
treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("排班已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
# ---------- 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用) ----------
def fetch_leave_page(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页请假记录数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为请假记录数组)
"""
params = {
"STRU_TREE_CODE": treecode,
"user_id": user_id,
"begin_date": "",
"end_date": "",
"sqlId": "select_kqLeave_record",
"commonQuery": "",
"commonQueryStr": "",
"post_no": "",
"source": "",
"person_status": "",
"staff_id": "",
"staffNames": "",
"post_type": "1",
"processing_reason": "",
"processing_date": "",
"start_operat_time": "",
"end_operat_time": "",
"orgAlias": "",
"dept_ids": "",
"base_code": base_code,
"staff_name": "",
"start_time": start_time,
"end_time": end_time,
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "operat_time",
"pageNo": page_no,
"pageSize": page_size,
}
resp = session.post(LEAVE_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("请假查询请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"请假查询接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,请假查询接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"请假查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_all_leave(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部请假记录。"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_leave_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("请假查询 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_leave_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
# ---------- 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用) ----------
def fetch_overtime_page(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页加班记录数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为加班记录数组)
"""
params = {
"STRU_TREE_CODE": treecode,
"user_id": user_id,
"sqlId": "kq_overtime_detail_select",
"commonQuery": "",
"commonQueryStr": "",
"BPM_STATUS": "",
"post_no": "",
"postName": "",
"source": "",
"IS_SUBSIDY": "",
"person_status": "",
"staff_id": "",
"staffNames": "",
"post_type": "1",
"processing_reason": "",
"start_operat_time": "",
"end_operat_time": "",
"base_code": base_code,
"staff_name": "",
"WORK_OVERTIME_TYPE": "",
"start_time": start_time,
"end_time": end_time,
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "OPERATE_TIME",
"pageNo": page_no,
"pageSize": page_size,
}
resp = session.post(OVERTIME_URL, data=params, timeout=20)
if not resp:
raise RuntimeError("加班查询请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"加班查询接口状态码异常: {resp.status_code}")
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,加班查询接口返回非 JSON 内容")
try:
return resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"加班查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
def fetch_all_overtime(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部加班记录。"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_overtime_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("加班查询 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_overtime_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common
@FileName: hr_api/__init__.py
@Description: HR 系统 API 包,按接口拆分到各子模块,此处统一导出(保持 from ...hr_api import X 兼容)
@Version: 2.0.0
"""
from app.service.hrbp.common.hr_session import HRSessionExpiredError, _is_expired, hr_request_json
from app.service.hrbp.ehr.common.hr_api.wage_card import fetch_wage_card_page, fetch_all_wage_card
from app.service.hrbp.ehr.common.hr_api.bank_dict import get_bank_dict, bank_type_to_name
from app.service.hrbp.ehr.common.hr_api.attendance import (
fetch_cur_user_info,
fetch_attendance_abnormal_page,
fetch_all_attendance_abnormal,
adjust_abnormal,
)
from app.service.hrbp.ehr.common.hr_api.shift import fetch_shift_page, fetch_all_shift
from app.service.hrbp.ehr.common.hr_api.leave import fetch_leave_page, fetch_all_leave
from app.service.hrbp.ehr.common.hr_api.overtime import fetch_overtime_page, fetch_all_overtime
from app.service.hrbp.ehr.common.hr_api.kq_data import fetch_kq_data_page, fetch_all_kq_data
__all__ = [
# base
"HRSessionExpiredError",
"_is_expired",
"hr_request_json",
# wage_card
"fetch_wage_card_page",
"fetch_all_wage_card",
# bank_dict
"get_bank_dict",
"bank_type_to_name",
# attendance
"fetch_cur_user_info",
"fetch_attendance_abnormal_page",
"fetch_all_attendance_abnormal",
"adjust_abnormal",
# shift
"fetch_shift_page",
"fetch_all_shift",
# leave
"fetch_leave_page",
"fetch_all_leave",
# overtime
"fetch_overtime_page",
"fetch_all_overtime",
# kq_data
"fetch_kq_data_page",
"fetch_all_kq_data",
]
@@ -0,0 +1,202 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: attendance.py
@Description: 当前用户信息 + 考勤异常查询/确认接口
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import (
GET_CUR_USER_INFO_URL,
ATTENDANCE_ABNORMAL_URL,
ATTENDANCE_ADJUST_URL,
PAGE_MAX_SIZE,
)
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
logger = get_logger(__name__)
def fetch_cur_user_info(session) -> Dict[str, Any]:
"""
调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。
该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode):
- 正常返回 JSON(含 userId / rootId),说明 cookies 有效;
- 返回登录页等非 JSON 内容,说明登录态过期。
Returns:
接口返回的 JSON 字典(含 userId / rootId 等字段)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
def adjust_abnormal(
session,
abnormal_ids,
type_code: int = 1,
) -> Dict[str, Any]:
"""
确认/调整考勤异常单据。
Args:
session: 已登录的 requests.Session 对象
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
type_code: 处理类型,1=自动确认异常(按接口约定)
Returns:
接口返回的 JSON 字典(state=1 表示处理成功)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
if isinstance(abnormal_ids, (list, tuple)):
ids = ",".join(str(i) for i in abnormal_ids)
else:
ids = str(abnormal_ids)
params = {"abnormalIds": ids, "type": type_code}
return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
def fetch_attendance_abnormal_page(
session,
user_id: str,
treecode: str,
begin_date: str,
end_date: str,
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
is_adjusted: str = "0",
abnormal_type: str = "",
) -> Dict[str, Any]:
"""
请求单页考勤异常数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月)
page_no: 页码(从 1 开始)
page_size: 每页条数
is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部
Returns:
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
params = {
"treecode": treecode,
"user_id": user_id,
"commonQuery": "",
"commonQueryStr": "",
"sqlId": "kq_count_abnormal_Select",
"redapiId": "rf_p_kq_count_abnormal_Select",
"treeCodeList": "",
"abnormal_type": abnormal_type,
"base_code": "",
"join_date": "",
"join_date_end": end_date,
"person_status": "",
"staff_id": "",
"post_no": "",
"post_type": "1",
"period_order": "",
"identity_test": "",
"identity": "",
"sex": "",
"age": "",
"age_end": "",
"start_operat_time": "",
"end_operat_time": "",
"operator_username": "",
"operator_userid": "",
"is_adjusted": is_adjusted,
"begin_date": begin_date,
"end_date": end_date,
"STAFF_NAME": "",
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "work_day",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
def fetch_all_attendance_abnormal(
session,
user_id: str,
treecode: str,
begin_date: str,
end_date: str,
is_adjusted: str = "0",
abnormal_type: str = "",
) -> List[Dict[str, Any]]:
"""
分页抓取指定日期范围内的全部考勤异常数据。
Args:
session: 已登录的 requests.Session 对象
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部
Returns:
异常明细列表(接口 datas 字段内容)
Raises:
HRSessionExpiredError: 登录态过期且重新登录后仍失败
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type
)
except HRSessionExpiredError:
logger.warning("考勤异常 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
# 重新登录后需重新获取 user_id / treecode
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
treecode = info.get("rootId", "")
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type
)
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_page = data.get("pageCount", 0)
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2) # 轻微限速,避免触发风控
return all_rows
@@ -0,0 +1,121 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: bank_dict.py
@Description: 银行字典接口(缓存 code -> 开卡银行 映射)
@Version: 1.0.0
"""
import json
import os
import time
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,
BANK_DICT_CODE_TYPE,
BANK_DICT_EXPIRE_SEC,
)
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
from app.service.hrbp.common.hr_session import build_hr_session
logger = get_logger(__name__)
# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录
_BANK_DICT_CACHE_DIR = get_sessions_dir()
BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json")
BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json")
def _fetch_bank_dict(session=None):
"""远程调用接口获取银行字典,并写入本地缓存。
Returns:
(list[dict], dict[code->name])
"""
if session is None:
session = build_hr_session()
payload = {
"codeType": BANK_DICT_CODE_TYPE,
"inUse": "0,1,2",
"platformMode": "redseaPlatform",
}
resp_json = hr_request_json(session, "POST", BANK_DICT_URL, payload, "银行字典", timeout=30)
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
for item in raw_list]
result_map = {item["code"]: item["name"] for item in result_list}
os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True)
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
json.dump(result_list, f, ensure_ascii=False, indent=2)
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
json.dump(result_map, f, ensure_ascii=False, indent=2)
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
return result_list, result_map
def _load_bank_dict_cache():
"""读取本地银行字典缓存,失败返回 (None, None)。"""
try:
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
lst = json.load(f)
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
mp = json.load(f)
return lst, mp
except Exception as e:
logger.warning("银行字典本地缓存读取失败:%s", e)
return None, None
def get_bank_dict(session=None, force_refresh: bool = False):
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
Args:
session: 可选的已登录 requests.Session;未提供时自动构建
force_refresh: True 强制重新调用接口
Returns:
(list版本, dict[code->name]版本)
"""
need_refresh = force_refresh
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
need_refresh = True
else:
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
need_refresh = True
if need_refresh:
try:
return _fetch_bank_dict(session)
except Exception as e:
logger.error("银行字典远程拉取失败:%s", e)
lst, mp = _load_bank_dict_cache()
if lst is not None:
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
return [], {}
lst, mp = _load_bank_dict_cache()
if lst is None:
# 缓存异常时重新拉取
return _fetch_bank_dict(session)
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
def bank_type_to_name(bank_type, bank_map) -> str:
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
if bank_type is None:
return ""
if isinstance(bank_type, float):
if bank_type != bank_type: # NaN
return ""
bank_type = str(int(bank_type))
elif isinstance(bank_type, int):
bank_type = str(bank_type)
else:
bank_type = str(bank_type).strip()
return bank_map.get(bank_type, "")
@@ -0,0 +1,137 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: kq_data.py
@Description: 查询打卡记录接口(用于校验休息日半天上班是否按班段打卡)
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import KQ_DATA_URL, PAGE_MAX_SIZE
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
logger = get_logger(__name__)
def fetch_kq_data_page(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页打卡记录数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为打卡流水数组,关键字段见下)
"""
params = {
"user_id": user_id,
"sqlId": "kq_data_query",
# datas 记录关键字段(aa.md 提供的返回样例):
# base_code 工号、staff_id、staff_name、
# kq_time 打卡时间("YYYY-MM-DD HH:MM:SS")、kq_type 打卡类型(如 9)、
# status 打卡状态、addr_status 地址状态、time_order 上/下班顺序、
# bc_date 班次日期、kq_bc_id 考勤班次id、pb_id 排班id、address 打卡地点、
# time_zone_min 时区分钟、varchar1 扩展标记
"commonQuery": "",
"commonQueryStr": "",
"kqStaffIds": "",
"staff_id": "",
"staff_name": "",
"orgAlias": "",
"dept_ids": "",
"kq_type": "",
"post_type": "",
"person_status": "",
"dkstatus": "",
"addr_status": " ",
"struTreeCode": treecode,
"belongUnitStruId": "",
"work_day_begin": start_time,
"work_day_end": end_time,
"base_code": base_code,
"STAFF_NAME": "",
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", KQ_DATA_URL, params, "打卡查询")
def fetch_all_kq_data(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部打卡记录。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
Returns:
打卡记录列表(接口 datas 字段内容)
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_kq_data_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("打卡查询 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_kq_data_page(
session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
+147
View File
@@ -0,0 +1,147 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: leave.py
@Description: 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用)
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import LEAVE_URL, PAGE_MAX_SIZE
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
logger = get_logger(__name__)
def fetch_leave_page(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
leave_type=None,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页请假记录数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"];
不传(None)表示全部类型
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为请假记录数组,字段含 start_time/end_time/leave_days/
begin_date_other_name/end_date_other_name/base_code/staff_id 等)
"""
params = {
"STRU_TREE_CODE": treecode,
"user_id": user_id,
"begin_date": "",
"end_date": "",
"sqlId": "select_kqLeave_record",
"commonQuery": "",
"commonQueryStr": "",
"post_no": "",
"source": "",
"person_status": "",
"staff_id": "",
"staffNames": "",
"post_type": "1",
"processing_reason": "",
"processing_date": "",
"start_operat_time": "",
"end_operat_time": "",
"orgAlias": "",
"dept_ids": "",
"base_code": base_code,
"staff_name": "",
"start_time": start_time,
"end_time": end_time,
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "operat_time",
"pageNo": page_no,
"pageSize": page_size,
}
# leave_type 可多值(如 22&09&24...),requests 会把列表序列化为重复键;不传表示全部类型
if leave_type:
if isinstance(leave_type, (list, tuple)):
params["leave_type"] = [str(t) for t in leave_type]
else:
params["leave_type"] = str(leave_type)
return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询")
def fetch_all_leave(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
leave_type=None,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部请假记录。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"];
不传(None)表示全部类型
treecode: 组织树编码,默认 cq37du
Returns:
请假记录列表(接口 datas 字段内容,含 start_time/end_time/leave_days 等)
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_leave_page(
session, user_id, base_code, start_time, end_time,
leave_type, treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("请假查询 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_leave_page(
session, user_id, base_code, start_time, end_time,
leave_type, treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: overtime.py
@Description: 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用)
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import OVERTIME_URL, PAGE_MAX_SIZE
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
logger = get_logger(__name__)
def fetch_overtime_page(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
work_overtime_type: str = "",
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页加班记录数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为加班记录数组,关键字段见下)
"""
params = {
"STRU_TREE_CODE": treecode,
"user_id": user_id,
"sqlId": "kq_overtime_detail_select",
# datas 记录关键字段(aa.md 提供的返回样例):
# base_code 工号、STAFF_ID、WORK_OVERTIME_TYPE 加班类型(1延时/2法定/3休息日)、
# OT_DATE 加班日期、ot_days / sys_ot_days / plan_ot_days 加班天数(筛 0.5 天用)、
# ot_hours / FINAL_HOURS 加班小时、
# PLAN_START_TIME/PLAN_END_TIME、ACTUAL_START_TIME/ACTUAL_END_TIME、FINAL_START_TIME/FINAL_END_TIME 时间段、
# SB_DA_RANGE / XB_DA_RANGE 上下班打卡分钟范围、SB_TIME_MORE/LESS、XB_TIME_MORE/LESS、OT_SB_TYPE/OT_XB_TYPE
"commonQuery": "",
"commonQueryStr": "",
"BPM_STATUS": "",
"post_no": "",
"postName": "",
"source": "",
"IS_SUBSIDY": "",
"person_status": "",
"staff_id": "",
"staffNames": "",
"post_type": "1",
"processing_reason": "",
"start_operat_time": "",
"end_operat_time": "",
"base_code": base_code,
"staff_name": "",
"WORK_OVERTIME_TYPE": work_overtime_type,
"start_time": start_time,
"end_time": end_time,
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "OPERATE_TIME",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", OVERTIME_URL, params, "加班查询")
def fetch_all_overtime(
session,
user_id: str,
base_code: str,
start_time: str,
end_time: str,
work_overtime_type: str = "",
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部加班记录。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班
treecode: 组织树编码,默认 cq37du
Returns:
加班记录列表(接口 datas 字段内容)
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_overtime_page(
session, user_id, base_code, start_time, end_time,
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("加班查询 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_overtime_page(
session, user_id, base_code, start_time, end_time,
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
+123
View File
@@ -0,0 +1,123 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: shift.py
@Description: 查询排班接口(用于过滤虚假异常,暂未在主流程调用)
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import SHIFT_URL, PAGE_MAX_SIZE
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
logger = get_logger(__name__)
def fetch_shift_page(
session,
user_id: str,
base_code: str,
begin_date: str,
end_date: str,
treecode: str = "cq37du",
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
) -> Dict[str, Any]:
"""
请求单页排班数据(aa.md 提供的接口入参)。
Args:
session: 已登录的 requests.Session 对象
user_id: 由 getCurUserInfo 返回的 userId
base_code: 员工工号
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
treecode: 组织树编码,默认 cq37du
page_no / page_size: 分页参数
Returns:
接口返回的 JSON 字典(datas 为排班明细数组,关键字段见下)
"""
params = {
"treecode": treecode,
"user_id": user_id,
"sqlId": "kq_count_SelectBanci",
# datas 记录关键字段(aa.md 提供的返回样例,一条记录 = 一个员工在查询范围内的排班):
# base_code 工号、staff_id、staff_name、work_day 首日、total_day / total_hours 汇总、
# 基础班次:bc_name 班次名、bc_time 班段时间(如 "09:00 ~ 18:00",即班端)、begin_time / end_time、yq_total_min、
# 逐日班次(动态列,key 为 "YYYY-MM-DD_bc_id/bc_name/bc_time/paiban_type/sb_type/xb_type"),
# paiban_type:-2=上班班次、0=休息;bc_time 为空串表示休息
"commonQuery": "",
"commonQueryStr": "",
"staff_ids": "",
"person_status": "1,4",
"post_no": "",
"post_type": "1",
"post_level": "",
"identity": "",
"showType": "1",
"dateType": "1",
"begin": begin_date,
"end": end_date,
"bc_date": begin_date,
"base_code": base_code,
"staff_name": "",
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
def fetch_all_shift(
session,
user_id: str,
base_code: str,
begin_date: str,
end_date: str,
treecode: str = "cq37du",
) -> List[Dict[str, Any]]:
"""分页抓取指定工号、日期范围内的全部排班数据。"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_shift_page(
session, user_id, base_code, begin_date, end_date,
treecode, page_no, PAGE_MAX_SIZE,
)
except HRSessionExpiredError:
logger.warning("排班 HR 登录态过期,重新登录后续抓")
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
info = fetch_cur_user_info(session)
user_id = info.get("userId", "")
data = fetch_shift_page(
session, user_id, base_code, begin_date, end_date,
treecode, page_no, PAGE_MAX_SIZE,
)
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_page = data.get("pageCount", 0)
logger.info("排班已抓取 %d/%d 页,累计 %d 条",
page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common.hr_api
@FileName: wage_card.py
@Description: 银行卡(工资卡)信息查询接口
@Version: 1.0.0
"""
import time
from typing import Any, Dict, List
from app.utils.logger import get_logger
from app.service.hrbp.ehr.common.config import WAGE_CARD_URL, PAGE_MAX_SIZE
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
logger = get_logger(__name__)
def fetch_wage_card_page(
session,
status: int,
page_no: int = 1,
page_size: int = PAGE_MAX_SIZE,
leave_start: str = None,
leave_end: str = None,
) -> Dict[str, Any]:
"""
请求单页工资卡数据。
Args:
session: 已登录的 requests.Session 对象
status: 人员状态,1=在职 / 2=离职
page_no: 页码(从 1 开始)
page_size: 每页条数
leave_start / leave_end: 离职筛选时间范围 "YYYY-MM-DD"(status=2 时必填)
Returns:
接口返回的 JSON 字典
Raises:
RuntimeError: 请求失败或响应异常
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
"""
params = {
"start": (page_no - 1) * page_size,
"pageNo": page_no,
"pageSize": page_size,
"ftl_list_STRU_TREE_CODE": "cq37du",
"sortName": "hr_staff_wage_card.STAFF_NAME",
"sortType": "asc",
"commonQuery": "[]",
"person_status": status,
}
# 在职、离职参数区分
if status == 1:
params["leaveOffice_date"] = ""
elif leave_start and leave_end:
params["leaveOffice_date[0]"] = leave_start
params["leaveOffice_date[1]"] = leave_end
params["leaveOffice_date_start"] = leave_start
params["leaveOffice_date_end"] = leave_end
return hr_request_json(session, "POST", WAGE_CARD_URL, params, "工资卡")
def fetch_all_wage_card(
session,
status: int,
status_name: str,
leave_start: str = None,
leave_end: str = None,
) -> List[Dict[str, Any]]:
"""
分页抓取指定人员类型(在职/离职)的全部工资卡数据。
Args:
session: 已登录的 requests.Session 对象
status: 人员状态,1=在职 / 2=离职
status_name: 人员类型文字(用于日志与数据标记)
leave_start / leave_end: 离职筛选时间范围(status=2 时必填)
Returns:
数据行列表(每条已附加「人员类型」字段)
"""
all_rows: List[Dict[str, Any]] = []
page_no = 1
while True:
try:
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
except HRSessionExpiredError:
logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name)
from app.service.hrbp.common.hr_session import refresh_hr_session
session = refresh_hr_session()
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
if data.get("state") != "1":
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
break
page_list = data.get("datas", []) or []
if not page_list:
logger.info("【%s】无更多数据", status_name)
break
# 给每条数据增加人员类型标识
for item in page_list:
item["人员类型"] = status_name
all_rows.extend(page_list)
total = data.get("count", 0)
total_page = data.get("pageCount", 0)
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
status_name, page_no, total_page, len(all_rows), total)
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2) # 轻微限速,避免触发风控
return all_rows
-490
View File
@@ -1,490 +0,0 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common
@FileName: login.py
@Author: 小布丁
@CreateTime: 2026-08-05 23:52
@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍)
@Version: 1.1.0
"""
import os
import re
import json
import time
import random
from PIL import Image, ImageDraw
from DrissionPage import ChromiumPage, ChromiumOptions
import cv2
import numpy as np
import io
from dotenv import load_dotenv
from app.common.app_paths import get_sessions_dir
load_dotenv()
# ================== 配置 ==================
LOGIN_URL = os.getenv('hr_login_url')
SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword')
USERNAME = os.getenv('hr_login_username')
PASSWORD = os.getenv('hr_login_password')
LOGIN_BTN = "@id=login-btn"
ACCOUNT_INPUT = "@id=j_username"
PASSWORD_INPUT = "@id=j_password_2"
CAPTCHA_CONTAINER = ".:comImageValidate"
SLIDER_BTN = ".:v_rightBtn"
BG_IMG = ".imgBg"
SLIDER_IMG = "css:div.imgBg_3 > img"
# 注意:不再使用 REFRESH_BTN
RETRY_MAX = 5
TIMEOUT = 10
HEADLESS = False
DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug')
# 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,与 OA 系统一致)
_COOKIE_DIR = get_sessions_dir()
COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json')
def ensure_dir(path):
os.makedirs(path, exist_ok=True)
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
def save_browser_cookies(page):
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
cookies = page.cookies(all_domains=True)
if not cookies:
print("未获取到 Cookies,跳过保存")
return
ensure_dir(_COOKIE_DIR)
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
def load_cookies():
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 改进的匹配函数(双候选 + 低置信度容忍) ==================
def match_slider_dual(bg_bytes, slider_bytes, debug_prefix=""):
"""
双候选匹配,返回最佳候选和次佳候选(即使置信度低)
返回: (best_distance, best_conf, best_loc, candidates_list, x_offset, y_offset, slider_w, slider_h)
其中 candidates_list 为 [(x, y, conf), ...] 用于绘制标记
"""
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
if bg_img is None or slider_color is None:
print(f" [{debug_prefix}匹配错误] 无法解码图片")
return None, 0, None, [], 0, 0, 0, 0
bg_h, bg_w = bg_img.shape[:2]
s_h, s_w = slider_color.shape[:2]
print(f" [{debug_prefix}图片尺寸] 背景: {bg_w}x{bg_h}, 滑块原始: {s_w}x{s_h}")
# ---- 提取滑块有效区域 ----
x_offset = 0
y_offset = 0
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
alpha = slider_color[:, :, 3]
slider_rgb = slider_color[:, :, :3]
ys, xs = np.where(alpha > 0)
if len(ys) > 0 and len(xs) > 0:
y_min, y_max = np.min(ys), np.max(ys)
x_min, x_max = np.min(xs), np.max(xs)
slider_rgb = slider_rgb[y_min:y_max+1, x_min:x_max+1]
x_offset = x_min
y_offset = y_min
print(f" [{debug_prefix}滑块裁剪] 有效区域: x=[{x_min},{x_max}], y=[{y_min},{y_max}], 裁剪后尺寸: {slider_rgb.shape[1]}x{slider_rgb.shape[0]}")
else:
print(f" [{debug_prefix}滑块裁剪] 未找到非透明区域,使用完整图")
slider_rgb = slider_color[:, :, :3]
else:
if len(slider_color.shape) == 3:
slider_rgb = slider_color
else:
slider_rgb = cv2.cvtColor(slider_color, cv2.COLOR_GRAY2BGR)
x_offset = 0
y_offset = 0
s_h, s_w = slider_rgb.shape[:2]
# ---- 预处理:灰度 + 高斯模糊 + Canny ----
gray_bg = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
gray_slider = cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY)
gray_bg = cv2.GaussianBlur(gray_bg, (3, 3), 0)
gray_slider = cv2.GaussianBlur(gray_slider, (3, 3), 0)
bg_edges = cv2.Canny(gray_bg, 50, 150)
slider_edges = cv2.Canny(gray_slider, 50, 150)
# ---- 模板匹配(全图) ----
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
# 收集多个候选(前 6 个),避免真实缺口被最右侧干扰或滑块区假候选挤掉
candidates = []
temp_result = result.copy()
for i in range(6):
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
if max_val < 0.03: # 极低则停止
break
candidates.append((max_val, max_loc))
# 抑制周围
y0 = max(0, max_loc[1] - s_h // 2)
y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
x0 = max(0, max_loc[0] - s_w // 2)
x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
temp_result[y0:y1, x0:x1] = -2.0
if not candidates:
print(f" [{debug_prefix}] 无有效候选")
return None, 0, None, [], x_offset, y_offset, s_w, s_h
# 最右侧判定为干扰项:真实缺口不会紧贴背景图最右端
right_margin = max(15, int(bg_w * 0.06))
right_limit = bg_w - s_w - right_margin
# 真实缺口常为半透明白色矩形,白度是强判别信号(区域近白像素占比)
def region_whiteness(x, y, w, h):
roi = bg_img[y:y+h, x:x+w]
if roi.size == 0:
return 0.0
return float(np.all(roi > 200, axis=2).mean())
# 在有效区间 [s_w, right_limit] 内按「置信度 + 白度」综合评分选择
scored = []
for val, loc in candidates:
x, y = loc
if x <= s_w or x > right_limit: # 排除左端滑块区与最右侧干扰
continue
wn = region_whiteness(x, y, s_w, s_h)
score = val + 0.5 * wn
scored.append((score, val, loc))
print(f" [{debug_prefix}] 有效候选 loc={loc} conf={val:.4f} 白度={wn:.2f} 综合={score:.4f}")
if not scored:
best_val, best_loc = candidates[0] # 全部落在无效区,回退全局最高
print(f" [{debug_prefix}] 无有效区候选,回退最高置信度: loc={best_loc}, val={best_val:.4f}")
else:
scored.sort(key=lambda t: t[0], reverse=True)
best_val, best_loc = scored[0][1], scored[0][2]
print(f" [{debug_prefix}] 选择综合最优候选: loc={best_loc}, conf={best_val:.4f}")
distance_phys = best_loc[0] - x_offset
if distance_phys < 0:
distance_phys = 0
if distance_phys + s_w > bg_w:
distance_phys = bg_w - s_w
# ---- 若置信度极低,尝试 ORB 辅助 ----
if best_val < 0.25 and len(candidates) > 0:
orb = cv2.ORB_create(nfeatures=500)
kp1, des1 = orb.detectAndCompute(slider_edges, None)
kp2, des2 = orb.detectAndCompute(bg_edges, None)
if des1 is not None and des2 is not None and len(kp1) > 5 and len(kp2) > 5:
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
if len(matches) > 10:
good = [m for m in matches[:30] if m.distance < np.mean([m.distance for m in matches[:15]]) * 0.7]
if len(good) > 5:
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
offsets = dst_pts - src_pts
median_offset = np.median(offsets, axis=0)[0]
orb_x = int(median_offset[0]) - x_offset
if 0 < orb_x < bg_w - s_w:
print(f" [{debug_prefix}] ORB辅助偏移: {orb_x}px (原模板置信度{best_val:.3f})")
distance_phys = orb_x
best_val = 0.5 # 提升置信度用于显示
# ---- 构建候选列表(用于绘图) ----
candidate_points = []
for val, loc in candidates:
candidate_points.append((loc[0], loc[1], val))
print(f" [{debug_prefix}最终物理距离] distance={distance_phys}px (置信度 {best_val:.4f})")
return distance_phys, best_val, best_loc, candidate_points, x_offset, y_offset, s_w, s_h
def draw_match_debug_multi(bg_bytes, slider_bytes, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, save_path):
"""在背景图上绘制所有候选矩形和最佳匹配"""
try:
bg_img = Image.open(io.BytesIO(bg_bytes)).convert("RGBA")
draw = ImageDraw.Draw(bg_img)
# 绘制所有候选(灰色虚线框)
for i, (cx, cy, conf) in enumerate(candidate_points):
if (cx, cy) == (best_loc[0], best_loc[1]):
continue # 最佳单独绘制
rect = [cx, cy, cx + slider_w, cy + slider_h]
draw.rectangle(rect, outline="gray", width=1)
draw.text((cx + 5, cy - 10), f"conf={conf:.2f}", fill="gray")
# 绘制最佳匹配(红色实线)
if best_loc:
rect = [best_loc[0], best_loc[1], best_loc[0] + slider_w, best_loc[1] + slider_h]
draw.rectangle(rect, outline="red", width=3)
text = f"best phys={distance_phys} css={distance_css}"
draw.text((best_loc[0] + 5, best_loc[1] - 20), text, fill="red")
bg_img.save(save_path)
print(f" [匹配标记] 已保存: {save_path}")
except Exception as e:
print(f" [匹配标记] 绘制失败: {e}")
# ================== 轨迹生成与滑动(与原相同) ==================
def generate_track(distance):
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
aim = distance + overshoot
steps = []
moved = 0
y = 0
while moved < aim:
remain = aim - moved
if remain > 80:
dx = min(remain, random.randint(9, 15))
dt = random.uniform(0.010, 0.022)
elif remain > 35:
dx = min(remain, random.randint(5, 9))
dt = random.uniform(0.012, 0.028)
elif remain > 12:
dx = min(remain, random.randint(2, 5))
dt = random.uniform(0.016, 0.040)
else:
dx = min(remain, random.randint(1, 3))
dt = random.uniform(0.020, 0.060)
if random.random() < 0.22:
y = max(-2, min(2, y + random.choice([-1, 1])))
else:
y = int(round(y * 0.6))
steps.append((dx, y, dt))
moved += dx
if overshoot > 0:
back = overshoot
while back > 0:
dx = -min(back, random.randint(1, 3))
dt = random.uniform(0.030, 0.080)
if random.random() < 0.35:
y = random.choice([-1, 0, 1])
steps.append((dx, y, dt))
back += dx
if random.random() < 0.65:
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
(1, 0, random.uniform(0.020, 0.050)),
(-1, 0, random.uniform(0.020, 0.050))])
return steps
def perform_slide(page, btn, distance_css):
if distance_css <= 0:
return False
mid = btn.rect.midpoint
steps = generate_track(distance_css)
try:
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
duration=random.uniform(0.25, 0.60))
time.sleep(random.uniform(0.18, 0.45))
page.actions.hold(on_ele=btn)
time.sleep(random.uniform(0.12, 0.28))
for dx, dy, dt in steps:
if dx == 0 and dy == 0:
time.sleep(dt)
else:
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
if random.random() < 0.08:
time.sleep(random.uniform(0.010, 0.035))
time.sleep(random.uniform(0.10, 0.26))
page.actions.release()
return True
except Exception as e:
print(f"拖拽异常:{e}")
return False
# ================== 验证码处理(移除刷新按钮,容忍低置信度) ==================
def handle_captcha(page):
ensure_dir(DEBUG_DIR)
dpr = page.run_js('return window.devicePixelRatio')
print(f"设备像素比(DPR): {dpr}")
for retry in range(RETRY_MAX):
print(f"\n--- 第 {retry+1} 次尝试验证 ---")
try:
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
if not container:
print("验证码容器未出现")
continue
bg_ele = container.ele(BG_IMG)
if not bg_ele:
bg_ele = container.ele('div[style*="background-image"]')
if not bg_ele:
print("找不到背景图元素")
continue
slider_ele = container.ele(SLIDER_IMG)
if not slider_ele:
print("找不到滑块小图元素")
continue
if slider_ele.tag != 'img':
img_inner = slider_ele.ele('tag:img')
if img_inner:
slider_ele = img_inner
# 隐藏滑块 -> 截取背景 -> 恢复 -> 截取滑块
bg_screenshot = None
slider_screenshot = None
try:
page.run_js('arguments[0].style.display = "none"', slider_ele)
time.sleep(0.2)
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
page.run_js('arguments[0].style.display = ""', slider_ele)
time.sleep(0.2)
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
except Exception as e:
print(f"隐藏/截图过程出错:{e}")
try:
page.run_js('arguments[0].style.display = ""', slider_ele)
except:
pass
continue
if not bg_screenshot or not slider_screenshot:
print("截图数据为空")
continue
# 保存原始截图
bg_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}.png")
slider_path = os.path.join(DEBUG_DIR, f"slider_{retry}.png")
with open(bg_path, 'wb') as f:
f.write(bg_screenshot)
with open(slider_path, 'wb') as f:
f.write(slider_screenshot)
print(f" [调试截图] 背景: {bg_path}")
print(f" [调试截图] 滑块: {slider_path}")
# 调用改进的匹配函数
ret = match_slider_dual(bg_screenshot, slider_screenshot, debug_prefix=f"retry{retry}")
if ret[0] is None:
print("匹配失败,无候选,尝试随机拖动触发刷新")
# 随机拖动一段距离(比如100-300px)尝试触发刷新
random_css = random.uniform(100, 300) / dpr
btn = page.ele(SLIDER_BTN)
if btn:
perform_slide(page, btn, random_css)
time.sleep(2)
continue
distance_phys, conf, best_loc, candidate_points, x_offset, y_offset, slider_w, slider_h = ret
# 转换为 CSS 距离
distance_css = distance_phys / dpr
print(f" [置信度] {conf:.4f},物理距离: {distance_phys}px,CSS距离: {distance_css:.1f}px")
# 生成标记图(绘制所有候选)
marked_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}_marked.png")
draw_match_debug_multi(bg_screenshot, slider_screenshot, candidate_points, best_loc,
x_offset, y_offset, slider_w, slider_h,
distance_phys, distance_css, marked_path)
if distance_css <= 0:
print(" CSS距离无效,尝试随机拖动")
random_css = random.uniform(100, 300) / dpr
btn = page.ele(SLIDER_BTN)
if btn:
perform_slide(page, btn, random_css)
time.sleep(2)
continue
btn = page.ele(SLIDER_BTN)
if not btn:
print("找不到滑块按钮")
continue
# 执行滑动
perform_slide(page, btn, distance_css)
time.sleep(2) # 等待验证结果
# 检查是否登录成功
if SUCCESS_KEYWORD in page.url:
return True
# 若验证码容器消失,则认为验证通过
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
return True
else:
print("验证未通过,等待自动刷新...")
# 不点击刷新按钮,等待网站自行更新验证码
time.sleep(2)
except Exception as e:
print(f"异常:{e}")
time.sleep(1)
return False
# ================== 登录主流程(不变) ==================
def login():
co = ChromiumOptions()
if HEADLESS:
co.headless()
page = ChromiumPage(co)
# 尝试复用已保存的 cookies,免重复登录
saved = load_cookies()
if saved:
try:
page.set.cookies(saved)
page.get(LOGIN_URL)
time.sleep(2)
if SUCCESS_KEYWORD in page.url:
print("已通过缓存的 Cookies 登录")
return True
print("缓存的 Cookies 已失效,重新登录")
except Exception as e:
print(f"复用 Cookies 失败:{e}")
else:
page.get(LOGIN_URL)
time.sleep(2)
if SUCCESS_KEYWORD in page.url:
print("已登录")
return True
account = page.ele(ACCOUNT_INPUT)
if not account:
print("找不到账号输入框")
return False
account.clear()
account.input(USERNAME)
time.sleep(0.5)
pwd = page.ele(PASSWORD_INPUT)
if not pwd:
print("找不到密码输入框")
return False
pwd.clear()
pwd.input(PASSWORD)
time.sleep(0.5)
login_btn = page.ele(LOGIN_BTN)
if not login_btn:
print("找不到登录按钮")
return False
login_btn.click()
time.sleep(3)
if SUCCESS_KEYWORD in page.url:
print("登录成功(无滑块)")
save_browser_cookies(page)
return True
if handle_captcha(page):
print("登录成功(验证通过)")
save_browser_cookies(page)
return True
else:
print("登录失败")
return False
if __name__ == "__main__":
success = login()
print("最终结果:", "成功" if success else "失败")
@@ -1,58 +0,0 @@
# -*- coding: utf-8 -*-
"""
@Module: hrbp.ehr.common
@FileName: session_manager.py
@Author: 小布丁
@CreateTime: 2026-08-08 10:45
@Description: 从 login.py 持久化的 HR cookies 构建 requests 会话;支持会话过期重新登录刷新(供各 HR 业务模块复用)
@Version: 1.0.0
"""
import os
import json
from app.common.app_paths import get_sessions_dir
from app.utils.logger import get_logger
try:
import requests
except ImportError:
requests = None
logger = get_logger(__name__)
# HR 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,login.py 登录成功后保存)
_SESSIONS_DIR = get_sessions_dir()
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
def build_hr_session() -> "requests.Session":
"""用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。"""
if requests is None:
raise RuntimeError("缺少 requests 依赖,请先安装")
if not os.path.exists(HR_COOKIE_FILE):
logger.info("未找到 HR cookies 缓存,先执行 HR 登录")
refresh_hr_session()
if not os.path.exists(HR_COOKIE_FILE):
raise RuntimeError(f"HR 登录后仍未生成 cookies 文件:{HR_COOKIE_FILE}")
with open(HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
"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 refresh_hr_session() -> "requests.Session":
"""HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。"""
from app.service.hrbp.ehr.common.login import login as hr_login
if not hr_login():
raise RuntimeError("HR 登录态过期后重新登录失败")
return build_hr_session()