feat: 新增HR纯接口登录OA接口探针及试用期变更流程增强
新增3个核心文件: 1. workflows/share/oa_login_api.py:OA纯接口登录模块,与浏览器版输出兼容 2. workflows/share/hr_login_api.py:HR纯接口登录模块,支持滑块验证,与浏览器版输出兼容 3. workflows/share/_probe_we_process_todo.py:HR WeProcess待办探针,验证替代OA待办+SSO链路 同时增强试用期变更流程: - 新增流程交叉验证逻辑,处理已被他人操作的情况 - 新增离职电子签详情链接获取逻辑 - 新增AI表格自动回填逻辑,处理无需处理的情况 - 新增流程待办查询接口,支持反查流程实例
This commit is contained in:
@@ -11,8 +11,13 @@
|
||||
pip install DrissionPage python-dotenv Pillow numpy rapidocr onnxruntime
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
|
||||
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
待办链路(纯 HR 接口,全程不依赖 OA 登录与 SSO 解析):
|
||||
WeProcess.mc?method=getProcessAndData(按标题关键字拉流程待办,行内自带
|
||||
taskId/businessKey/processId)-> WfActivity.mc 取 formId
|
||||
-> WorkformEngine.mc?method=getBusinessDate 取表单数据。
|
||||
|
||||
推送(本脚本只生成待推送文本,不内联发送):
|
||||
main() 将结果消息写入影刀全局变量 messages,由「37du钉钉群机器人推送」指令发送。
|
||||
@@ -29,7 +34,6 @@ import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
# ==================== VC++ 运行库预加载(自包含,目标机免装运行库) ====================
|
||||
# onnxruntime 强依赖新版 MSVC 运行库 DLL(msvcp140*.dll / vcruntime140*.dll),缺失会报
|
||||
@@ -75,21 +79,15 @@ except ImportError as _import_err:
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有
|
||||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 workflows/share/oa_login.py)
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令写入(见 workflows/share/hr_login_api.py)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令(workflows/share/hr_login.py)写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# ---------- HR 系统(待办/表单/排班/附件全部走 HR,不再依赖 OA) ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_TYPE = "13"
|
||||
# 流程待办查询:数据行在响应 jsonList/datas(随服务端版本切换,已兼容),行内自带 taskId/businessKey/processId/formId(免 SSO 解析)
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
@@ -367,10 +365,6 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
@@ -404,100 +398,89 @@ def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== OA/HR API 接口 ====================
|
||||
def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
# ==================== HR API 接口(流程待办 WeProcess) ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""调 WeProcess getProcessAndData 拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"method": "list",
|
||||
"dataType": "todo",
|
||||
"fdType": FD_TYPE,
|
||||
"fdCateId": "",
|
||||
# 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
|
||||
"q.s_raq": str(random.random()),
|
||||
"q.fdSubject": subject,
|
||||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||||
"pageno": page_no,
|
||||
"rowsize": page_size,
|
||||
"pagingtype": "default",
|
||||
"orderby": "fdCreateTime",
|
||||
"ordertype": "down",
|
||||
"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),
|
||||
}
|
||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
||||
|
||||
session.get(url)
|
||||
session.post(WE_PROCESS_QUERY_URL, data=params)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("请求失败,未获取到响应")
|
||||
raise RuntimeError("WeProcess 请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
||||
raise RuntimeError(f"WeProcess 接口请求失败,状态码: {resp.status_code}")
|
||||
|
||||
try:
|
||||
return resp.json()
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||||
# HR 会话失效时接口返回登录页/非 JSON 内容
|
||||
raise HRSessionExpiredError("WeProcess 接口返回非 JSON,HR 登录态已失效")
|
||||
|
||||
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_todo_list(data):
|
||||
datas = data.get("datas", [])
|
||||
if not datas:
|
||||
return []
|
||||
def parse_we_process_list(data):
|
||||
"""解析 WeProcess 待办行为单据字典。
|
||||
|
||||
taskId/businessKey/processId/formId 行内自带,无需再经浏览器 SSO 解析;
|
||||
detail_url 拼为 HR 流程详情页(goToWorkFlow, reqType=VIEW),供审批提交/推送链接用。
|
||||
注:数据行随服务端版本在 jsonList(total 型)与 datas(count 分页型)间切换,两种都兼容。
|
||||
"""
|
||||
docs = []
|
||||
for row in datas:
|
||||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||||
title_raw = title_cell.get("value", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
|
||||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
||||
creator = creator_cell.get("value", "")
|
||||
|
||||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
||||
time_str = time_cell.get("value", "")
|
||||
|
||||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
||||
detail_url = href_cell.get("value", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:请假申请"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
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
|
||||
|
||||
docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
|
||||
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=VIEW&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):
|
||||
all_docs = []
|
||||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
||||
total = int(data.get("page", {}).get("totalSize", 0))
|
||||
logger.info("总待办[%s]条数: %d", subject, total)
|
||||
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
|
||||
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 1 页获取 %d 条", len(docs))
|
||||
|
||||
if total > page_size:
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
for p in range(2, total_pages + 1):
|
||||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
||||
|
||||
# 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
|
||||
# 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
|
||||
# 去重:以 taskId(唯一任务实例)为键,避免同一单重复审批、重复推送
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("detail_url") or doc.get("title")
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
@@ -595,14 +578,25 @@ def _load_shared_hr_cookies():
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
def _ensure_hr_cookies(force=False):
|
||||
"""确保存在 HR 登录态文件;缺失或 force=True 时抛 SystemExit 友好提示(无堆栈)。
|
||||
|
||||
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
|
||||
登录态缺失或失效时直接提醒先运行「37duHR登录」流程。
|
||||
"""
|
||||
if not force and _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 "
|
||||
"python workflows/share/hr_login.py")
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 HR 登录态文件(hr_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"HR 登录态已失效(hr_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
@@ -867,14 +861,8 @@ def _parse_leave_form(result):
|
||||
|
||||
|
||||
# ==================== 会话管理 ====================
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
|
||||
# 待办/表单/附件下载全部走 hr.37du.co 纯接口,共享 hr_cookies.json 登录态即可,
|
||||
# 无需 OA 登录、无需浏览器 SSO 解析;浏览器仅用于真实审批提交与结果弹窗。
|
||||
|
||||
def download_attachment(session, file_id, save_dir=r"D:\资料\人资\请假流程审批\附件"):
|
||||
"""
|
||||
@@ -967,129 +955,82 @@ def _download_one(session, file_id, save_dir):
|
||||
return path
|
||||
|
||||
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
|
||||
|
||||
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
|
||||
登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
|
||||
"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
return True
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
def is_session_valid(session, subject="请假"):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
def is_session_valid(session, subject=""):
|
||||
"""调 getCurUserInfo 判断 HR 会话是否有效(返回 JSON 且含 userId)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
session.post(GET_CUR_USER_INFO_URL, data={}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
# 会话有效时返回顶层含 userId 的 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text or ""
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
return False
|
||||
info = resp.json()
|
||||
return bool(isinstance(info, dict) and info.get("userId"))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
logger.info("HR 会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def build_session(subject):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||||
def build_session(subject=""):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 hr_cookies.json 填充 HR 登录态。
|
||||
|
||||
用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
|
||||
提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
|
||||
用于拉待办、取表单、下载附件等纯接口操作;登录态失效时抛友好提示(SystemExit,
|
||||
无堆栈),提醒先运行「37duHR登录」指令重新登录,而不是中途崩溃。
|
||||
"""
|
||||
_ensure_oa_cookies()
|
||||
_ensure_hr_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
session.set.headers({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session, subject):
|
||||
return session
|
||||
# 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
|
||||
_ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
_ensure_hr_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
|
||||
|
||||
def build_browser(subject):
|
||||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||||
_ensure_oa_cookies()
|
||||
def build_browser(subject=""):
|
||||
"""确有单据时才启动浏览器(真实审批点击 / 结果弹窗用),并填充共享 HR cookies。"""
|
||||
_ensure_hr_cookies()
|
||||
browser = ChromiumPage()
|
||||
cookies = _load_shared_oa_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
# ==================== 登录(共享) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 workflows/share/oa_login.py),
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login_api.py),
|
||||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||||
|
||||
|
||||
# ==================== SSO 解析 ====================
|
||||
def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc):
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
refresh_session_cookies(session, browser)
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_doc_detail(session, doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
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, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
def show_rpa_result_popup(page: ChromiumPage,
|
||||
@@ -1366,100 +1307,101 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
"""
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 登录态失效(待办/表单接口返回登录页)时本脚本不做自动重登(单文件自包含),
|
||||
# 直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duOA登录」指令
|
||||
for login_attempt in range(2):
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
# 登录态失效(待办/表单接口返回非 JSON 或 Nosession)时本脚本不做自动重登
|
||||
# (单文件自包含),直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duHR登录」指令
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"])
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
|
||||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||||
browser = build_browser(subject)
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# 排班校验依赖 HR 登录态(hr_cookies.json),提前一次性校验:
|
||||
# 失效时友好提示先运行「37duHR登录」,避免每张单据校验排班时才逐个失败
|
||||
ensure_hr_context()
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
# 与加班共用同一开关(公共审批引擎亦如此),校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if APPROVE_ENABLED:
|
||||
if result.get("decision") == "通过":
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/消息推送模块):
|
||||
# 按结果类型分多条(校验不通过/人工复核/异常/失败 各一条,含单笔明细;
|
||||
# 通过的单据不逐条推送,仅汇总计数)
|
||||
texts = build_push_summary(results, subject)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"])
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||||
# 提醒先运行「37duOA登录」指令重新登录后再跑本流程
|
||||
_ensure_oa_cookies(force=True)
|
||||
finally:
|
||||
if browser is not None:
|
||||
|
||||
# 有单据才启动浏览器:真实审批提交 / 结果弹窗(待办与表单均为纯接口)
|
||||
browser = build_browser(subject)
|
||||
|
||||
# 排班校验依赖 HR 登录态(hr_cookies.json),提前一次性校验:
|
||||
# 失效时友好提示先运行「37duHR登录」,避免每张单据校验排班时才逐个失败
|
||||
ensure_hr_context()
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
# 与加班共用同一开关(公共审批引擎亦如此),校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if APPROVE_ENABLED:
|
||||
if result.get("decision") == "通过":
|
||||
# 浏览器在审批前导航到当前单据的 HR 流程详情页(替代原 SSO 跳转)
|
||||
browser.get(doc_detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在流程中状态未变,不能仍标为通过,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
browser.quit()
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/消息推送模块):
|
||||
# 按结果类型分多条(校验不通过/人工复核/异常/失败 各一条,含单笔明细;
|
||||
# 通过的单据不逐条推送,仅汇总计数)
|
||||
texts = build_push_summary(results, subject)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return push_messages
|
||||
except HRSessionExpiredError as e:
|
||||
logger.warning("HR 登录态失效: %s", e)
|
||||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||||
# 提醒先运行「37duHR登录」指令重新登录后再跑本流程
|
||||
_ensure_hr_cookies(force=True)
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 请假校验规则 ====================
|
||||
|
||||
@@ -11,8 +11,12 @@
|
||||
pip install DrissionPage python-dotenv chinese_calendar
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
|
||||
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
待办链路(免 OA/SSO,全接口):
|
||||
WeProcess.getProcessAndData 拉待办(行内自带 taskId/businessKey/processId/formId)
|
||||
-> WfActivity.getWfActivityByTaskId 取 formId -> WorkformEngine.getBusinessDate 取表单。
|
||||
|
||||
推送(本脚本只生成待推送文本,不内联发送):
|
||||
main() 将结果消息写入影刀全局变量 messages,由「37du钉钉群机器人推送」指令发送。
|
||||
@@ -25,11 +29,9 @@ import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
@@ -47,19 +49,18 @@ except ImportError as _import_err:
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有;
|
||||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 workflows/share/oa_login.py)
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令写入(见 workflows/share/hr_login_api.py)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_TYPE = "13"
|
||||
# 流程待办查询接口(替代 OA 待办 + SSO 解析):数据行在响应 jsonList/datas(随服务端版本切换,已兼容),行内自带 taskId/businessKey/processId/formId
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
# 轻量会话校验接口:返回顶层含 userId 的 JSON,会话失效会被重定向到登录页
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
# HR 流程详情页(审批提交/推送链接用)
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
# 考勤逐日接口(按员工+日期范围返回每日班次名/班次起止/上下班打卡,data 数组)
|
||||
@@ -102,7 +103,6 @@ OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
@@ -146,10 +146,6 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
@@ -183,100 +179,89 @@ def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== OA/HR API 接口 ====================
|
||||
def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
# ==================== HR API 接口(流程待办 WeProcess) ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""调 WeProcess getProcessAndData 拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"method": "list",
|
||||
"dataType": "todo",
|
||||
"fdType": FD_TYPE,
|
||||
"fdCateId": "",
|
||||
# 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
|
||||
"q.s_raq": str(random.random()),
|
||||
"q.fdSubject": subject,
|
||||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||||
"pageno": page_no,
|
||||
"rowsize": page_size,
|
||||
"pagingtype": "default",
|
||||
"orderby": "fdCreateTime",
|
||||
"ordertype": "down",
|
||||
"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),
|
||||
}
|
||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
||||
|
||||
session.get(url)
|
||||
session.post(WE_PROCESS_QUERY_URL, data=params)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("请求失败,未获取到响应")
|
||||
raise RuntimeError("WeProcess 请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
||||
raise RuntimeError(f"WeProcess 接口请求失败,状态码: {resp.status_code}")
|
||||
|
||||
try:
|
||||
return resp.json()
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||||
# HR 会话失效时接口返回登录页/非 JSON 内容
|
||||
raise HRSessionExpiredError("WeProcess 接口返回非 JSON,HR 登录态已失效")
|
||||
|
||||
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_todo_list(data):
|
||||
datas = data.get("datas", [])
|
||||
if not datas:
|
||||
return []
|
||||
def parse_we_process_list(data):
|
||||
"""解析 WeProcess 待办行为单据字典。
|
||||
|
||||
taskId/businessKey/processId/formId 行内自带,无需再经浏览器 SSO 解析;
|
||||
detail_url 拼为 HR 流程详情页(goToWorkFlow, reqType=VIEW),供审批提交/推送链接用。
|
||||
注:数据行随服务端版本在 jsonList(total 型)与 datas(count 分页型)间切换,两种都兼容。
|
||||
"""
|
||||
docs = []
|
||||
for row in datas:
|
||||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||||
title_raw = title_cell.get("value", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
|
||||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
||||
creator = creator_cell.get("value", "")
|
||||
|
||||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
||||
time_str = time_cell.get("value", "")
|
||||
|
||||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
||||
detail_url = href_cell.get("value", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:加班申请"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
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
|
||||
|
||||
docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
|
||||
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=VIEW&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):
|
||||
all_docs = []
|
||||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
||||
total = int(data.get("page", {}).get("totalSize", 0))
|
||||
logger.info("总待办[%s]条数: %d", subject, total)
|
||||
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
|
||||
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 1 页获取 %d 条", len(docs))
|
||||
|
||||
if total > page_size:
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
for p in range(2, total_pages + 1):
|
||||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
||||
|
||||
# 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
|
||||
# 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
|
||||
# 去重:以 taskId(唯一任务实例)为键,避免同一单重复审批、重复推送
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("detail_url") or doc.get("title")
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
@@ -560,144 +545,120 @@ def parse_overtime_form(result):
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 workflows/share/oa_login.py),
|
||||
# ==================== HR 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login_api.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR 登录 cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
|
||||
def _ensure_hr_cookies(force=False):
|
||||
"""确保存在 HR 登录态文件;缺失或 force=True 时抛 SystemExit 友好提示(无堆栈)。
|
||||
|
||||
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
|
||||
登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
|
||||
登录态缺失或失效时直接提醒先运行「37duHR登录」流程。
|
||||
"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
if not force and _load_shared_hr_cookies():
|
||||
return True
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"未找到 HR 登录态文件(hr_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"HR 登录态已失效(hr_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
def is_session_valid(session, subject="加班"):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
"""调 getCurUserInfo 判断 HR 会话是否有效(返回 JSON 且顶层含 userId)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
session.post(GET_CUR_USER_INFO_URL, data={}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
# 会话有效时返回顶层含 userId 的 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text or ""
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
return False
|
||||
info = resp.json()
|
||||
return bool(isinstance(info, dict) and info.get("userId"))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
logger.info("HR 会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
def build_session(subject="加班"):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 hr_cookies.json 填充 HR 登录态。
|
||||
|
||||
|
||||
def build_session(subject):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||||
|
||||
用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
|
||||
提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
|
||||
用于查待办、拉表单、考勤打卡等纯接口操作;登录态失效时抛友好提示(SystemExit,
|
||||
无堆栈),提醒先运行「37duHR登录」指令重新登录,而不是中途崩溃。
|
||||
"""
|
||||
_ensure_oa_cookies()
|
||||
_ensure_hr_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
session.set.headers({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session, subject):
|
||||
return session
|
||||
# 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
|
||||
_ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
_ensure_hr_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
|
||||
|
||||
def build_browser(subject):
|
||||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||||
_ensure_oa_cookies()
|
||||
def build_browser(subject="加班"):
|
||||
"""确有单据时才启动浏览器(真实审批点击 / 结果弹窗用),并填充共享 HR cookies。"""
|
||||
_ensure_hr_cookies()
|
||||
browser = ChromiumPage()
|
||||
cookies = _load_shared_oa_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
# ==================== 登录(共享) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 workflows/share/oa_login.py),
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login_api.py),
|
||||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||||
|
||||
|
||||
# ==================== SSO 解析 ====================
|
||||
def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc):
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
refresh_session_cookies(session, browser)
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_doc_detail(session, doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
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, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
def show_rpa_result_popup(page: ChromiumPage,
|
||||
@@ -971,96 +932,97 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
"""
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 登录态失效(待办/表单接口返回登录页)时本脚本不做自动重登(单文件自包含),
|
||||
# 直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duOA登录」指令
|
||||
for login_attempt in range(2):
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
# 登录态失效(待办/表单接口返回非 JSON 或 Nosession)时本脚本不做自动重登
|
||||
# (单文件自包含),直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duHR登录」指令
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"])
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
|
||||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||||
browser = build_browser(subject)
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
if APPROVE_ENABLED:
|
||||
# 校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if result.get("decision") == "通过":
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/推送指令):
|
||||
# 按结果类型分多条(校验不通过/人工复核/超期/异常/失败 各一条,含单笔明细;
|
||||
# 通过的单据不逐条推送,仅汇总计数)
|
||||
texts = build_push_summary(results, subject)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"])
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||||
# 提醒先运行「37duOA登录」指令重新登录后再跑本流程
|
||||
_ensure_oa_cookies(force=True)
|
||||
finally:
|
||||
if browser is not None:
|
||||
|
||||
# 有单据才启动浏览器:真实审批提交 / 结果弹窗(待办与表单均为纯接口)
|
||||
browser = build_browser(subject)
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
# 校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if APPROVE_ENABLED:
|
||||
if result.get("decision") == "通过":
|
||||
# 浏览器在审批前导航到当前单据的 HR 流程详情页(替代原 SSO 跳转)
|
||||
browser.get(doc_detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在流程中状态未变,不能仍标为通过,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
browser.quit()
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/推送指令):
|
||||
# 按结果类型分多条(校验不通过/人工复核/超期/异常/失败 各一条,含单笔明细;
|
||||
# 通过的单据不逐条推送,仅汇总计数)
|
||||
texts = build_push_summary(results, subject)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return push_messages
|
||||
except HRSessionExpiredError as e:
|
||||
logger.warning("HR 登录态失效: %s", e)
|
||||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||||
# 提醒先运行「37duHR登录」指令重新登录后再跑本流程
|
||||
_ensure_hr_cookies(force=True)
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 加班校验规则 ====================
|
||||
@@ -1740,7 +1702,7 @@ def generate_report(results):
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
"""加班审批:查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||||
"""加班审批:查待办 -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||||
|
||||
本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages),
|
||||
由「37du钉钉群机器人推送」指令消费;仅生成群消息。
|
||||
|
||||
@@ -11,8 +11,11 @@
|
||||
pip install DrissionPage python-dotenv pymupdf
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
|
||||
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
待办链路(免 OA/SSO,全接口):WeProcess 待办列表 -> WfActivity 取 formId
|
||||
-> WorkformEngine getBusinessData 取表单;审批提交仍走浏览器(goToWorkFlow 页面)。
|
||||
|
||||
推送(本脚本只生成待推送文本,不内联发送):
|
||||
main() 将结果消息写入影刀全局变量 messages,由「37du钉钉群机器人推送」指令发送。
|
||||
@@ -28,7 +31,6 @@ import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
@@ -57,19 +59,17 @@ except ImportError as _import_err:
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有;
|
||||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 workflows/share/oa_login.py)
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令写入(见 workflows/share/hr_login_api.py)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# ---------- HR 系统(待办/表单/附件全部走 HR,不再依赖 OA) ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_TYPE = "13"
|
||||
# 流程待办查询:数据行在响应 jsonList/datas(随服务端版本切换,已兼容),行内自带 taskId/businessKey/processId/formId(免 SSO 解析)
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
# 当前登录用户信息(轻量会话校验:返回顶层含 userId 的 JSON,会话失效会被重定向到登录页)
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
# 附件清单查询接口:按 ids(逗号分隔 fileId)查附件元信息(fileName/herfUrl 等)
|
||||
@@ -94,8 +94,7 @@ OVERDUE_ACTIVITY_NAME = "完善信息(操作人)"
|
||||
OVERDUE_DAYS = 3
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
# WeProcess 每页调大至 100 作为兜底:一次请求尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
@@ -139,10 +138,6 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
@@ -176,100 +171,89 @@ def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== OA/HR API 接口 ====================
|
||||
def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
# ==================== HR API 接口(流程待办 WeProcess) ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""调 WeProcess getProcessAndData 拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"method": "list",
|
||||
"dataType": "todo",
|
||||
"fdType": FD_TYPE,
|
||||
"fdCateId": "",
|
||||
# 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
|
||||
"q.s_raq": str(random.random()),
|
||||
"q.fdSubject": subject,
|
||||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||||
"pageno": page_no,
|
||||
"rowsize": page_size,
|
||||
"pagingtype": "default",
|
||||
"orderby": "fdCreateTime",
|
||||
"ordertype": "down",
|
||||
"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),
|
||||
}
|
||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
||||
|
||||
session.get(url)
|
||||
session.post(WE_PROCESS_QUERY_URL, data=params)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("请求失败,未获取到响应")
|
||||
raise RuntimeError("WeProcess 请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
||||
raise RuntimeError(f"WeProcess 接口请求失败,状态码: {resp.status_code}")
|
||||
|
||||
try:
|
||||
return resp.json()
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||||
# HR 会话失效时接口返回登录页/非 JSON 内容
|
||||
raise HRSessionExpiredError("WeProcess 接口返回非 JSON,HR 登录态已失效")
|
||||
|
||||
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_todo_list(data):
|
||||
datas = data.get("datas", [])
|
||||
if not datas:
|
||||
return []
|
||||
def parse_we_process_list(data):
|
||||
"""解析 WeProcess 待办行为单据字典。
|
||||
|
||||
taskId/businessKey/processId/formId 行内自带,无需再经浏览器 SSO 解析;
|
||||
detail_url 拼为 HR 流程详情页(goToWorkFlow, reqType=VIEW),供审批提交/推送链接用。
|
||||
注:数据行随服务端版本在 jsonList(total 型)与 datas(count 分页型)间切换,两种都兼容。
|
||||
"""
|
||||
docs = []
|
||||
for row in datas:
|
||||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||||
title_raw = title_cell.get("value", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
|
||||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
||||
creator = creator_cell.get("value", "")
|
||||
|
||||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
||||
time_str = time_cell.get("value", "")
|
||||
|
||||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
||||
detail_url = href_cell.get("value", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:改签离职电子签流程"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
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
|
||||
|
||||
docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
|
||||
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=VIEW&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):
|
||||
all_docs = []
|
||||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
||||
total = int(data.get("page", {}).get("totalSize", 0))
|
||||
logger.info("总待办[%s]条数: %d", subject, total)
|
||||
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
|
||||
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 1 页获取 %d 条", len(docs))
|
||||
|
||||
if total > page_size:
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
for p in range(2, total_pages + 1):
|
||||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
||||
|
||||
# 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
|
||||
# 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
|
||||
# 去重:以 taskId(唯一任务实例)为键,避免同一单重复审批、重复推送
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("detail_url") or doc.get("title")
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
@@ -605,142 +589,113 @@ def parse_resign_e_sign_form(result):
|
||||
}
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 workflows/share/oa_login.py),
|
||||
# ==================== HR 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login_api.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR 登录 cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
|
||||
def _ensure_hr_cookies(force=False):
|
||||
"""确保存在 HR 登录态文件;缺失或 force=True 时抛 SystemExit 友好提示(无堆栈)。
|
||||
|
||||
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
|
||||
登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
|
||||
登录态缺失或失效时直接提醒先运行「37duHR登录」流程。
|
||||
"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
if not force and _load_shared_hr_cookies():
|
||||
return True
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"未找到 HR 登录态文件(hr_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/oa_login.py\n"
|
||||
"HR 登录态已失效(hr_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login_api.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
def is_session_valid(session, subject="改签离职电子签流程"):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
"""调 getCurUserInfo 判断 HR 会话是否有效(返回 JSON 且含 userId)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
session.post(GET_CUR_USER_INFO_URL, data={}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
# 会话有效时返回顶层含 userId 的 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text or ""
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
return False
|
||||
info = resp.json()
|
||||
return bool(isinstance(info, dict) and info.get("userId"))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
logger.info("HR 会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
def build_session(subject="改签离职电子签流程"):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 hr_cookies.json 填充 HR 登录态。
|
||||
|
||||
|
||||
def build_session(subject):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||||
|
||||
用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
|
||||
提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
|
||||
用于拉待办、取表单等纯接口操作;登录态失效时抛友好提示(SystemExit,
|
||||
无堆栈),提醒先运行「37duHR登录」指令重新登录,而不是中途崩溃。
|
||||
"""
|
||||
_ensure_oa_cookies()
|
||||
_ensure_hr_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
session.set.headers({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session, subject):
|
||||
return session
|
||||
# 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
|
||||
_ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
_ensure_hr_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||||
|
||||
|
||||
def build_browser(subject):
|
||||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||||
_ensure_oa_cookies()
|
||||
def build_browser(subject="改签离职电子签流程"):
|
||||
"""确有单据时才启动浏览器(真实审批点击 / 结果弹窗用),并填充共享 HR cookies。"""
|
||||
_ensure_hr_cookies()
|
||||
browser = ChromiumPage()
|
||||
cookies = _load_shared_oa_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
# ==================== 登录(共享) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 workflows/share/oa_login.py),
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login_api.py),
|
||||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||||
|
||||
|
||||
# ==================== SSO 解析 ====================
|
||||
def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
# 重定向 URL 同时携带流程实例 processId(WeTask.query 超期检查用);
|
||||
# WfActivity 接口返回不含 processId,processId 只能从这里拿,缺失不阻断主流程
|
||||
process_id = params.get("processId", [None])[0] or ""
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s, processId=%s", task_id, business_key, process_id or "无")
|
||||
return {"taskId": task_id, "businessKey": business_key, "processId": process_id}
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc):
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
process_id = sso_params.get("processId", "")
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s, processId=%s",
|
||||
task_id, business_key, process_id or "无")
|
||||
|
||||
refresh_session_cookies(session, browser)
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _fetch_doc_detail(session, doc):
|
||||
"""纯接口取单据详情:taskId/businessKey/processId 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
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)
|
||||
@@ -750,8 +705,7 @@ def _fetch_doc_detail(browser, session, doc):
|
||||
# 需再调签署状态查询接口把真实状态写回,否则校验结果永远是"未完成"
|
||||
enrich_form_sign_status(form_data, session)
|
||||
|
||||
return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id,
|
||||
"processId": process_id, "formData": form_data}
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
def show_rpa_result_popup(page: ChromiumPage,
|
||||
@@ -1090,15 +1044,14 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
|
||||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||||
# 有单据才启动浏览器:真实审批提交 / 结果弹窗
|
||||
browser = build_browser(subject)
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
results = []
|
||||
overdue_list = [] # 超期名单:完善信息(操作人)完成超 3 天仍未走完的流程
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
doc_detail = _fetch_doc_detail(session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
|
||||
# 超期检查(独立于审批校验,失败不影响主流程):
|
||||
@@ -1125,6 +1078,9 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
if APPROVE_ENABLED:
|
||||
# 未完成(电子签未全部完成)不自动处理("不管"),仅对"通过"提交真实审批
|
||||
if result.get("decision") == "通过":
|
||||
# 浏览器在审批前导航到当前单据的 HR 流程详情页(替代原 SSO 跳转)
|
||||
browser.get(doc_detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
@@ -1195,11 +1151,11 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return push_messages
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
except HRSessionExpiredError as e:
|
||||
logger.warning("HR 登录态失效: %s", e)
|
||||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||||
# 提醒先运行「37duOA登录」指令重新登录后再跑本流程
|
||||
_ensure_oa_cookies(force=True)
|
||||
# 提醒先运行「37duHR登录」指令重新登录后再跑本流程
|
||||
_ensure_hr_cookies(force=True)
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
@@ -1773,7 +1729,7 @@ def generate_report(results):
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
"""改签离职电子签流程审核:查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||||
"""改签离职电子签流程审核:查待办 -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||||
|
||||
本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages),
|
||||
由「37du钉钉群机器人推送」指令消费;仅生成群消息。
|
||||
|
||||
@@ -107,6 +107,8 @@ CONFIRM_URL = (HR_BASE_URL + "/RedseaPlatform/hrmodulesqlid/excuteSql/"
|
||||
# ---------- 查询接口 ----------
|
||||
QUERY_TRIAL_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID_TRIAL}/queryRealTimeData.mc"
|
||||
QUERY_PENDING_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID_PENDING}/queryRealTimeData.mc"
|
||||
QUERY_WAIT_EFFECT_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID_WAIT_EFFECT}/queryRealTimeData.mc"
|
||||
QUERY_EFFECTED_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID_EFFECTED}/queryRealTimeData.mc"
|
||||
|
||||
# ---------- 规则1-① 合同调动解除(电子签):合同台账-生效中合同(roster/按钮 getRosterList 逆向) ----------
|
||||
ROSTER_ID_ACTIVE_CONTRACT = "614ffe05-b4f1-11ea-b588-14187743d052" # 合同台账-生效中合同 Tab
|
||||
@@ -119,6 +121,10 @@ TRANSFER_CHECK_URL = (HR_BASE_URL + "/RedseaPlatform/redmagicapi/"
|
||||
# 发起《(改签)离职电子签流程》(按钮 expression 固定 workflowId,state=1 成功)
|
||||
TRANSFER_START_URL = (HR_BASE_URL + "/RedseaPlatform/wfProcessScheduled/"
|
||||
"0c517acb-2822-4963-ba57-1828cd2316a6/startWorkFlowScheduled.mc")
|
||||
# 离职电子签详情页(goToWorkFlow)的表单 ID:流程定义固定值,实例链接中 businessKey/processId/taskId 动态生成
|
||||
WORKFORM_FORM_ID = "5b904505-c319-4b29-8b0b-d2c887b2469a"
|
||||
# 流程实例/待办查询接口(流程引擎类,需最新登录态 cookies;title 为模糊匹配,CREATE_TIME 倒序)
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
|
||||
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
|
||||
CURRENT_USER_ID = "178b0efa-8a65-11f1-a7d9-000c296f9469"
|
||||
@@ -164,6 +170,10 @@ AITABLE_TARGET_OPINION = "离职后再入职" # 人员处理意见 目标
|
||||
AITABLE_DONE_FIELD = "人资是否处理" # 回填字段:处理标记(singleSelect)
|
||||
AITABLE_DONE_VALUE = "是"
|
||||
AITABLE_PUSH_DATE_FIELD = "离职推送时间" # 回填字段:需求「离职推送日期」对应表内实际字段名(date)
|
||||
# 规则:到期能否考核通过 = 能 → 无需离职+入职处理,人资是否处理 直接回填「否」(防遗漏)
|
||||
AITABLE_PASS_FIELD = "到期能否考核通过"
|
||||
AITABLE_PASS_VALUE = "能"
|
||||
AITABLE_NO_DONE_VALUE = "否"
|
||||
|
||||
# 钉钉 AI表格接口(notable OpenAPI,头 x-acs-dingtalk-access-token;operatorId=操作人 unionId)
|
||||
AITABLE_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
|
||||
@@ -395,22 +405,110 @@ def check_transfer_allowed(session, contract_id):
|
||||
return False, meg
|
||||
|
||||
|
||||
def _extract_flow_params(d):
|
||||
"""从发起接口响应中宽松提取流程实例参数,拼 goToWorkFlow 详情链接。
|
||||
|
||||
前端按钮发起成功后即跳转到该详情页(供发起人进入页面完善信息)。响应字段名
|
||||
不同版本可能有差异,这里做多键名兜底提取;拿不到完整参数返回 None(不阻断主流程)。
|
||||
|
||||
Returns:
|
||||
dict {url, business_key, process_id, task_id, form_id} 或 None
|
||||
"""
|
||||
data = d.get("data")
|
||||
if isinstance(data, str):
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except Exception:
|
||||
data = {}
|
||||
if not isinstance(data, dict):
|
||||
data = d
|
||||
result_nested = data.get("result") if isinstance(data.get("result"), dict) else {}
|
||||
|
||||
def _first(*keys):
|
||||
for k in keys:
|
||||
for src in (data, result_nested):
|
||||
v = src.get(k)
|
||||
if v not in (None, ""):
|
||||
return str(v)
|
||||
return ""
|
||||
|
||||
business_key = _first("businessKey", "business_key", "processBusinessKey",
|
||||
"bpmBusinessKey", "businessId", "fkId")
|
||||
process_id = _first("processId", "process_id", "processInstanceId", "instanceId", "piId")
|
||||
task_id = _first("taskId", "task_id", "taskID", "currentTaskId")
|
||||
if not (business_key and process_id and task_id):
|
||||
return None
|
||||
url = (f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={WORKFORM_FORM_ID}&businessKey={business_key}"
|
||||
f"&processId={process_id}&taskId={task_id}&reqType=VIEW&headType=&systemId=")
|
||||
return {"url": url, "business_key": business_key, "process_id": process_id,
|
||||
"task_id": task_id, "form_id": WORKFORM_FORM_ID}
|
||||
|
||||
|
||||
def initiate_transfer_release(session, contract_id):
|
||||
"""发起《(改签)离职电子签流程》(EHR「调动解除(电子签)」按钮逆向实现)。
|
||||
|
||||
流程参数(新签合同=否、实际离职日期=原始试用期到期日期)由工作流模板固化,
|
||||
接口仅传 contract_id + operatorId(与前端按钮行为一致)。
|
||||
接口仅传 contract_id + operatorId(与前端按钮行为一致)。发起成功后从响应中
|
||||
提取流程实例参数并拼出 goToWorkFlow 详情链接(供进入页面完善信息)。
|
||||
|
||||
Returns:
|
||||
(ok: bool, msg: str):state=1 发起成功
|
||||
(ok: bool, msg: str, flow: dict|None):state=1 发起成功;
|
||||
flow 含 url/business_key/process_id/task_id/form_id;响应无实例参数时为 None
|
||||
"""
|
||||
resp = _request_retry("POST", TRANSFER_START_URL, session,
|
||||
data={"contract_id": contract_id, "operatorId": CURRENT_USER_ID},
|
||||
headers=CSRF_HEADERS)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) == "1":
|
||||
return True, "改签-离职电子签流程发起成功"
|
||||
return False, f"改签-离职电子签流程发起失败:{d.get('meg') or d}"
|
||||
if str(d.get("state")) != "1":
|
||||
return False, f"改签-离职电子签流程发起失败:{d.get('meg') or d}", None
|
||||
flow = _extract_flow_params(d)
|
||||
if flow:
|
||||
return True, f"改签-离职电子签流程发起成功:{flow['url']}", flow
|
||||
# 响应未解析到流程实例参数:打印完整响应便于排查字段名,仍视为发起成功(不阻断后续环节)
|
||||
logger.warning("改签-离职电子签流程发起成功,但响应未解析到流程实例参数(供人工排查):%s",
|
||||
json.dumps(d, ensure_ascii=False)[:500])
|
||||
return True, "改签-离职电子签流程发起成功(响应未含流程实例参数,详情链接需人工补录)", None
|
||||
|
||||
|
||||
def query_transfer_workflow(session, business_key=None, title="改签离职电子签"):
|
||||
"""通过流程待办接口 WeProcess.mc 查询「改签离职电子签」流程实例,返回最新一条详情链接。
|
||||
|
||||
该接口与 WorkformEngine 同属流程引擎接口,需共享登录态 cookies 为最新(过期返回 Nosession)。
|
||||
优先按 businessKey 精确匹配(发起接口响应带出时最准确);否则按 title 模糊匹配
|
||||
(接口实测为模糊匹配)取 CREATE_TIME 最新一条。
|
||||
返回的 businessKey/processId/taskId/formId 可拼 goToWorkFlow 详情链接(供进入页面完善信息)。
|
||||
|
||||
Returns:
|
||||
dict {url, business_key, process_id, task_id, form_id, title, create_user, create_time} 或 None
|
||||
"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": title,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": "0", "pageNo": "1", "pageSize": "15",
|
||||
}
|
||||
resp = _request_retry("POST", WE_PROCESS_QUERY_URL, session, data=params)
|
||||
# WeProcess 数据行随服务端版本在 jsonList(total 型)与 datas(count 分页型)间切换,两种都兼容
|
||||
datas = resp.json().get("jsonList") or resp.json().get("datas") or []
|
||||
if not datas:
|
||||
return None
|
||||
rows = datas
|
||||
if business_key:
|
||||
matched = [r for r in datas if str(r.get("businessKey")) == str(business_key)]
|
||||
if matched:
|
||||
rows = matched
|
||||
rec = rows[0]
|
||||
bk, pid, tid = (rec.get("businessKey") or ""), (rec.get("processId") or ""), (rec.get("taskId") or "")
|
||||
fid = rec.get("formId") or WORKFORM_FORM_ID
|
||||
if not (bk and pid and tid):
|
||||
return None
|
||||
url = (f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={fid}&businessKey={bk}&processId={pid}&taskId={tid}&reqType=VIEW&headType=&systemId=")
|
||||
return {"url": url, "business_key": bk, "process_id": pid, "task_id": tid, "form_id": fid,
|
||||
"title": rec.get("title") or "", "create_user": rec.get("createUserName") or "",
|
||||
"create_time": rec.get("createTime") or ""}
|
||||
|
||||
|
||||
# ==================== 1) 查询「试用期人员」定位员工 ====================
|
||||
@@ -499,6 +597,58 @@ def confirm_pending(session, management_id):
|
||||
return resp.json()
|
||||
|
||||
|
||||
# ==================== 4.5) 交叉验证:流程可能已被他人操作到任意环节 ====================
|
||||
def check_processed_stage(session, base_code):
|
||||
"""交叉验证该员工在「调动解除+变更试用期」流程中已进行到哪一步。
|
||||
|
||||
线上流程可能被他人操作到任意环节(AI表格回填并不随之发生),为避免重复发起
|
||||
调动解除(电子签)造成重复离职流程,处理前逐一核查三个 Tab:
|
||||
done - 「变更/转正已生效」:变更已提交并确认生效(record 含 new_period_end_date/操作人/时间)
|
||||
pending - 「变更/转正待确认」:变更已提交、待确认(半途,需人工核查确认环节)
|
||||
effect - 「变更/转正待生效」:变更已确认、待生效(半途,需人工核查生效情况)
|
||||
None - 均无记录:未开始任何变更环节,可正常走全链路
|
||||
|
||||
Returns:
|
||||
(stage, record):stage ∈ {'done','pending','effect',None},record 为命中记录 dict 或 None
|
||||
"""
|
||||
probes = [
|
||||
("done", ROSTER_ID_EFFECTED, QUERY_EFFECTED_URL, "assemble-hr_staff_probation"),
|
||||
("pending", ROSTER_ID_PENDING, QUERY_PENDING_URL, "assemble-hr_staff_probation"),
|
||||
("effect", ROSTER_ID_WAIT_EFFECT, QUERY_WAIT_EFFECT_URL, "assemble-hr_staff_probation"),
|
||||
]
|
||||
for stage, roster_id, url, table_id in probes:
|
||||
params = _build_query_params(
|
||||
roster_id, table_id,
|
||||
_encode_common_query([_build_like_condition("hr_staff_base.base_code", base_code)]),
|
||||
menu_name="试用期台账")
|
||||
params.update(_get_date_params())
|
||||
resp = _request_retry("POST", url, session, data=params)
|
||||
for row in resp.json().get("datas") or []:
|
||||
if str(row.get("hr_staff_base.base_code")) == str(base_code):
|
||||
return stage, row
|
||||
return None, None
|
||||
|
||||
|
||||
def _build_processed_msg(stage, rec, base_code, target_end_date):
|
||||
"""构造「已被处理,需人工核查」的跳过提示信息。"""
|
||||
def _v(field):
|
||||
return rec.get(field) if rec else None
|
||||
if stage == "done":
|
||||
return (
|
||||
f"交叉验证:该员工在「变更/转正已生效」中存在已生效变更记录(新试用期结束日期="
|
||||
f"{_v('hr_staff_probation.new_period_end_date')},操作人={_v('hr_staff_probation.operator_name')},"
|
||||
f"操作时间={_v('hr_staff_probation.operate_time')}),已超过AI表格原始到期日顺延目标"
|
||||
f"({target_end_date}),判定已被处理。跳过发起调动解除,请人工核查:"
|
||||
f"调动解除(电子签)是否已发起、AI表格是否需手动回填。")
|
||||
if stage == "pending":
|
||||
return ("交叉验证:该员工在「变更/转正待确认」中存在待确认记录(management_id="
|
||||
f"{_v('hr_staff_probation.management_id')}),变更已提交但未确认。"
|
||||
"跳过发起调动解除,请人工核查确认环节。")
|
||||
return ("交叉验证:该员工在「变更/转正待生效」中存在记录(management_id="
|
||||
f"{_v('hr_staff_probation.management_id')}),变更已确认待生效。"
|
||||
"跳过发起调动解除,请人工核查生效情况。")
|
||||
|
||||
|
||||
# ==================== 钉钉 AI表格:名单读取 + 处理后回写 ====================
|
||||
_aitable_tok = {"at": "", "exp": 0.0}
|
||||
|
||||
@@ -594,13 +744,11 @@ def _defer_end_date(origin_val, months=DEFER_MONTHS):
|
||||
return _defer_months(d, months).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def fetch_aitable_targets():
|
||||
"""从钉钉 AI表格读取「需要变更试用期」名单(分页全量)。
|
||||
|
||||
筛选规则:人员处理意见 = 离职后再入职 且 人资是否处理 != 是(否/空视为待处理)。
|
||||
def fetch_aitable_records():
|
||||
"""分页全量读取钉钉 AI表格原始记录(含所有字段),供筛选/兜底回填复用。
|
||||
|
||||
Returns:
|
||||
list[dict]:{record_id, base_code, staff_name, ...};失败抛 RuntimeError
|
||||
list[dict]:原始 records 列表;失败抛 RuntimeError
|
||||
"""
|
||||
records, token = [], ""
|
||||
for _ in range(200): # 兜底上限(200 页 * 100 条)
|
||||
@@ -613,7 +761,21 @@ def fetch_aitable_targets():
|
||||
token = d["nextToken"]
|
||||
else:
|
||||
break
|
||||
return records
|
||||
|
||||
|
||||
def fetch_aitable_targets(records=None):
|
||||
"""从钉钉 AI表格读取「需要变更试用期」名单。
|
||||
|
||||
筛选规则:人员处理意见 = 离职后再入职 且 人资是否处理 != 是(否/空视为待处理)。
|
||||
|
||||
Args:
|
||||
records: 原始记录列表(可传 fetch_aitable_records() 结果复用分页,避免重复拉取)
|
||||
|
||||
Returns:
|
||||
list[dict]:{record_id, base_code, staff_name, ...};失败抛 RuntimeError
|
||||
"""
|
||||
records = records if records is not None else fetch_aitable_records()
|
||||
targets = []
|
||||
for rec in records:
|
||||
fields = rec.get("fields") or {}
|
||||
@@ -639,6 +801,35 @@ def fetch_aitable_targets():
|
||||
return targets
|
||||
|
||||
|
||||
def mark_aitable_no(record_ids):
|
||||
"""把 AI表格对应行「人资是否处理」回填为「否」(到期能否考核通过=能,无需离职+入职处理)。
|
||||
|
||||
幂等分批;仅由 main() 在读取名单前调用,作为防遗漏兜底。
|
||||
|
||||
Returns:
|
||||
(成功数, 失败数)
|
||||
"""
|
||||
record_ids = [r for r in record_ids if r]
|
||||
if not record_ids:
|
||||
return 0, 0
|
||||
ok, fail = 0, 0
|
||||
for i in range(0, len(record_ids), AITABLE_WRITE_BATCH):
|
||||
batch = record_ids[i:i + AITABLE_WRITE_BATCH]
|
||||
try:
|
||||
d = _aitable_request("PUT", AITABLE_UPDATE_URL,
|
||||
params={"operatorId": AITABLE_OPERATOR_UNIONID},
|
||||
json_body={"records": [
|
||||
{"id": rid, "fields": {AITABLE_DONE_FIELD: AITABLE_NO_DONE_VALUE}}
|
||||
for rid in batch]})
|
||||
value = d.get("value") or []
|
||||
ok += len(value)
|
||||
except Exception as e:
|
||||
logger.error("AI表格回填「否」(无需处理)批次失败(%s):%s", batch, e)
|
||||
fail += len(batch)
|
||||
logger.info("AI表格回填「否」(无需处理)完成:成功 %d 条,失败 %d 条", ok, fail)
|
||||
return ok, fail
|
||||
|
||||
|
||||
def mark_aitable_done(record_ids):
|
||||
"""把 AI表格对应行回填处理结果(分批,幂等):
|
||||
人资是否处理 = 是
|
||||
@@ -684,10 +875,12 @@ def process_one(session, task):
|
||||
|
||||
Returns:
|
||||
dict {base_code, staff_name, correction_type, new_period_date, new_period_end_date,
|
||||
stages: {transfer/change/confirm}, all_done, status: 成功/失败, message}
|
||||
stages: {transfer/change/confirm}, all_done, status: 成功/失败/跳过, message}
|
||||
stages.transfer=调动解除(电子签);change=试用期变更;confirm=变更确认。
|
||||
按需求回填规则:任一环节失败即返回,不继续后续环节,all_done=False 不回填 AI表格。
|
||||
重试幂等:调动解除防重校验命中「已存在审批中流程」视为该环节此前已完成,继续执行。
|
||||
交叉验证:处理前核查三个变更 Tab,命中(已被他人操作到任意环节)则 status=跳过,
|
||||
不发起点调动解除,仅提示人工核查,all_done=False 不回填 AI表格。
|
||||
"""
|
||||
base_code = str(task["base_code"]).strip()
|
||||
new_period_date = task.get("new_period_date") or FIXED_NEW_PERIOD_MONTHS
|
||||
@@ -706,6 +899,7 @@ def process_one(session, task):
|
||||
"new_period_date": new_period_date,
|
||||
"new_period_end_date": new_period_end_date,
|
||||
"stages": {"transfer": False, "change": False, "confirm": False},
|
||||
"workflow_url": "", # 调动解除(电子签)发起后生成的 goToWorkFlow 详情链接(供完善信息)
|
||||
"all_done": False,
|
||||
"status": "失败",
|
||||
"message": "",
|
||||
@@ -716,6 +910,14 @@ def process_one(session, task):
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
try:
|
||||
# 0) 交叉验证:流程可能已被他人操作到任意环节,命中则跳过发起调动解除,提示人工核查
|
||||
stage, proc_rec = check_processed_stage(session, base_code)
|
||||
if stage is not None:
|
||||
result["status"] = "跳过"
|
||||
result["message"] = _build_processed_msg(stage, proc_rec, base_code, new_period_end_date)
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
# 1) 合同调动解除(电子签):查生效合同 -> 防重校验 -> 发起《(改签)离职电子签流程》
|
||||
logger.info("【%s】1/5 查询【生效中合同】并发起调动解除(电子签)……", base_code)
|
||||
contract = query_active_contract(session, base_code)
|
||||
@@ -739,13 +941,25 @@ def process_one(session, task):
|
||||
logger.info("【%s】调动解除(电子签)此前已发起(%s),本环节视为已完成",
|
||||
base_code, chk_msg)
|
||||
else:
|
||||
ok, msg = initiate_transfer_release(session, contract["contract_id"])
|
||||
ok, msg, flow = initiate_transfer_release(session, contract["contract_id"])
|
||||
if not ok:
|
||||
result["message"] = msg
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["transfer"] = True
|
||||
# 详情链接:优先发起接口响应解析;缺失则通过流程待办接口(WeProcess)反查兜底
|
||||
result["workflow_url"] = (flow or {}).get("url", "")
|
||||
if not result["workflow_url"]:
|
||||
wf = query_transfer_workflow(session, business_key=(flow or {}).get("business_key"))
|
||||
if wf:
|
||||
result["workflow_url"] = wf["url"]
|
||||
logger.info("【%s】已通过流程待办接口反查到离职电子签详情链接", base_code)
|
||||
else:
|
||||
logger.warning("【%s】未能在流程待办接口反查到详情链接"
|
||||
"(需最新登录态 cookies),完善信息需人工进入页面", base_code)
|
||||
logger.info("【%s】✅ %s", base_code, msg)
|
||||
# TODO(待逆向):进入 goToWorkFlow 页面「完善信息」的提交接口未实现——
|
||||
# 需有真实「改签离职电子签」流程实例后抓包确认提交接口与字段,再以接口方式完成完善信息。
|
||||
|
||||
# 2) 定位员工(试用期人员)
|
||||
logger.info("【%s】2/5 查询试用期人员……", base_code)
|
||||
@@ -913,14 +1127,19 @@ def _set_glv(name, value):
|
||||
|
||||
|
||||
def _build_messages(results):
|
||||
"""按结果类型构造钉钉群推送消息列表(成功/失败各一条汇总)。"""
|
||||
"""按结果类型构造钉钉群推送消息列表(成功/跳过/失败各一条汇总)。"""
|
||||
ok = [r for r in results if r["status"] == "成功"]
|
||||
fail = [r for r in results if r["status"] != "成功"]
|
||||
skip = [r for r in results if r["status"] == "跳过"]
|
||||
fail = [r for r in results if r["status"] not in ("成功", "跳过")]
|
||||
messages = []
|
||||
if ok:
|
||||
lines = [f"✅ 试用期变更成功 {len(ok)} 人:"]
|
||||
lines += [f" - {r['staff_name']}({r['base_code']}):{r['message']}" for r in ok]
|
||||
messages.append("\n".join(lines))
|
||||
if skip:
|
||||
lines = [f"⚠️ 试用期变更跳过 {len(skip)} 人(检测到已被处理,需人工核查):"]
|
||||
lines += [f" - {r['base_code']}:{r['message']}" for r in skip]
|
||||
messages.append("\n".join(lines))
|
||||
if fail:
|
||||
lines = [f"❌ 试用期变更失败 {len(fail)} 人:"]
|
||||
lines += [f" - {r['base_code']}:{r['message']}" for r in fail]
|
||||
@@ -971,8 +1190,21 @@ def main(tasks=None, excel_path=None, output_path=None, use_aitable=True, write_
|
||||
ret = {"results": results,
|
||||
"message": f"共 {len(results)} 条,成功 {sum(1 for r in results if r['status']=='成功')} 条"}
|
||||
elif use_aitable:
|
||||
# AI表格名单兜底:读取 -> 逐条变更(新到期日=原始到期日顺延1个月,自动计算)-> 环节全成才回填
|
||||
targets = fetch_aitable_targets()
|
||||
# AI表格名单兜底:读取 -> 先对「到期能否考核通过=能」自动回填否 -> 再对
|
||||
# 「离职后再入职」名单逐条变更(新到期日=原始到期日顺延1个月,自动计算)-> 环节全成才回填
|
||||
session = _build_session()
|
||||
records = fetch_aitable_records()
|
||||
# 规则:到期能否考核通过=能 → 无需离职+入职处理,人资是否处理直接回填「否」(防遗漏)
|
||||
no_done_ids = []
|
||||
for rec in records:
|
||||
f = rec.get("fields") or {}
|
||||
if (_aitable_opt_name(f.get(AITABLE_PASS_FIELD)) == AITABLE_PASS_VALUE
|
||||
and _aitable_opt_name(f.get(AITABLE_DONE_FIELD)) != AITABLE_NO_DONE_VALUE):
|
||||
no_done_ids.append(rec.get("id"))
|
||||
if no_done_ids:
|
||||
nok, nfail = mark_aitable_no(no_done_ids)
|
||||
logger.info("到期能否考核通过=能 自动回填「否」:成功 %d 条,失败 %d 条", nok, nfail)
|
||||
targets = fetch_aitable_targets(records=records)
|
||||
if not targets:
|
||||
ret = {"results": [], "success": True,
|
||||
"message": "AI表格暂无待处理名单(人员处理意见=离职后再入职 且 人资是否处理≠是)"}
|
||||
@@ -981,7 +1213,6 @@ def main(tasks=None, excel_path=None, output_path=None, use_aitable=True, write_
|
||||
"output_path": output_path, "results": []}
|
||||
logger.info("AI表格待处理名单 %d 条,固定参数:变更类型=%s 新试用期=%s 月 结束=原始到期日顺延%d个月",
|
||||
len(targets), FIXED_CORRECTION_TYPE, FIXED_NEW_PERIOD_MONTHS, DEFER_MONTHS)
|
||||
session = _build_session()
|
||||
results = []
|
||||
for t in targets:
|
||||
task = {
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针(只读):验证「HR WeProcess.mc?method=getProcessAndData」能否替代 OA 待办接口 + SSO 解析。
|
||||
背景:XQ0003 请假 / XQ0004 加班 / XQ0020 改签离职电子签流程 三个审核流程目前链路为
|
||||
OA 待办(sysNotifyMainIndex.do, fdType=13) -> 详情链接 SSO 跳转解析(taskId/businessKey)
|
||||
-> WfActivity 取 formId -> WorkformEngine 取表单(SSO 后落地均在 hr.37du.co)。
|
||||
本探针验证:
|
||||
1) 仅用 hr_cookies.json 调 WeProcess 按标题关键字拉待办(不依赖 OA 登录态);
|
||||
2) 与 OA 待办接口同关键字结果做数量/标题一致性比对(验证 OA 与 HR 数据一致);
|
||||
3) 免 SSO 链路:WeProcess 返回的 taskId -> WfActivity 取 formId -> WorkformEngine
|
||||
getBusinessDate 取表单数据(全程纯 HR 接口),证明无需浏览器 SSO 解析。
|
||||
注意事项(实测结论):
|
||||
- WeProcess 响应结构为 {state, meg, total, isRecord, result, jsonList},数据在 jsonList;
|
||||
- 会话过期时 state=Nosession、meg=会话过期,需先运行 hr_login_api.py 刷新登录态。
|
||||
只读探针:不发审批、不写任何业务文件,仅控制台输出。
|
||||
运行:.venv\\Scripts\\python.exe workflows/share/_probe_we_process_todo.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA')
|
||||
or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
OA_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
OA_BASE_URL = "https://oa.37du.co"
|
||||
WE_PROCESS_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
OA_TODO_URL = f"{OA_BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 三个审核流程的待办主题关键字(与各自 main() 中 run_flow(subject=...) 完全一致)
|
||||
SUBJECTS = ["请假", "加班", "改签离职电子签流程"]
|
||||
|
||||
PAGE_SIZE = 100
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def _mtime(path):
|
||||
try:
|
||||
return datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except OSError:
|
||||
return "不存在"
|
||||
|
||||
|
||||
def load_cookies(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def build_session(cookies, domain_keyword=None):
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": USER_AGENT,
|
||||
"X-Requested-With": "XMLHttpRequest"})
|
||||
for c in cookies or []:
|
||||
domain = c.get("domain") or ""
|
||||
if domain_keyword and domain_keyword not in domain:
|
||||
continue
|
||||
if domain:
|
||||
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
|
||||
else:
|
||||
session.cookies.set(c["name"], c["value"])
|
||||
return session
|
||||
|
||||
|
||||
def _is_login_page(text):
|
||||
return bool(text) and ("login.jsp" in text or "j_username" in text)
|
||||
|
||||
|
||||
def _is_json(text):
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def _row(row, *names):
|
||||
"""行字段多候选取值(兼容 jsonList 驼峰/下划线字段名)。"""
|
||||
for n in names:
|
||||
v = row.get(n)
|
||||
if v not in (None, ""):
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== OA 侧:待办列表(现状链路) ====================
|
||||
def oa_todo_page(session, subject, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"method": "list", "dataType": "todo", "fdType": "13", "fdCateId": "",
|
||||
"q.s_raq": str(random.random()), "q.fdSubject": subject,
|
||||
"pageno": page_no, "rowsize": page_size, "pagingtype": "default",
|
||||
"orderby": "fdCreateTime", "ordertype": "down",
|
||||
}
|
||||
resp = session.get(f"{OA_TODO_URL}?{urlencode(params)}", timeout=20)
|
||||
text = resp.text or ""
|
||||
if _is_login_page(text):
|
||||
raise RuntimeError("OA 登录态失效(返回登录页)")
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"OA 待办接口返回非 JSON(前 80 字符):{text[:80]}")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def oa_parse_rows(data):
|
||||
"""复刻 XQ0003 parse_todo_list:解析标题/发起人/时间/详情链接,跳过协作类待办。"""
|
||||
docs, skipped = [], 0
|
||||
for row in data.get("datas") or []:
|
||||
cells = {c.get("col"): (c.get("value") or "") for c in row if isinstance(c, dict)}
|
||||
title_raw = cells.get("todo.subject4View", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
detail_url = cells.get("tr_href", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = OA_BASE_URL + detail_url
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
skipped += 1
|
||||
continue
|
||||
docs.append({"title": title, "creator": cells.get("docCreatorName", ""),
|
||||
"time": cells.get("fdCreateTime", ""), "detail_url": detail_url})
|
||||
return docs, skipped
|
||||
|
||||
|
||||
def oa_fetch_all(session, subject):
|
||||
data = oa_todo_page(session, subject, page_no=1)
|
||||
total = int((data.get("page") or {}).get("totalSize") or 0)
|
||||
docs, skipped = oa_parse_rows(data)
|
||||
pages = (total + PAGE_SIZE - 1) // PAGE_SIZE if total else 1
|
||||
for p in range(2, min(pages, 20) + 1):
|
||||
data = oa_todo_page(session, subject, page_no=p)
|
||||
more, skip = oa_parse_rows(data)
|
||||
docs.extend(more)
|
||||
skipped += skip
|
||||
# 按详情链接去重(与现有 get_documents 口径一致)
|
||||
seen, unique = set(), []
|
||||
for d in docs:
|
||||
key = d.get("detail_url") or d.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique.append(d)
|
||||
return unique, total, skipped
|
||||
|
||||
|
||||
# ==================== HR 侧:WeProcess 流程待办(候选新链路) ====================
|
||||
def hr_we_process_page(session, title, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": title,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": "0", "pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
resp = session.post(WE_PROCESS_URL, data=params, timeout=20)
|
||||
text = resp.text or ""
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"WeProcess 返回非 JSON(HR 登录态可能失效,前 80 字符):{text[:80]}")
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
raise RuntimeError(f"WeProcess 返回失败 state={d.get('state')} meg={d.get('meg')}")
|
||||
return d
|
||||
|
||||
|
||||
def hr_fetch_all(session, title):
|
||||
rows, d, page_no = [], None, 1
|
||||
while page_no <= 20:
|
||||
d = hr_we_process_page(session, title, page_no=page_no)
|
||||
datas = d.get("jsonList") or d.get("datas") or []
|
||||
rows.extend(datas)
|
||||
if len(datas) < PAGE_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
total = d.get("total") if isinstance(d, dict) else None
|
||||
return rows, total
|
||||
|
||||
|
||||
# ==================== 免 SSO 链路验证:taskId -> formId -> 表单数据 ====================
|
||||
def wf_activity_form_id(session, task_id):
|
||||
resp = session.post(f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId",
|
||||
data={"taskId": task_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" and not d.get("formId"):
|
||||
raise RuntimeError(f"WfActivity 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
for src in [d] + [d.get(k) for k in ("data", "result") if isinstance(d.get(k), dict)]:
|
||||
for key in ("formId", "FormId", "form_id"):
|
||||
if src.get(key):
|
||||
return str(src[key])
|
||||
raise RuntimeError(f"WfActivity 未能提取 formId:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
|
||||
|
||||
def business_data(session, business_key, form_id):
|
||||
resp = session.post(f"{WORKFORM_ENGINE_URL}?method=getBusinessDate",
|
||||
data={"businessKey": business_key, "formId": form_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" or not isinstance(d.get("result"), dict):
|
||||
raise RuntimeError(f"getBusinessDate 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
return d["result"]
|
||||
|
||||
|
||||
def _norm_title(s):
|
||||
return re.sub(r"\s+", "", str(s or ""))
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def main():
|
||||
print("=" * 72)
|
||||
print("探针:OA 待办 vs HR WeProcess 一致性 + 免 SSO 链路验证(只读)")
|
||||
print(f"hr_cookies.json 修改时间: {_mtime(HR_COOKIE_FILE)}")
|
||||
print(f"oa_cookies.json 修改时间: {_mtime(OA_COOKIE_FILE)}")
|
||||
|
||||
hr_cookies = load_cookies(HR_COOKIE_FILE)
|
||||
oa_cookies = load_cookies(OA_COOKIE_FILE)
|
||||
if not hr_cookies:
|
||||
print("[终止] 未找到 hr_cookies.json,请先运行「37duHR登录」")
|
||||
return 1
|
||||
hr = build_session(hr_cookies, domain_keyword="37du.co")
|
||||
oa = build_session(oa_cookies) if oa_cookies else None
|
||||
if oa is None:
|
||||
print("[提示] 未找到 oa_cookies.json,将只测 HR 侧,无法做 OA 一致性比对")
|
||||
|
||||
all_subjects_ok = True
|
||||
for idx, subject in enumerate(SUBJECTS, 1):
|
||||
print("=" * 72)
|
||||
print(f"[{idx}/{len(SUBJECTS)}] 主题关键字: {subject}")
|
||||
|
||||
# ---- OA 侧 ----
|
||||
oa_docs, oa_total, oa_skipped = [], None, 0
|
||||
if oa is not None:
|
||||
try:
|
||||
oa_docs, oa_total, oa_skipped = oa_fetch_all(oa, subject)
|
||||
print(f"OA 待办: 接口 total={oa_total},解析去重 {len(oa_docs)} 条"
|
||||
f"(跳过协作类 {oa_skipped} 条)")
|
||||
except RuntimeError as e:
|
||||
print(f"OA 待办拉取失败: {e}")
|
||||
|
||||
# ---- HR 侧 ----
|
||||
try:
|
||||
hr_rows, hr_total = hr_fetch_all(hr, subject)
|
||||
except RuntimeError as e:
|
||||
print(f"[HR失败] {e}")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
print(f"HR WeProcess: jsonList={len(hr_rows)} 条, total={hr_total}")
|
||||
|
||||
if not hr_rows:
|
||||
print(" (HR 返回空,无法比对)")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
|
||||
# 首行字段发现 + 状态类字段
|
||||
keys = sorted(hr_rows[0].keys())
|
||||
print(f"HR 行字段({len(keys)}): {','.join(keys)}")
|
||||
for k in ("state", "processState", "taskState", "currentState", "flowState"):
|
||||
vals = sorted({str(r.get(k)) for r in hr_rows if r.get(k) is not None})
|
||||
if vals:
|
||||
print(f" 字段 {k} 取值: {vals}")
|
||||
|
||||
# ---- 一致性比对 ----
|
||||
if oa_docs is not None and oa_total is not None:
|
||||
oa_map = {_norm_title(_row(d, "title")): d for d in oa_docs}
|
||||
hr_map = {}
|
||||
for r in hr_rows:
|
||||
t = _norm_title(_row(r, "title", "processTitle", "docSubject", "businessName"))
|
||||
if t:
|
||||
hr_map.setdefault(t, r)
|
||||
matched = set(oa_map) & set(hr_map)
|
||||
oa_only, hr_only = set(oa_map) - set(hr_map), set(hr_map) - set(oa_map)
|
||||
print(f"标题比对: OA {len(oa_map)} 条 vs HR {len(hr_map)} 条,"
|
||||
f"完全匹配 {len(matched)} 条;OA 独有 {len(oa_only)} 条,HR 独有 {len(hr_only)} 条")
|
||||
for t in list(oa_only)[:5]:
|
||||
print(f" [OA独有] {oa_map[t]['title']}(发起人 {oa_map[t]['creator']})")
|
||||
for t in list(hr_only)[:5]:
|
||||
r = hr_map[t]
|
||||
print(f" [HR独有] {_row(r, 'title')}(发起人 {_row(r, 'createUserName', 'createUserNameCn')})")
|
||||
if oa_only or hr_only:
|
||||
all_subjects_ok = False
|
||||
|
||||
# ---- 免 SSO 链路验证(最多 3 条)----
|
||||
chain_ok = chain_fail = 0
|
||||
for r in hr_rows[:3]:
|
||||
task_id = str(_row(r, "taskId", "task_id"))
|
||||
bk = str(_row(r, "businessKey", "business_key"))
|
||||
try:
|
||||
if not task_id:
|
||||
raise RuntimeError("行内无 taskId")
|
||||
form_id = wf_activity_form_id(hr, task_id)
|
||||
row_form = str(_row(r, "formId", "form_id"))
|
||||
result = business_data(hr, bk, form_id)
|
||||
chain_ok += 1
|
||||
agree = ("一致" if (not row_form or row_form == form_id)
|
||||
else f"与行内formId({row_form})不一致")
|
||||
print(f" [链路OK] {_row(r, 'title')} | taskId={task_id} -> formId={form_id}"
|
||||
f"({agree}) | 表单字段数={len(result)}")
|
||||
except Exception as e:
|
||||
chain_fail += 1
|
||||
print(f" [链路FAIL] {_row(r, 'title')} | taskId={task_id} businessKey={bk} | {e}")
|
||||
print(f"免SSO链路验证: 成功 {chain_ok} 条,失败 {chain_fail} 条")
|
||||
if chain_fail:
|
||||
all_subjects_ok = False
|
||||
|
||||
print("=" * 72)
|
||||
verdict = "三个主题均一致,免 SSO 链路可用" if all_subjects_ok else "存在差异/失败,见上方明细"
|
||||
print(f"探针结束。结论: {verdict}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,483 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login_api.py
|
||||
@Description: HR 纯接口登录(无浏览器版),「37duHR登录(接口版)」影刀自定义指令模块源码。
|
||||
与 workflows/share/hr_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录(含滑块验证),不打开浏览器、无拖拽拟人。
|
||||
|
||||
登录链路(从登录页前端 JS 逆向 + 2025-10 实测验证):
|
||||
1. GET /RedseaPlatform/ 建立 Session 基础 cookie(routeEhr/JSESSIONID);
|
||||
2. GET /RedseaPlatform/captcha/get/verification/image.mob 取滑块图,返回
|
||||
result = {shadeImage(带缺口背景 jpg b64), originImage(原始背景 jpg b64),
|
||||
cutoutImage(55x55 拼图块 png b64), y(拼图块 top), x(恒 0)};
|
||||
前端 CSS 固定 340x171 容器、background 原尺寸绘制 => 浏览器只显示原图
|
||||
左上角 min(w,340) x min(h,171) 的窗口,坐标系 1:1,匹配前需先裁切到该窗口;
|
||||
3. 定位缺口 x:
|
||||
a) 首选 diff 法:|shadeImage - originImage| 最大连通域左边界 = 缺口 x
|
||||
(两图同源成对,diff 定位最准,且天然免疫整图变换);
|
||||
b) 兜底模板匹配法(与 hr_login.py 浏览器截图版同源算法);
|
||||
两者互验:diff 可信用 diff,diff 缺失用模板,分歧过大判定本图不可信换图重取;
|
||||
4. POST /RedseaPlatform/captcha/check/verification/result.mob?x=&y= 校验滑块(返回 true/false);
|
||||
5. POST /RedseaPlatform/j_red_security_check/PW 提交登录:
|
||||
form: MENU_TYPE=classic & sysCode=RedseaP & j_username & j_password=<AES密文> & x & y
|
||||
header: Csrf-Token: RP(前端写死常量);
|
||||
密码加密:AES-128-ECB + PKCS7,key='ps_uer_!@#BGYUJN'(前端硬编码),输出 base64;
|
||||
成功判定:state != "0";失败 state == "0" 且 meg 为错误信息;
|
||||
6. GET getCurUserInfo 校验会话有效后,cookies 落盘 hr_cookies.json。
|
||||
|
||||
配置(与 hr_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
hr_login_username=用户名
|
||||
hr_login_password=密码
|
||||
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install requests python-dotenv opencv-python numpy pycryptodome
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login_api.py 独立运行(等价 main({"force": false}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
import base64
|
||||
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 hr_login.py 统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://hr.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/RedseaPlatform/'
|
||||
CAPTCHA_GET_URL = BASE_URL + '/RedseaPlatform/captcha/get/verification/image.mob'
|
||||
CAPTCHA_CHECK_URL = BASE_URL + '/RedseaPlatform/captcha/check/verification/result.mob'
|
||||
LOGIN_POST_URL = BASE_URL + '/RedseaPlatform/j_red_security_check/PW'
|
||||
GET_CUR_USER_INFO_URL = BASE_URL + '/RedseaPlatform/PtUsers.mc?method=getCurUserInfo'
|
||||
|
||||
# 前端登录页硬编码:AES 密钥与 CSRF 常量
|
||||
AES_KEY = b'ps_uer_!@#BGYUJN'
|
||||
CSRF_TOKEN = 'RP'
|
||||
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# 浏览器可见窗口(登录页 CSS:.imgBg 340x171 固定、background 原尺寸绘制)
|
||||
VIEW_W = 340
|
||||
VIEW_H = 171
|
||||
|
||||
RETRY_MAX = 5 # 单轮滑块重试次数(与浏览器版一致)
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 hr_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 hr_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(与 hr_login.py 同款) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(前端 pubAesEncrypt 等价实现) ==================
|
||||
def aes_encrypt_password(password):
|
||||
"""AES-128-ECB + PKCS7,key 前端硬编码,输出 base64(与 CryptoJS encrypted.toString() 一致)。"""
|
||||
cipher = AES.new(AES_KEY, AES.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 16))).decode('ascii')
|
||||
|
||||
|
||||
# ================== 滑块图获取与裁切 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(routeEhr/JSESSIONID),验证码/登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Referer": LOGIN_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def _b64_to_img(b64str, flag):
|
||||
"""base64 -> cv2 图像(失败返回 None)。"""
|
||||
if not b64str:
|
||||
return None
|
||||
try:
|
||||
buf = base64.b64decode(b64str)
|
||||
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _crop_view(img):
|
||||
"""裁切到浏览器可见窗口(左上角 min(w,340) x min(h,171)),坐标系与浏览器 1:1。"""
|
||||
if img is None:
|
||||
return None
|
||||
h, w = img.shape[:2]
|
||||
return img[:min(h, VIEW_H), :min(w, VIEW_W)]
|
||||
|
||||
|
||||
def get_captcha(session):
|
||||
"""取滑块图,返回 dict(shade, origin, cutout, y);y 为拼图块 top(服务端给定)。"""
|
||||
resp = session.get(CAPTCHA_GET_URL, timeout=TIMEOUT)
|
||||
data = resp.json()
|
||||
res = data.get("result") or {}
|
||||
shade = _crop_view(_b64_to_img(res.get("shadeImage"), cv2.IMREAD_COLOR))
|
||||
origin = _crop_view(_b64_to_img(res.get("originImage"), cv2.IMREAD_COLOR))
|
||||
cutout = _b64_to_img(res.get("cutoutImage"), cv2.IMREAD_UNCHANGED)
|
||||
y = int(res.get("y") or 0)
|
||||
return {"shade": shade, "origin": origin, "cutout": cutout, "y": y}
|
||||
|
||||
|
||||
# ================== 缺口定位 ==================
|
||||
def locate_by_diff(shade, origin):
|
||||
"""diff 法:shade/origin 同源成对,逐像素差异的最大连通域左边界 = 缺口 x。
|
||||
返回 (x, 可信度);不可信返回 (None, 原因)。"""
|
||||
if shade is None or origin is None or shade.shape != origin.shape:
|
||||
return None, "图片缺失或尺寸不一致"
|
||||
diff = cv2.absdiff(shade, origin).max(axis=2)
|
||||
mask = (diff > 30).astype(np.uint8) * 255
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
||||
n, _, stats, _ = cv2.connectedComponentsWithStats(mask)
|
||||
if n <= 1:
|
||||
return None, "无差异区域"
|
||||
best = max(range(1, n), key=lambda i: stats[i, cv2.CC_STAT_AREA])
|
||||
area = int(stats[best, cv2.CC_STAT_AREA])
|
||||
x = int(stats[best, cv2.CC_STAT_LEFT])
|
||||
# 缺口约 55x55(面积 ~3000),过大/过小视为 jpg 噪声或异常
|
||||
if area < 300 or area > 12000:
|
||||
return None, f"差异区域面积异常({area})"
|
||||
return x, f"diff(area={area})"
|
||||
|
||||
|
||||
def match_slider_dual(bg_img, slider_color):
|
||||
"""模板匹配滑块缺口,返回物理距离 px。
|
||||
算法与 hr_login.py 浏览器截图版同源(边缘 Canny + TM_CCOEFF_NORMED + 白区加权)。"""
|
||||
if bg_img is None or slider_color is None:
|
||||
return None
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset = 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, _ = x_min, np.min(ys)
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
|
||||
return None
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_loc = scored[0][2]
|
||||
else:
|
||||
best_loc = candidates[0][1]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
def solve_distance(cap):
|
||||
"""定位缺口并输出应提交的 x(= 滑块从 0 到缺口的距离,即缺口左边界 - 拼图透明边)。
|
||||
返回 (x, 说明);本图不可信返回 (None, 原因)。
|
||||
|
||||
几何说明(与浏览器画面一致):
|
||||
- 原图宽 >= 340:浏览器只显示左上 340x171 裁切窗口;
|
||||
- 原图宽 < 340:.imgBg 的 background 默认 repeat 会把原图复制拼接到右侧,
|
||||
画面上缺口可能出现副本(x_g 与 x_g+原图宽),但服务端记录的是原图缺口
|
||||
坐标 x_g,提交 x_g 即可通过;
|
||||
因此匹配始终在原图(裁切后)上进行——拼接成画面等价图反而会让 diff 出双峰
|
||||
(副本也带缺口)——越界过滤上限用实际图宽。
|
||||
"""
|
||||
shade = cap["shade"]
|
||||
cutout = cap["cutout"]
|
||||
s_w = cutout.shape[1] if cutout is not None else 55
|
||||
view_w = shade.shape[1] if shade is not None else VIEW_W
|
||||
x_diff, info = locate_by_diff(cap["shade"], cap["origin"])
|
||||
x_tpl = match_slider_dual(cap["shade"], cutout)
|
||||
print(f" 缺口定位:{info} diff_x={x_diff} tpl_x={x_tpl}")
|
||||
|
||||
x, how = None, "无法定位"
|
||||
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
|
||||
x, how = x_diff, "diff+tpl 一致"
|
||||
elif x_diff is not None:
|
||||
x, how = x_diff, "仅 diff(与模板分歧)"
|
||||
elif x_tpl is not None:
|
||||
x, how = x_tpl, "仅模板"
|
||||
if x is None:
|
||||
return None, how
|
||||
# 合理性校验:缺口不会贴最左/最右(贴边缺口可能是平铺坐标映射产物,直接换图)
|
||||
if x <= s_w or x > view_w - s_w:
|
||||
return None, f"缺口位置越界({x}, 图宽{view_w})"
|
||||
return x, how
|
||||
|
||||
|
||||
# ================== 滑块校验与登录提交 ==================
|
||||
def check_slider(session, x, y):
|
||||
"""提交滑块校验,返回 True/False。"""
|
||||
resp = session.post(CAPTCHA_CHECK_URL, params={"x": int(round(x)), "y": int(y)}, timeout=TIMEOUT)
|
||||
try:
|
||||
return bool(resp.json())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def submit_login(session, username, password, x, y):
|
||||
"""提交登录,返回 (ok, message)。"""
|
||||
form = {
|
||||
"MENU_TYPE": "classic",
|
||||
"sysCode": "RedseaP",
|
||||
"j_username": username,
|
||||
"j_password": aes_encrypt_password(password),
|
||||
"x": int(round(x)),
|
||||
"y": int(y),
|
||||
}
|
||||
headers = {"Csrf-Token": CSRF_TOKEN}
|
||||
resp = session.post(LOGIN_POST_URL, data=form, headers=headers, timeout=TIMEOUT)
|
||||
try:
|
||||
result = resp.json()
|
||||
except Exception:
|
||||
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
|
||||
if result.get("state") == "0":
|
||||
return False, str(result.get("meg") or "登录失败")
|
||||
return True, "登录成功"
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:滑块校验(带重试)+ 提交登录。成功返回 True。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
for attempt in range(RETRY_MAX):
|
||||
print(f"--- 第 {attempt + 1} 次尝试验证 ---")
|
||||
try:
|
||||
cap = get_captcha(session)
|
||||
except Exception as e:
|
||||
print(f"取验证码图异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
shade = cap["shade"]
|
||||
y = cap["y"]
|
||||
# y 用实际图高校验(裁切窗口高 = min(图高, 171),小图场景更严谨)
|
||||
if shade is None or not (0 <= y <= shade.shape[0] - 55):
|
||||
print(f"验证码图异常(shade={None if shade is None else shade.shape}, y={y})")
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
x, info = solve_distance(cap)
|
||||
if x is None:
|
||||
time.sleep(random.uniform(0.3, 0.8))
|
||||
continue
|
||||
|
||||
print(f" 提交滑块校验 x={x} y={y}({info})")
|
||||
if check_slider(session, x, y):
|
||||
print(" 滑块校验通过")
|
||||
ok, msg = submit_login(session, username, password, x, y)
|
||||
if ok:
|
||||
save_session_cookies(session)
|
||||
return True
|
||||
print(f"登录失败:{msg}")
|
||||
return False # 账号密码类错误,重试无意义
|
||||
else:
|
||||
print(" 滑块校验未通过,换图重试")
|
||||
time.sleep(random.uniform(0.5, 1.2))
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主入口(与 hr_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次会话有效性,确保落盘的 cookies 可用
|
||||
if _is_hr_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过或接口异常)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录(接口版)」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,319 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login_api.py
|
||||
@Description: OA 纯接口登录(无浏览器版),「37duOA登录(接口版)」影刀自定义指令模块源码。
|
||||
与 workflows/share/oa_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json;
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 配置读取一致(共享 .env 的 oa_login_username / oa_login_password);
|
||||
- 对外入口 main(force) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录,不打开浏览器。
|
||||
|
||||
登录链路(蓝凌 EKP security.js 逆向 + 2026-10 实测验证):
|
||||
1. GET /login.jsp 建立 Session 基础 cookie(SESSION/sl-session);
|
||||
2. GET /resource/js/session.jsp?_=时间戳 服务端按会话下发密钥串:
|
||||
window.getSessionId = function(){ return "<36位UUID>"; }
|
||||
同一会话内固定,登录 POST 必须与本次取密钥同会话;
|
||||
3. 密码加密(复刻 security.js desEncrypt 的 des 分支,浏览器默认走 sm2 分支,
|
||||
但密文前缀带算法标记、服务端按标记选算法解密,des 同样受支持):
|
||||
a) 密钥串不足 16 位补 "abcdefghijklmnopqrstuvwxyz",再 toUpperCase;
|
||||
b) key = 前 8 字符 toHexString、iv = 第 8~16 字符 toHexString
|
||||
(toHexString = 逐字符 charCode 转 16 进制拼接,ASCII 即 .encode().hex());
|
||||
c) DES-CBC + PKCS7 加密密码,输出 base64;
|
||||
d) j_password = 标记前缀 "\\u4445\\u5320\\u4d45" + base64 密文;
|
||||
4. POST /j_acegi_security_check form: j_username & j_password & j_redirectto(空)
|
||||
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
|
||||
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
|
||||
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
|
||||
|
||||
配置(与 oa_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)OA 会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install requests python-dotenv pycryptodome
|
||||
|
||||
入口:
|
||||
python oa_login_api.py 独立运行(等价 main(force=True))
|
||||
main(force) 影刀自定义指令调用入口,force 传 True/False,返回 JSON 安全 dict
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import base64
|
||||
|
||||
import requests
|
||||
from Crypto.Cipher import DES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 oa_login.py 统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/login.jsp'
|
||||
SESSION_KEY_URL = BASE_URL + '/resource/js/session.jsp'
|
||||
LOGIN_POST_URL = BASE_URL + '/j_acegi_security_check'
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = BASE_URL + "/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# security.js 密码加密常量(逆向自 /resource/js/security.js,Dean Edwards packer 混淆已还原)
|
||||
DES_MARKER = "\u4445\u5320\u4d45" # des 分支密文标记前缀(服务端按标记选算法)
|
||||
DES_PADDING = "abcdefghijklmnopqrstuvwxyz" # 密钥串不足 16 位时的补齐串
|
||||
SESSION_KEY_RE = re.compile(
|
||||
r'getSessionId\s*=\s*function\s*\(\s*\)\s*\{\s*return\s*"([^"]*)"')
|
||||
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 oa_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 oa_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== 会话校验(与 oa_login.py 同款逻辑) ==================
|
||||
def _is_todo_count_json(resp):
|
||||
"""sumTodoCount 响应判定:200 且返回 JSON 视为登录态有效。"""
|
||||
try:
|
||||
return (resp.status_code == 200 and bool(resp.text)
|
||||
and resp.text.lstrip().startswith(("{", "[")))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
与 oa_login.py 及业务脚本使用同一套接口与校验逻辑。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_session_alive(session):
|
||||
"""用当前登录会话直接校验(登录后、落盘前使用)。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"会话校验异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(复刻 security.js desEncrypt 的 des 分支) ==================
|
||||
def to_hex_str(text):
|
||||
"""复刻 security.js 的 toHexString:逐字符 charCode 转 16 进制(小写、无补零)拼接。"""
|
||||
return ''.join(format(ord(ch), 'x') for ch in text)
|
||||
|
||||
|
||||
def fetch_session_key(session):
|
||||
"""GET session.jsp 取服务端按会话下发的密钥串(同会话固定)。"""
|
||||
url = f"{SESSION_KEY_URL}?_={int(time.time() * 1000)}"
|
||||
resp = session.get(url, timeout=TIMEOUT)
|
||||
m = SESSION_KEY_RE.search(resp.text)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def des_encrypt_password(session, password):
|
||||
"""返回可直接提交的 j_password:标记前缀 + DES-CBC-PKCS7 base64 密文。
|
||||
密钥派生:密钥串不足 16 位补齐 -> 大写 -> key/iv 各取 8 字符 toHexString。"""
|
||||
sid = fetch_session_key(session)
|
||||
if not sid:
|
||||
raise RuntimeError("session.jsp 未返回 getSessionId 密钥串")
|
||||
b = sid
|
||||
if len(b) < 16:
|
||||
b += DES_PADDING
|
||||
b = b.upper()
|
||||
key = bytes.fromhex(to_hex_str(b[:8]))
|
||||
iv = bytes.fromhex(to_hex_str(b[8:16]))
|
||||
cipher = DES.new(key, DES.MODE_CBC, iv)
|
||||
ct = base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 8))).decode('ascii')
|
||||
return DES_MARKER + ct
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(SESSION/sl-session),取密钥与登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:取密钥 -> DES 加密 -> 表单提交 -> 会话校验。返回 (ok, message)。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
j_password = des_encrypt_password(session, password)
|
||||
except Exception as e:
|
||||
print(f"获取会话密钥/加密异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = session.post(
|
||||
LOGIN_POST_URL,
|
||||
data={"j_username": username, "j_password": j_password, "j_redirectto": ""},
|
||||
headers={"Referer": LOGIN_URL, "Origin": BASE_URL},
|
||||
timeout=TIMEOUT, allow_redirects=True)
|
||||
except Exception as e:
|
||||
print(f"提交登录异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
final_url = str(resp.url)
|
||||
if "login.jsp" in final_url:
|
||||
# Acegi 拒绝(凭据错误/解密失败)会重定向回登录页,重试无意义
|
||||
return False, f"登录被拒绝(用户名或密码错误?):{final_url}"
|
||||
if check_session_alive(session):
|
||||
save_session_cookies(session)
|
||||
return True, "登录成功"
|
||||
print(f"登录后会话校验未通过,最终URL:{final_url}")
|
||||
time.sleep(1)
|
||||
return False, "登录失败(重试耗尽或接口异常)"
|
||||
|
||||
|
||||
# ================== 登录主入口(与 oa_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok, msg = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次落盘 cookies 可用性,确保业务脚本拿到的登录态真实有效
|
||||
if _is_oa_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "message": msg, "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口(与 oa_login.py 契约一致) ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录(接口版)」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
Reference in New Issue
Block a user