# -*- coding: utf-8 -*- """HR 参保记录查询(si_main 接口,登录态由底座注入)。 按工号批(15 个/批)查询 HR 是否已有社保参保记录: - 接口返回 JSON 且 datas 中出现的 base_Code 即「有参保记录」; - 返回非 JSON(登录页/错误页)视为登录态过期,直接上抛提示重新登录 HR, 不做自动补登、也不把「查不到」当成「无记录」(避免大批误标异常); - 网络超时等其它异常按批次重试 3 次(项目级重试约定),仍失败由调用方标注 「查询失败,需人工复核」。 """ import time from .. import config class HRSessionExpiredError(Exception): """HR 登录态过期:接口返回登录页等非 JSON 内容。""" def _looks_expired(text): return bool(text) and not text.lstrip().startswith(("{", "[")) def _query_once(session, codes_batch): params = dict(config.SI_BASE_PARAMS) params["base_codes"] = ",".join(str(c) for c in codes_batch) resp = session.post(config.SI_QUERY_URL, data=params, timeout=30) resp.raise_for_status() if _looks_expired(resp.text or ""): raise HRSessionExpiredError("HR 接口返回非 JSON 内容(登录态可能已过期)") return resp.json() def query_batch(session, codes_batch): """查询一批工号,返回接口 JSON;登录态过期不重试,其它异常最多重试 3 次。""" last_err = None for attempt in range(1, config.SI_QUERY_RETRY + 1): try: return _query_once(session, codes_batch) except HRSessionExpiredError: raise except Exception as e: last_err = e if attempt >= config.SI_QUERY_RETRY: break delay = 1.0 * attempt config.logger.warning("参保记录查询第 %d 次失败:%s,%.1f 秒后重试", attempt, e, delay) time.sleep(delay) raise RuntimeError(f"参保记录查询失败(已重试 {config.SI_QUERY_RETRY} 次):{last_err}") def found_codes(response_json): """从接口响应中取出「有参保记录」的工号集合。""" datas = (response_json or {}).get("datas") or [] return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")} def preflight(session): """正式核对前探测一次接口,确认 HR 登录态有效(失效抛 HRSessionExpiredError)。""" try: query_batch(session, ["0"]) except HRSessionExpiredError: raise except Exception as e: # 超时也可能由 cookies 过期(重定向登录页后加载超时)引发,统一按登录态问题提示 raise HRSessionExpiredError(f"预检查询异常(HR 登录态可能已过期):{e}") return session