Files
37duAutomation/libs/hr_sdk/hr_sdk/attendance.py
T

235 lines
11 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 -*-
"""考勤接口:逐日考勤 / 请假记录 / 打卡明细 / 考勤异常 / 加班明细。
用法::
from hr_sdk import HrClient, attendance
client = HrClient(ctx.get_session("hr"))
days = attendance.daily(client, staff_id, "2026-10-01", "2026-10-31")
leaves = attendance.leaves(client, staff_id, "2026-10-01", "2026-10-31")
punches = attendance.punches(client, staff_id, "2026-10-01", "2026-10-31")
abnormal = attendance.abnormal(client, "2026-10-01", "2026-10-31", is_adjusted="2")
overtime = attendance.overtime(client, "2026-10-01", "2026-10-31", work_type="1")
all_leaves = attendance.leave_records(client, "2026-10-01", "2026-10-31") # 空工号=全部员工
day_punch = attendance.punch_records(client, "37031376", "2026-10-26", "2026-10-27")
说明:``abnormal`` / ``overtime`` / ``leave_records`` / ``punch_records`` 走
``kqController/getPageAjaxList.mc`` 列表接口(``state``/``datas`` 信封);
``daily`` / ``leaves`` / ``punches`` 走 ``redApiExec`` 单员工接口(``success`` 信封)。
"""
from __future__ import annotations
import time
from typing import Dict, List
from .config import MAX_PAGES, PAGE_MAX_SIZE, REDSEA
from .errors import ApiError, SessionExpiredError
ATTENDANCE_DAILY_URL = f"{REDSEA}/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
LEAVE_RECORD_URL = f"{REDSEA}/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
PUNCH_RECORD_URL = f"{REDSEA}/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
#: 考勤列表类接口(考勤异常 / 请假 / 加班 / 打卡明细)
KQ_LIST_URL = f"{REDSEA}/kqController/getPageAjaxList.mc"
DEFAULT_PAGE_SIZE = 100
DEFAULT_TREE_CODE = "cq37du"
#: 逐日考勤按考勤状态各查一次:0=休息日 1=正常班 9=未打卡 11=异常
DAILY_STATUSES = ("0", "1", "9", "11")
def _check_success(data: dict, label: str) -> dict:
"""``redApiExec`` 用 ``success/code`` 信封(与 ``state`` 不同)。"""
if data.get("success") is True and str(data.get("code")) == "200":
return data
message = str(data.get("message") or data.get("msg") or data)
if any(hint in message for hint in ("会话", "登录")):
raise SessionExpiredError(f"{label}登录态失效:{message}")
raise ApiError(f"{label}返回失败:{message}", code=str(data.get("code") or ""),
payload=data)
def _page_records(client, url: str, payload: dict, label: str, *,
page_size: int = DEFAULT_PAGE_SIZE, max_pages: int = MAX_PAGES,
sleep: float = 0.2) -> List[dict]:
"""``data{list,total,pageCount}`` 形态的自动分页。"""
records: List[dict] = []
page_count = 1
for page_no in range(1, max_pages + 1):
body = dict(payload)
body.update({"start": str((page_no - 1) * page_size), "pageNo": str(page_no),
"pageSize": str(page_size)})
data = _check_success(client.request_json("POST", url, data=body, label=label),
label)
info = data.get("data") if isinstance(data.get("data"), dict) else {}
page_rows = info.get("list") or []
records.extend(page_rows)
if page_no == 1:
page_count = int(info.get("pageCount") or 1)
client.log(f"[INFO] {label}共 {info.get('total')} 条 / {page_count} 页")
if page_no >= page_count or not page_rows:
break
if sleep:
time.sleep(sleep)
return records
# ==================== 逐日考勤 ====================
def daily(client, staff_id: str, start: str, end: str) -> List[dict]:
"""按员工 + 日期范围查每日考勤(按 ``work_day`` 合并四种状态)。"""
by_day: Dict[str, dict] = {}
for status in DAILY_STATUSES:
params = {"staff_id": staff_id, "begin_date": start, "end_date": end,
"kq_status_total": status}
data = client.request_json("POST", ATTENDANCE_DAILY_URL, data=params,
label="考勤逐日")
_check_success(data, "考勤逐日")
for row in data.get("data") or []:
by_day.setdefault(str(row.get("work_day", "")), row)
records = [by_day[k] for k in sorted(by_day)]
client.log(f"[INFO] 逐日考勤合并 {len(records)} 天({staff_id} {start}~{end})")
return records
# ==================== 请假 / 打卡 ====================
def leaves(client, staff_id: str, start: str, end: str, *,
sub_type: str = "-1", page_size: int = DEFAULT_PAGE_SIZE) -> List[dict]:
"""请假记录(自动分页)。"""
payload = {"sub_type": sub_type, "staff_id": staff_id,
"begin_date": start, "end_date": end,
"sortType": "", "sortName": ""}
return _page_records(client, LEAVE_RECORD_URL, payload, "请假记录",
page_size=page_size)
def punches(client, staff_id: str, start: str, end: str, *,
sub_type: str = "-1", page_size: int = DEFAULT_PAGE_SIZE) -> List[dict]:
"""打卡明细(自动分页;``kq_time`` 真实打卡时间 / ``bc_date`` 考勤归属日)。"""
payload = {"staff_id": staff_id, "rootId": "", "countId": "",
"bc_date": start, "bc_date_end": end,
"begin": start, "end": end, "sub_type": sub_type,
"sortType": "", "sortName": ""}
return _page_records(client, PUNCH_RECORD_URL, payload, "打卡明细",
page_size=page_size)
# ==================== 列表查询(kqController/getPageAjaxList.mc) ====================
def _list_pages(client, params: dict, label: str,
page_size: int = PAGE_MAX_SIZE) -> List[dict]:
"""``state``/``datas``/``pageCount`` 信封的自动分页。"""
def _fetch(page_no: int, size: int):
body = dict(params)
body.update({"start": str((page_no - 1) * size), "pageNo": page_no,
"pageSize": size})
data = client.request_json("POST", KQ_LIST_URL, data=body, label=label)
client.check_state(data, label)
page_rows = data.get("datas") or []
total_page = int(data.get("pageCount") or 0)
if page_no == 1:
client.log(f"[INFO] {label}共 {data.get('count') or len(page_rows)} 条 / "
f"{total_page or 1} 页")
return page_rows, bool(total_page and page_no < total_page)
return client.paginate(_fetch, page_size=page_size, sleep=0.2)
def _user_id(client, user_id: str) -> str:
"""取 userId:调用方显式传入优先,否则用当前登录用户(``getCurUserInfo``)。"""
return str(user_id or client.current_user().get("userId") or "")
def abnormal(client, start: str, end: str, *, is_adjusted: str = "",
treecode: str = DEFAULT_TREE_CODE, user_id: str = "",
page_size: int = PAGE_MAX_SIZE) -> List[dict]:
"""考勤异常明细(``is_adjusted``:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=全部)。"""
params = {
"treecode": treecode, "user_id": _user_id(client, 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, "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": start, "end_date": end, "STAFF_NAME": "",
"sortType": "desc", "sortName": "work_day",
}
return _list_pages(client, params, "考勤异常", page_size)
def overtime(client, start: str, end: str, *, work_type: str = "",
base_code: str = "", treecode: str = DEFAULT_TREE_CODE,
user_id: str = "", page_size: int = PAGE_MAX_SIZE) -> List[dict]:
"""加班明细(``work_type``:1=延时加班、2=法定假日加班、3=休息日加班、空=全部)。"""
params = {
"STRU_TREE_CODE": treecode, "user_id": _user_id(client, 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": work_type,
"start_time": start, "end_time": end,
"sortType": "desc", "sortName": "OPERATE_TIME",
}
return _list_pages(client, params, "加班查询", page_size)
def leave_records(client, start: str, end: str, *, base_code: str = "",
treecode: str = DEFAULT_TREE_CODE, user_id: str = "",
page_size: int = PAGE_MAX_SIZE) -> List[dict]:
"""请假记录列表(``base_code`` 留空=全部员工)。"""
params = {
"STRU_TREE_CODE": treecode, "user_id": _user_id(client, 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, "end_time": end,
"sortType": "desc", "sortName": "operat_time",
}
return _list_pages(client, params, "请假查询", page_size)
def punch_records(client, base_code: str, start: str, end: str, *,
treecode: str = DEFAULT_TREE_CODE, user_id: str = "",
page_size: int = PAGE_MAX_SIZE) -> List[dict]:
"""按工号拉打卡明细(``kq_data_query``,含 ``kq_time`` 打卡时间)。"""
params = {
"user_id": _user_id(client, user_id), "sqlId": "kq_data_query",
"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, "work_day_end": end,
"base_code": base_code, "STAFF_NAME": "", "sortType": "", "sortName": "",
}
return _list_pages(client, params, "打卡查询", page_size)
__all__ = [
"ATTENDANCE_DAILY_URL",
"DAILY_STATUSES",
"DEFAULT_PAGE_SIZE",
"DEFAULT_TREE_CODE",
"KQ_LIST_URL",
"LEAVE_RECORD_URL",
"PUNCH_RECORD_URL",
"abnormal",
"daily",
"leave_records",
"leaves",
"overtime",
"punch_records",
"punches",
]