feat(hr_sdk): 考勤接口扩充并发布 0.2.5

This commit is contained in:
2026-11-27 17:18:30 +08:00
parent 26c2538fa3
commit d54e4f7676
9 changed files with 242 additions and 10 deletions
+5 -2
View File
@@ -4,7 +4,7 @@
分工:**SDK 出接口,插件出业务**。这里封装登录态访问、查询条件加密、异步导出、
分页拉全、模板解析等接口事实;异常判定、店长分组、文案、列名映射、落盘策略留在插件。
当前版本(0.2.4)覆盖:
当前版本(0.2.5)覆盖:
========================== ==========================================================
接口 入口
@@ -16,6 +16,9 @@
预入职台账 / 调动台账 / 预支台账 :mod:`ledger`(``export_pre_entry`` / ``export_transfer`` /
``export_advance_pay``)
组织机构 :mod:`org`(``rows``)
考勤(逐日/请假/打卡/异常/加班):mod:`attendance`(``daily`` / ``leaves`` / ``punches`` /
``abnormal`` / ``overtime`` / ``leave_records`` / ``punch_records``)
排班 :mod:`shift`(``person`` / ``day_shift`` / ``department_names``)
工资待办 / 账套 / 起调薪 :mod:`wage`(``rows`` / ``accounts`` / ``account_items`` /
``started`` / ``standards`` / ``submit_start`` / ``submit_change``)
工资卡导入(浏览器上下文) :mod:`wage_import`(``build_xlsx`` / ``import_cards``)
@@ -35,7 +38,7 @@
from __future__ import annotations
__version__ = "0.2.4"
__version__ = "0.2.5"
from . import (attach, attendance, auth, client, config, contract, errors, export, imports,
ledger, org, query, roster, seal, session, shift, wage, wage_import, workflow)
+70
View File
@@ -154,6 +154,22 @@ def test_client() -> None:
_raises(errors.ConfigError, lambda: client_mod.HrClient(None), "空会话抛 ConfigError")
class _CountingSession(_FakeSession):
def __init__(self):
self.posts = 0
def post(self, url, **kwargs):
self.posts += 1
return _Resp('{"userId":"u1","rootId":"cq37du"}')
sess = _CountingSession()
hr2 = client_mod.HrClient(sess, log=lambda m: None)
_eq(hr2.current_user().get("rootId"), "cq37du", "当前用户 rootId")
hr2.current_user()
_eq(sess.posts, 1, "当前用户信息结果缓存")
hr2.current_user(refresh=True)
_eq(sess.posts, 2, "refresh 强制重取当前用户")
# ==================== 导出机制 ====================
@@ -299,6 +315,40 @@ def test_workflow() -> None:
_eq(workflow.SUPERVISE_DEFAULTS["stru_tree_code"], "cq37du", "流程监控固定筛选条件")
class _KqStubClient:
"""考勤列表接口假客户端:固定 2 页、每页 1 行,不联网。"""
def __init__(self) -> None:
self.calls = []
self.log = lambda msg: None
def request_json(self, method, url, *, params=None, data=None, timeout=None,
label="", allow_list=False):
self.calls.append(dict(data or {}))
page = int((data or {}).get("pageNo") or 1)
return {"state": "1", "datas": [{"page": page}], "pageCount": 2, "count": 2}
def check_state(self, data, label=""):
if str(data.get("state")) != "1":
raise errors.ApiError("state != 1", payload=data)
return data
def paginate(self, fetch_page, *, page_size=200, max_pages=None, sleep=0.2):
rows = []
page_no = 1
limit = max_pages or client_mod.MAX_PAGES
while page_no <= limit:
page_rows, has_more = fetch_page(page_no, page_size)
rows.extend(page_rows)
if not has_more or not page_rows:
break
page_no += 1
return rows
def current_user(self, *, refresh=False):
return {"userId": "u1", "rootId": "cq37du"}
def test_attendance() -> None:
_eq(len(attendance.DAILY_STATUSES), 4, "逐日考勤四种状态")
ok = attendance._check_success({"success": True, "code": 200, "data": {}}, "x")
@@ -312,6 +362,26 @@ def test_attendance() -> None:
{"success": False, "code": 500, "message": "参数错误"}, "x"),
"业务失败 → ApiError")
stub = _KqStubClient()
rows = attendance.overtime(stub, "2026-10-01", "2026-10-31", work_type="3")
_eq(len(rows), 2, "加班明细分页合并 2 行")
_eq(stub.calls[0]["WORK_OVERTIME_TYPE"], "3", "加班类型入参")
_eq(stub.calls[0]["sqlId"], "kq_overtime_detail_select", "加班明细 sqlId")
_eq(stub.calls[-1]["pageNo"], 2, "加班明细第 2 页 pageNo")
attendance.abnormal(stub, "2026-10-01", "2026-10-31", is_adjusted="2")
_eq(stub.calls[-1]["is_adjusted"], "2", "考勤异常 is_adjusted 入参")
_eq(stub.calls[-1]["sqlId"], "kq_count_abnormal_Select", "考勤异常 sqlId")
attendance.leave_records(stub, "2026-10-01", "2026-10-31")
_eq(stub.calls[-1]["base_code"], "", "请假列表空工号=全部员工")
_eq(stub.calls[-1]["sqlId"], "select_kqLeave_record", "请假列表 sqlId")
attendance.punch_records(stub, "37031376", "2026-10-26", "2026-10-27")
_eq(stub.calls[-1]["base_code"], "37031376", "打卡明细工号入参")
_eq(stub.calls[-1]["work_day_begin"], "2026-10-26", "打卡明细起始日")
_eq(stub.calls[-1]["sqlId"], "kq_data_query", "打卡明细 sqlId")
def test_shift() -> None:
_eq(shift.day_shift([{"2026-11-09_team_name": "早班"}], "2026-11-09"), "早班",
+119 -2
View File
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""考勤接口:逐日考勤 / 请假记录 / 打卡明细。
"""考勤接口:逐日考勤 / 请假记录 / 打卡明细 / 考勤异常 / 加班明细。
用法::
@@ -9,6 +9,14 @@
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
@@ -16,14 +24,17 @@ from __future__ import annotations
import time
from typing import Dict, List
from .config import MAX_PAGES, REDSEA
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")
@@ -105,13 +116,119 @@ def punches(client, staff_id: str, start: str, end: str, *,
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",
]
+16 -1
View File
@@ -10,7 +10,8 @@ import os
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
from .config import DEFAULT_TIMEOUT, DOWNLOAD_TIMEOUT, MAX_ATTEMPTS, MAX_PAGES, XHR_HEADERS
from .config import (CUR_USER_INFO_URL, DEFAULT_TIMEOUT, DOWNLOAD_TIMEOUT, MAX_ATTEMPTS,
MAX_PAGES, XHR_HEADERS)
from .errors import ApiError, ConfigError, HrError, SessionExpiredError
from .session import SessionLike, looks_like_login_page
@@ -35,6 +36,7 @@ class HrClient:
self.timeout = float(timeout if timeout is not None else DEFAULT_TIMEOUT)
self.retries = max(1, int(retries if retries is not None else MAX_ATTEMPTS))
self.log: LOGGER = log or (lambda msg: None)
self._user_info: Optional[Dict[str, Any]] = None
# ---------------- 底层 ----------------
def get(self, url: str, *, params: Optional[dict] = None,
@@ -153,6 +155,19 @@ class HrClient:
return self.paginate(_fetch, page_size=page_size)
# ---------------- 当前用户 ----------------
def current_user(self, *, refresh: bool = False) -> Dict[str, Any]:
"""当前登录用户信息(``getCurUserInfo``,结果缓存);登录态失效抛异常。
返回原始 dict(含 ``userId`` / ``rootId`` 等);``refresh=True`` 强制重取,
用于插件启动时的登录态校验。
"""
if self._user_info is None or refresh:
data = self.request_json("POST", CUR_USER_INFO_URL, data={},
label="当前用户信息")
self._user_info = data if isinstance(data, dict) else {}
return self._user_info
# ---------------- 文件 ----------------
def download(self, url: str, *, save_dir: str = "", filename: str = "",
timeout: Optional[float] = None) -> str:
+4
View File
@@ -15,6 +15,9 @@ from typing import Dict, Optional
HR_BASE_URL = (os.getenv("HR_BASE_URL") or "https://hr.37du.co").rstrip("/")
REDSEA = f"{HR_BASE_URL}/RedseaPlatform"
#: 当前登录用户信息(校验登录态,取 userId / rootId)
CUR_USER_INFO_URL = f"{REDSEA}/PtUsers.mc?method=getCurUserInfo"
#: 会话注册(未注册时 WS 握手 500)
BRIDGE_URL = f"{REDSEA}/ws/bridge"
#: 异步导出推送主题
@@ -142,6 +145,7 @@ def base_params(menu_name: str, table_id: str, roster_id: str,
__all__ = [
"BRIDGE_URL",
"COOKIES_FILE",
"CUR_USER_INFO_URL",
"DEFAULT_TIMEOUT",
"DOWNLOAD_TIMEOUT",
"EXPORT_TIMEOUT_SECONDS",