refactor: 重构多插件 UI 与配置结构,新增抖音/新美大平台核对插件
- 新增 XQ0042 抖音平台核对、XQ0041 新美大平台核对插件的 UI 源码与打包脚本 - 重构续签电子签、服务岗转正不通过电子签等插件的版本与配置 - 删除旧版考勤异常处理、微盟数据导出等冗余插件文件 - 修复出勤积分更新插件的 OPM 推送判断逻辑 - 优化壳子插件页面的 iframe 滚动条样式
This commit is contained in:
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 数据层。"""
|
||||
@@ -1,348 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - HR 接口层(由影刀版 overtime_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查加班流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId
|
||||
3) WorkformEngine getBusinessDate 取加班表单数据
|
||||
4) rf_s_kq_count_leave_yc_day_all 按员工+日期范围取每日考勤(班次名/班次起止)
|
||||
5) rf_s_kq_leave_record_SelectByStaffID 取请假记录(弹性兑换前置校验)
|
||||
6) rf_s_kq_data_queryByStaffId 取打卡明细(kq_time/bc_date/time_order)
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, ATTENDANCE_DAILY_URL, LEAVE_RECORD_URL, PUNCH_RECORD_URL,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 加班流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 每日考勤(排班 + 班次时段) ====================
|
||||
def get_attendance_daily(session, staff_id, start_date, end_date):
|
||||
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
kq_status_total 按考勤状态分类返回记录:0=休息日、1=正常班、9=未打卡、11=异常,
|
||||
需四种状态各查一次,再按 work_day 合并去重,才能同时拿到班次名/班次时段与休息日记录。
|
||||
"""
|
||||
by_day = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"考勤逐日接口请求失败: {e}") from e
|
||||
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 请假记录 ====================
|
||||
def fetch_leave_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
data = {
|
||||
"sub_type": sub_type,
|
||||
"staff_id": staff_id,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"pageSize": str(page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
}
|
||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"请假记录接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_leave_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
all_records = []
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 打卡明细 ====================
|
||||
def fetch_punch_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""请求单页员工打卡明细(kq_time 真实打卡时间 / bc_date 考勤归属日 / time_order 1上2下)。"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"打卡明细接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""查询员工某时间段内的全部打卡明细(自动分页)。"""
|
||||
all_records = []
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
@@ -1,124 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
Reference in New Issue
Block a user