本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
270 lines
11 KiB
Python
270 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0009 插件 - HR 接口(考勤统计报表 / 请假记录)与按月懒缓存。
|
||
|
||
由 workflows/.../absence_analysis.py 内联 HR 逻辑移植:
|
||
- 会话改由底座注入(config 全局钩子),删除自动补登逻辑——登录态失效直接抛
|
||
HRSessionExpiredError,由调用方转为「请重新登录 HR」明确提示(插件开发规范 §7);
|
||
- 请求带项目级重试(最多 3 次,4xx 不重试);
|
||
- 历史月接口数据按月落盘懒缓存(跨月追溯复用),统计月/当前月始终实时。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
|
||
import requests
|
||
|
||
from ..config import (
|
||
logger, CACHE_DIR, MAX_REQUEST_RETRY,
|
||
HR_BASE_URL, GET_CUR_USER_INFO_URL, LEAVE_URL, PAGE_MAX_SIZE,
|
||
MONTH_ATT_REPORT_URL, MONTH_ATT_REPORT_ID, COMPANY_STRU_ID, REPORT_PAGE_SIZE,
|
||
)
|
||
|
||
|
||
class HRSessionExpiredError(Exception):
|
||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||
|
||
|
||
def _request_with_retry(session, method, url, params, timeout, label):
|
||
"""带项目级重试的 HTTP 请求:连接/超时/5xx 等瞬时故障最多重试 MAX_REQUEST_RETRY 次。
|
||
|
||
4xx 业务类错误(401/403 等)重试无意义,直接抛出;三次仍失败后抛出最后一次异常。
|
||
"""
|
||
last_exc = None
|
||
for attempt in range(1, MAX_REQUEST_RETRY + 1):
|
||
try:
|
||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||
resp.raise_for_status()
|
||
return resp
|
||
except requests.HTTPError as e:
|
||
if e.response is not None and e.response.status_code < 500:
|
||
raise # 4xx 不重试
|
||
last_exc = e
|
||
except (requests.ConnectionError, requests.Timeout) as e:
|
||
last_exc = e
|
||
if attempt < MAX_REQUEST_RETRY:
|
||
delay = 2 ** (attempt - 1) # 1s / 2s / 4s 指数退避
|
||
logger.warning("%s 第 %d 次请求失败(%s),%d 秒后重试", label, attempt, last_exc, delay)
|
||
time.sleep(delay)
|
||
logger.error("%s 请求重试 %d 次仍失败:%s", label, MAX_REQUEST_RETRY, last_exc)
|
||
raise last_exc
|
||
|
||
|
||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||
"""POST/GET 请求(带项目级重试)并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||
resp = _request_with_retry(session, method, url, params, timeout, label)
|
||
text = resp.text
|
||
if not text or not text.lstrip().startswith(("{", "[")):
|
||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON),请重新登录 HR 后再重试")
|
||
return resp.json()
|
||
|
||
|
||
def validate_session(session):
|
||
"""调用 getCurUserInfo 校验登录态有效性,返回 userId;失效抛 HRSessionExpiredError。"""
|
||
info = hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||
user_id = info.get("userId", "")
|
||
if not user_id:
|
||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||
logger.info("HR 会话校验通过,user_id=%s", user_id)
|
||
return user_id
|
||
|
||
|
||
# ==================== 考勤统计报表 ====================
|
||
def fetch_attendance_stat_page(session, user_id, month, page_no=1, page_size=REPORT_PAGE_SIZE,
|
||
stru_id=COMPANY_STRU_ID, base_code=""):
|
||
"""请求单页「考勤统计报表」数据。
|
||
|
||
返回 datas 一条记录 = 一个员工在查询月的逐日出勤,动态列 key 形如 v_1~v_最后一天,
|
||
值为该日状态(休息/旷工/迟到/漏打卡/早退等)。
|
||
"""
|
||
params = {
|
||
"reportId": MONTH_ATT_REPORT_ID,
|
||
"struId": stru_id,
|
||
"start": (page_no - 1) * page_size,
|
||
"sortType": "",
|
||
"sortName": "",
|
||
"pageNo": page_no,
|
||
"pageSize": page_size,
|
||
"ds1.userId": user_id,
|
||
"ds1.struId": stru_id,
|
||
"ds1.month": month,
|
||
"ds2.stru_id": stru_id,
|
||
"ds3.month": "#ds1.month#",
|
||
"orgTypeCode": "1",
|
||
"rootId": "cq37du",
|
||
"showSetField": "1",
|
||
"menuName": "考勤统计报表",
|
||
"treePermitType": "permit",
|
||
"struTreeCode": "cq37du",
|
||
"belongUnitStruId": stru_id,
|
||
"isVirtual": "0",
|
||
"isHistory": "undefined",
|
||
"useSealTreeData": "0",
|
||
"orgAlias": "集团",
|
||
"commonQuery": "[]",
|
||
"ds1.base_code": base_code,
|
||
}
|
||
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
|
||
return hr_request_json(session, "POST", url, params, "考勤统计报表")
|
||
|
||
|
||
def fetch_all_attendance_stat(session, user_id, month, stru_id=COMPANY_STRU_ID, base_code=""):
|
||
"""分页抓取某月「考勤统计报表」明细(每人一行,含 v_1~v_最后一天)。
|
||
|
||
base_code 非空时仅查该员工(跨月追溯单人查询)。
|
||
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免导出缺人名单)。
|
||
"""
|
||
all_rows = []
|
||
page_no = 1
|
||
while True:
|
||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||
if data.get("state") != "1":
|
||
raise RuntimeError(f"考勤统计报表第 {page_no} 页请求失败:{data.get('meg')}")
|
||
page_list = data.get("datas", []) or []
|
||
if not page_list:
|
||
logger.info("考勤统计报表无更多数据")
|
||
break
|
||
all_rows.extend(page_list)
|
||
total_page = data.get("pageCount", 0)
|
||
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 fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||
"""请求单页请假记录数据。"""
|
||
params = {
|
||
"STRU_TREE_CODE": treecode,
|
||
"user_id": 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_time,
|
||
"end_time": end_time,
|
||
"start": str((page_no - 1) * page_size),
|
||
"sortType": "desc",
|
||
"sortName": "operat_time",
|
||
"pageNo": page_no,
|
||
"pageSize": page_size,
|
||
}
|
||
return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询")
|
||
|
||
|
||
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||
"""分页抓取指定工号、日期范围内的全部请假记录。
|
||
|
||
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免漏掉仍在休假的假单)。
|
||
"""
|
||
all_rows = []
|
||
page_no = 1
|
||
while True:
|
||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||
treecode, page_no, PAGE_MAX_SIZE)
|
||
if data.get("state") != "1":
|
||
raise RuntimeError(f"请假查询第 {page_no} 页请求失败:{data.get('meg')}")
|
||
page_list = data.get("datas", []) or []
|
||
if not page_list:
|
||
logger.info("请假查询无更多数据")
|
||
break
|
||
all_rows.extend(page_list)
|
||
total_page = data.get("pageCount", 0)
|
||
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 _cache_path(kind, month_key, code=""):
|
||
"""构造缓存文件路径。kind ∈ {att, leave};month_key 为 "YYYYMM";code 空表示全量。"""
|
||
fname = f"{kind}_{month_key}" + (f"_{code}" if code else "")
|
||
return os.path.join(CACHE_DIR, fname + ".json")
|
||
|
||
|
||
def _read_cache(path):
|
||
"""读取缓存列表;不存在/损坏返回 None。"""
|
||
if not os.path.exists(path):
|
||
return None
|
||
try:
|
||
with open(path, encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
return data if isinstance(data, list) else None
|
||
except Exception as e:
|
||
logger.warning("缓存读取失败,忽略:%s(%s)", path, e)
|
||
return None
|
||
|
||
|
||
def _write_cache(path, records):
|
||
"""把接口返回的 datas 列表写入缓存(失败仅告警,不影响主流程)。"""
|
||
try:
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
with open(path, "w", encoding="utf-8") as f:
|
||
json.dump(records, f, ensure_ascii=False)
|
||
except Exception as e:
|
||
logger.warning("缓存写入失败,忽略:%s(%s)", path, e)
|
||
|
||
|
||
def cached_attendance(session, user_id, month_key, base_code=""):
|
||
"""按月缓存整月考勤统计报表:先查缓存,未命中才调接口并落盘,下次直接复用。
|
||
|
||
month_key:月份 "YYYYMM";base_code 非空时为该员工单人报表(跨月追溯单人模式)。
|
||
"""
|
||
path = _cache_path("att", month_key, base_code)
|
||
cached = _read_cache(path)
|
||
if cached is not None:
|
||
logger.info("命中考勤报表缓存:%s(%d 条)", os.path.basename(path), len(cached))
|
||
return cached
|
||
records = fetch_all_attendance_stat(session, user_id, month_key, base_code=base_code)
|
||
_write_cache(path, records)
|
||
return records
|
||
|
||
|
||
def cached_leave(session, user_id, base_code, month_str):
|
||
"""按月缓存整月请假记录:先查缓存,未命中才调接口并落盘,下次直接复用。
|
||
|
||
month_str:月份 "YYYY-MM";base_code 空为全集团,非空为该员工(跨月追溯单人模式)。
|
||
"""
|
||
month_key = month_str.replace("-", "")
|
||
path = _cache_path("leave", month_key, base_code)
|
||
cached = _read_cache(path)
|
||
if cached is not None:
|
||
logger.info("命中请假记录缓存:%s(%d 条)", os.path.basename(path), len(cached))
|
||
return cached
|
||
from datetime import date, timedelta
|
||
|
||
def month_range(m):
|
||
import calendar
|
||
s = str(m).replace("-", "")
|
||
year, mon = int(s[:4]), int(s[4:6])
|
||
last_day = calendar.monthrange(year, mon)[1]
|
||
return date(year, mon, 1), date(year, mon, last_day)
|
||
|
||
mb, me = month_range(month_str)
|
||
records = fetch_all_leave(session, user_id, base_code,
|
||
mb.strftime("%Y-%m-%d"), me.strftime("%Y-%m-%d"))
|
||
_write_cache(path, records)
|
||
return records
|