feat: 新增登录态过期不重试逻辑,优化社保核对流程
1. 重构重试装饰器,新增no_retry_on参数支持指定异常不重试 2. 为社保核对模块添加登录态过期检测与自动刷新逻辑 3. 统一两处社保业务代码的异常处理与会话重建流程 4. 更新版本号与默认输出目录配置
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 14:55
|
||||
@Description: 社保增减名单模块:复用 OA 登录态,监听首页请求动态获取参数并导出员工异动名单(精简版)
|
||||
@Version: 2.3.0
|
||||
@Version: 2.4.0
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -502,13 +502,32 @@ def _build_hr_session():
|
||||
return session
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _si_is_expired(text) -> bool:
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def _si_refresh_hr_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()
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _si_query_batch(session, codes_batch):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||||
resp.raise_for_status()
|
||||
if _si_is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
return resp.json()
|
||||
|
||||
|
||||
@@ -522,11 +541,23 @@ def _si_check_batch(session, codes_batch) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败返回空集合并告警。"""
|
||||
try:
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def _si_preflight(session):
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
_si_query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return _si_refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> str:
|
||||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。"""
|
||||
if _XlsxWorkbook is None:
|
||||
@@ -540,10 +571,17 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") ->
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = _build_hr_session()
|
||||
session = _si_preflight(_build_hr_session())
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||||
found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE])
|
||||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = _si_refresh_hr_session()
|
||||
found |= _si_check_batch(session, batch)
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
@CreateTime: 2026-08-07 15:20
|
||||
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
|
||||
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
|
||||
@Version: 2.0.0
|
||||
@Version: 2.1.0
|
||||
|
||||
业务判定(对应 aa.md):
|
||||
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
|
||||
@@ -87,6 +87,23 @@ RESULT_COL = "社保记录查询结果"
|
||||
BATCH_SIZE = 15
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. HR 会话(复用登录缓存 cookies)
|
||||
# ----------------------------------------------
|
||||
@@ -115,13 +132,15 @@ def build_hr_session() -> "requests.Session":
|
||||
# ----------------------------------------------
|
||||
# 2. 查询参保记录接口
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def query_batch(session, codes_batch: List[str]):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||||
resp.raise_for_status()
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
return resp.json()
|
||||
|
||||
|
||||
@@ -135,11 +154,23 @@ def check_codes(session, codes_batch: List[str]) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
|
||||
try:
|
||||
return extract_found_codes(query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def preflight(session) -> "requests.Session":
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return _refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 读取表格(支持 .xlsx / .xls)
|
||||
# ----------------------------------------------
|
||||
@@ -189,10 +220,17 @@ def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = build_hr_session()
|
||||
session = preflight(build_hr_session())
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), BATCH_SIZE):
|
||||
found |= check_codes(session, unique_codes[i:i + BATCH_SIZE])
|
||||
batch = unique_codes[i:i + BATCH_SIZE]
|
||||
try:
|
||||
found |= check_codes(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = _refresh_hr_session()
|
||||
found |= check_codes(session, batch)
|
||||
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3) # 轻微限速,避免触发风控
|
||||
|
||||
|
||||
@@ -23,12 +23,13 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3) -> Callable:
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
"""
|
||||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
||||
|
||||
Args:
|
||||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
||||
no_retry_on: 遇到这些异常类型时直接抛出、不做重试(用于无需重试的确定性失败)。
|
||||
|
||||
内部行为(对调用方透明):
|
||||
- 捕获所有 Exception;
|
||||
@@ -48,6 +49,8 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
|
||||
@@ -4,12 +4,11 @@
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07
|
||||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——OA 登录导出参保/停保名单 -> 清洗去重 -> HR 登录(滑块验证码)调用 si_main 参保记录接口核对 -> 追加结果列 -> 钉钉推送两张表
|
||||
@Version: 2.0.0
|
||||
@Version: 2.1.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 内含 HR 登录(滑块验证码识别),保证 si_main 查询所需的 hr.37du.co 登录态。
|
||||
- 社保模块无 SSO(SSO 仅用于加班/请假等单据解析),本脚本不含 SSO 逻辑。
|
||||
|
||||
业务判定:
|
||||
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
|
||||
@@ -23,7 +22,7 @@
|
||||
HR 登录:hr_login_url / hr_target_url_keyword / hr_login_username / hr_login_password
|
||||
钉钉推送:dingtalk_notify_enabled=true|false(默认false) / dingtalk_notify_target=联系人姓名
|
||||
可选:social_change_query_date=查询起始日期(如 2026-08-01,默认当月1号)
|
||||
social_change_output_dir=结果输出目录(默认当前目录)
|
||||
social_change_output_dir=结果输出目录(默认 D:\资料\人资\员工社保增减名单)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
@@ -188,7 +187,7 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3):
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
@@ -199,6 +198,8 @@ def retry(max_attempts: int = 3):
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
@@ -351,10 +352,10 @@ def get_oa_session():
|
||||
|
||||
|
||||
# ==================== HR 登录(滑块验证码) ====================
|
||||
HR_LOGIN_URL = None
|
||||
HR_SUCCESS_KEYWORD = None
|
||||
HR_USERNAME = None
|
||||
HR_PASSWORD = None
|
||||
HR_LOGIN_URL = "https://hr.37du.co/RedseaPlatform/"
|
||||
HR_SUCCESS_KEYWORD = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
HR_USERNAME = "Test01"
|
||||
HR_PASSWORD = "37du@1234"
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT_HR = "@id=j_username"
|
||||
PASSWORD_INPUT_HR = "@id=j_password_2"
|
||||
@@ -367,15 +368,6 @@ HR_TIMEOUT = 10
|
||||
HR_HEADLESS = False
|
||||
|
||||
|
||||
def _load_hr_env():
|
||||
global HR_LOGIN_URL, HR_SUCCESS_KEYWORD, HR_USERNAME, HR_PASSWORD
|
||||
load_dotenv()
|
||||
HR_LOGIN_URL = os.getenv('hr_login_url')
|
||||
HR_SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword')
|
||||
HR_USERNAME = os.getenv('hr_login_username')
|
||||
HR_PASSWORD = os.getenv('hr_login_password')
|
||||
|
||||
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。缺 opencv 时抛清晰错误。"""
|
||||
if cv2 is None or np is None:
|
||||
@@ -555,9 +547,8 @@ def handle_hr_captcha(page):
|
||||
|
||||
|
||||
def hr_login(username=None, password=None):
|
||||
_load_hr_env()
|
||||
if not (HR_LOGIN_URL and HR_SUCCESS_KEYWORD):
|
||||
raise RuntimeError("环境变量 hr_login_url / hr_target_url_keyword 未设置")
|
||||
raise RuntimeError("HR 登录配置未设置")
|
||||
final_username = username or HR_USERNAME
|
||||
final_password = password or HR_PASSWORD
|
||||
if not final_username or not final_password:
|
||||
@@ -847,12 +838,23 @@ def _read_and_clean(xls_path):
|
||||
|
||||
|
||||
# ==================== HR 参保记录核对 ====================
|
||||
@retry(max_attempts=3)
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _si_is_expired(text):
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _si_query_batch(session, codes_batch):
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||||
resp.raise_for_status()
|
||||
if _si_is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
return resp.json()
|
||||
|
||||
|
||||
@@ -864,11 +866,24 @@ def _si_found_codes(response_json):
|
||||
def _si_check_batch(session, codes_batch):
|
||||
try:
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def _si_preflight(session):
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建 session。"""
|
||||
try:
|
||||
_si_query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
hr_login()
|
||||
return _build_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir="."):
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
@@ -880,10 +895,18 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir="."):
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = get_hr_session()
|
||||
session = _si_preflight(get_hr_session())
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||||
found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE])
|
||||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
hr_login()
|
||||
session = _build_hr_session()
|
||||
found |= _si_check_batch(session, batch)
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
@@ -1136,7 +1159,8 @@ def push_report(text):
|
||||
def main():
|
||||
load_dotenv()
|
||||
args = sys.argv[1:]
|
||||
output_dir = os.getenv("social_change_output_dir") or os.getcwd()
|
||||
output_dir = os.getenv("social_change_output_dir") or r"D:\资料\人资\员工社保增减名单"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
query_date = None
|
||||
change_type = "全部"
|
||||
for a in args:
|
||||
|
||||
Reference in New Issue
Block a user