Files
37duAutomation/plugins/XQ0001-0100/XQ0006 EHR系统周考勤异常处理/data/hr_api.py
T
puddy 50fb138e1b feat(plugin): 新增 XQ0006 周考勤异常处理、XQ0083 调动流程生效确认;其余插件累积改动
XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
2026-11-18 18:55:59 +08:00

166 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0006 数据层:HR 考勤异常查询与确认接口(纯接口,无浏览器)。"""
import time
from .. import config
IS_ADJUSTED = config.IS_ADJUSTED
PAGE_MAX_SIZE = config.PAGE_MAX_SIZE
MAX_ATTEMPTS = 3
RETRY_WAIT = 1.0
class HRSessionExpiredError(RuntimeError):
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
def hr_request_json(session, method, url, params, label, timeout=config.HTTP_TIMEOUT):
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
resp = session.request(method.upper(), url, data=params, timeout=timeout)
resp.raise_for_status()
text = resp.text
if not text or not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON),请重新登录 HR 后重试")
return resp.json()
def fetch_cur_user_info(session):
return hr_request_json(session, "POST", config.GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
def validate_session(session):
"""校验底座注入的 HR 会话,返回 (user_id, treecode);会话无效抛错提示重新登录。"""
info = fetch_cur_user_info(session)
user_id = str(info.get("userId", "") or "")
treecode = str(info.get("rootId", "") or "")
if not user_id or not treecode:
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
config.logger.info("HR 会话校验通过,user_id=%s,treecode=%s", user_id, treecode)
return user_id, treecode
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
page_no=1, page_size=PAGE_MAX_SIZE,
is_adjusted=IS_ADJUSTED, abnormal_type=""):
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", config.ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
is_adjusted=IS_ADJUSTED, abnormal_type=""):
"""分页拉取全部考勤异常。"""
all_rows = []
page_no = 1
while True:
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date,
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
if str(data.get("state")) != "1":
raise RuntimeError(f"考勤异常第 {page_no} 页请求失败:{data.get('meg')}")
page_list = data.get("datas", []) or []
if not page_list:
break
all_rows.extend(page_list)
total_page = int(data.get("pageCount", 0) or 0)
config.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 adjust_abnormal(session, abnormal_ids, type_code=1):
"""确认/调整考勤异常单据(type=1 自动确认异常)。"""
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", config.ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
def _confirm_batch(session, ids):
"""确认一批异常(最多重试 3 次),失败抛错。"""
last_err = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
result = adjust_abnormal(session, ids)
if str(result.get("state")) == "1":
return True
last_err = result.get("meg") or result
except HRSessionExpiredError:
raise
except Exception as e: # noqa: BLE001 - 网络/接口异常统一重试
last_err = e
config.logger.warning("考勤异常自动确认第 %d/%d 次失败:%s",
attempt, MAX_ATTEMPTS, last_err)
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT * attempt)
raise RuntimeError(f"考勤异常自动确认失败({len(ids)} 条):{last_err}")
def auto_confirm_all(session, data, batch_size=config.CONFIRM_BATCH_SIZE, on_progress=None):
"""自动确认查询范围内的全部异常(分批提交,批次失败不中断其余批次)。
Returns:
(待确认条数, 确认成功条数, 失败 id 列表)
"""
ids = [it.get("abnormal_id") for it in data if it.get("abnormal_id")]
if not ids:
config.logger.info("无可确认的异常单据编号,跳过自动确认")
return 0, 0, []
confirmed = 0
failed = []
total = len(ids)
for start in range(0, total, batch_size):
batch = ids[start:start + batch_size]
try:
_confirm_batch(session, batch)
confirmed += len(batch)
config.logger.info("自动确认进度:%d/%d 条", confirmed, total)
except HRSessionExpiredError:
raise
except Exception as e: # noqa: BLE001 - 单批失败继续其余批次
failed.extend(batch)
config.logger.error("自动确认失败(%d 条):%s", len(batch), e)
if on_progress:
on_progress(confirmed, total)
return total, confirmed, failed