# -*- 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']*>(.*?)', 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())