新增步骤7脚本,实现OA待办对账销办逻辑: 1. 解析OA待办链路由fdId获取HR任务ID 2. 核对任务/流程状态,仅销办COMPLETED状态的待办 3. 校验账号权限,仅处理当前人资账号待办 4. 支持试算模式,避免误操作 同时更新XQ0035转正流程规则,将分支1回填条件从"到期能否考核通过=能"调整为"人员处理意见=直接离职/无需处理",并更新XQ0037合同模板逻辑,为超龄人员配置专用合同模板组合
255 lines
11 KiB
Python
255 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0037 步骤7:OA「改签离职电子签」待办对账销办。
|
||
|
||
判据链路(2026-10-22 实锤):
|
||
OA 待办 fdId
|
||
--(GET sysNotifyTodo.do?method=view&fdId=)--> 跳转脚本 gotourl(URL 编码)
|
||
--(unquote 后取 fkId=)--> HR taskId
|
||
--(POST WeTask.mc?method=query&task_id=)--> jsonList[0] 的
|
||
currentState / activityName / participantName / processId
|
||
--(GET WeProcess.mc?method=getWeProcess&processId=)--> result.currentState
|
||
|
||
销办判据(任一成立才销,其余一律跳过):
|
||
1. HR 任务 currentState == "COMPLETED"(任务已办结);
|
||
2. HR 流程 currentState == "COMPLETED"(流程完结,任务状态残留也清掉)。
|
||
WAITING / ACCEPTED = 仍在自己手上待办,绝不销;
|
||
取不到 fkId / 查不到 HR 任务 = 无法判定,跳过不销。
|
||
|
||
账号边界(重要):
|
||
OA 销办接口只能销「当前 OA 登录账号自己」的待办。同一 HR 流程会向全部参与者
|
||
(办理人 + 10 位审批人)各推一条 OA 待办;本脚本登录的是「人资专用号」,只能清
|
||
自己那条,其余参与者的待办无法代销,记入「他人待办」清单,需对应账号自行处理
|
||
或等 HR 服务端撤回(人工在 HR 提交时服务端会批量撤回,脚本提交无此效果)。
|
||
|
||
运行方式:
|
||
1. 命令行:python step7_oa_todo_reconcile.py(DRY_RUN 于文件顶部,默认 False=实销)
|
||
2. 业务脚本:importlib 加载调用 main(dry_run=...)
|
||
建议首次以 DRY_RUN=True 试算核对清单后再实跑。
|
||
"""
|
||
import os
|
||
import sys
|
||
import time
|
||
from urllib.parse import unquote
|
||
|
||
import requests
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
_SHARE = r"d:\work\code\37duAutomation\workflows\share"
|
||
_XQ35 = r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0035 服务岗转正不通过电子签(离职+入职)"
|
||
for _p in (_XQ35, _SHARE, HERE):
|
||
if _p not in sys.path:
|
||
sys.path.insert(0, _p)
|
||
|
||
import oa_login_api # noqa: E402
|
||
from step2_sign_new_contract import _request_retry # noqa: E402
|
||
from step2_transfer_initiate import _hr_session # noqa: E402
|
||
from step3_transfer_todo import FLOW_TITLE, _log # noqa: E402
|
||
|
||
# ---------- 常量 ----------
|
||
OA_BASE = "https://oa.37du.co"
|
||
OA_TODO_URL = f"{OA_BASE}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||
OA_TODO_TYPE = "13" # fdType=13:第三方(HR)待办
|
||
HR_BASE = "https://hr.37du.co/RedseaPlatform"
|
||
|
||
# 当前 OA 登录账号昵称:OA 只能销本账号待办;participantName 与之不符的不销。
|
||
# 留空则不做账号校验(不建议,可能把「待办指向的任务不属于本账号」误销)。
|
||
OA_ACCOUNT_NAME = "人资专用号"
|
||
|
||
TASK_DONE_STATE = "COMPLETED" # 任务已办结
|
||
TASK_ACTIVE_STATES = ("WAITING", "ACCEPTED")
|
||
PROCESS_DONE_STATE = "COMPLETED" # 流程完结
|
||
|
||
MAX_OA_PAGES = 50 # 待办列表分页上限(15 条/页)
|
||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||
|
||
# 列表页 JS 数据行:data:["<fdId>","","<标题>","<接收时间>"]
|
||
ROW_RE = __import__("re").compile(
|
||
r'data:\["([0-9a-f]{32})"\s*,\s*"[^"]*"\s*,\s*"([^"]*)"\s*,\s*"([^"]*)"')
|
||
TOTAL_RE = __import__("re").compile(r"total:(\d+)")
|
||
FKID_RE = __import__("re").compile(r"fkId=([0-9a-f\-]{36})")
|
||
|
||
# 试算开关:True=试算(只打印清单,不销办);False=实跑销办
|
||
DRY_RUN = False
|
||
|
||
|
||
# ---------- OA 会话 ----------
|
||
def _oa_session():
|
||
"""复用/刷新 OA 登录态,构建带 cookies 的 requests 会话。"""
|
||
res = oa_login_api.ensure_login()
|
||
if not res.get("success"):
|
||
raise RuntimeError(f"OA 登录失败:{res.get('message')}")
|
||
cookies = oa_login_api.load_cookies() or []
|
||
if not cookies:
|
||
raise RuntimeError("OA 登录态为空(oa_cookies.json 无有效 cookie)")
|
||
session = requests.Session()
|
||
session.headers.update({"User-Agent": oa_login_api.UA})
|
||
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", "/"))
|
||
return session
|
||
|
||
|
||
def _oa_request(session, method, params, data=None, desc=""):
|
||
"""OA 请求(全局重试 3 次);返回 response。"""
|
||
last_exc = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
if method.upper() == "GET":
|
||
resp = session.get(OA_TODO_URL, params=params, timeout=30)
|
||
else:
|
||
resp = session.post(OA_TODO_URL, params=params, data=data, timeout=30)
|
||
resp.raise_for_status()
|
||
return resp
|
||
except requests.RequestException as exc:
|
||
last_exc = exc
|
||
if attempt < MAX_ATTEMPTS:
|
||
time.sleep(attempt)
|
||
raise RuntimeError(f"{desc}重试{MAX_ATTEMPTS}次仍失败:{last_exc}")
|
||
|
||
|
||
# ---------- 待办列表 ----------
|
||
def fetch_oa_todos(session):
|
||
"""分页拉全部 OA 待办,按 FLOW_TITLE 过滤 -> [{fdId,title,time}]。"""
|
||
rows, seen = [], set()
|
||
for pageno in range(1, MAX_OA_PAGES + 1):
|
||
resp = _oa_request(session, "GET",
|
||
{"method": "list", "fdType": OA_TODO_TYPE,
|
||
"pageno": str(pageno)}, desc=f"OA待办第{pageno}页")
|
||
page_rows = ROW_RE.findall(resp.text)
|
||
for fid, title, tm in page_rows:
|
||
if fid in seen:
|
||
continue
|
||
seen.add(fid)
|
||
rows.append({"fdId": fid, "title": title, "time": tm})
|
||
m = TOTAL_RE.search(resp.text)
|
||
total_pages = int(m.group(1)) if m else 1
|
||
if not page_rows or pageno >= total_pages:
|
||
break
|
||
hits = [r for r in rows if FLOW_TITLE in r["title"]]
|
||
_log(f"[OA] 待办共 {len(rows)} 条,其中「{FLOW_TITLE}」{len(hits)} 条")
|
||
return hits
|
||
|
||
|
||
def resolve_task_id(session, fd_id):
|
||
"""OA 待办 view 页 -> HR taskId(gotourl 里的 fkId,需先 URL 解码)。"""
|
||
resp = _oa_request(session, "GET", {"method": "view", "fdId": fd_id},
|
||
desc=f"OA待办详情{fd_id}")
|
||
m = FKID_RE.search(unquote(resp.text))
|
||
return m.group(1) if m else ""
|
||
|
||
|
||
# ---------- HR 只读核对 ----------
|
||
def query_hr_task(session, task_id):
|
||
"""WeTask.mc?method=query 查任务(只读,不会接单)。返回任务 dict。"""
|
||
resp = _request_retry("POST", f"{HR_BASE}/WeTask.mc?method=query",
|
||
session, data={"task_id": task_id})
|
||
rows = resp.json().get("jsonList") or []
|
||
return rows[0] if rows else {}
|
||
|
||
|
||
def query_process_state(session, process_id):
|
||
"""WeProcess.mc?method=getWeProcess 查流程状态。返回 currentState 字符串。"""
|
||
last_exc = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
resp = session.get(f"{HR_BASE}/WeProcess.mc?method=getWeProcess",
|
||
params={"processId": process_id}, timeout=30)
|
||
result = resp.json().get("result") or {}
|
||
if isinstance(result, str):
|
||
import json
|
||
result = json.loads(result)
|
||
return str(result.get("currentState") or "")
|
||
except Exception as exc: # noqa: BLE001
|
||
last_exc = exc
|
||
if attempt < MAX_ATTEMPTS:
|
||
time.sleep(attempt)
|
||
raise RuntimeError(f"查流程状态失败({process_id}):{last_exc}")
|
||
|
||
|
||
def decide(task, process_state):
|
||
"""销办判定 -> (should_delete: bool, reason: str)。"""
|
||
task_state = str(task.get("currentState") or "")
|
||
activity = str(task.get("activityName") or "")
|
||
if task_state == TASK_DONE_STATE:
|
||
return True, f"任务已办结({activity} COMPLETED)"
|
||
if process_state == PROCESS_DONE_STATE:
|
||
return True, f"流程已完结(任务状态{task_state or '空'},一并清理)"
|
||
if task_state in TASK_ACTIVE_STATES:
|
||
return False, f"仍待办理({activity} {task_state})"
|
||
return False, f"无法判定(任务状态{task_state or '空'} / 流程{process_state or '空'})"
|
||
|
||
|
||
# ---------- 销办 ----------
|
||
def delete_todo(session, fd_id):
|
||
"""OA 置为已办(deleteall)。返回 (ok, message)。"""
|
||
resp = _oa_request(session, "POST", {"method": "deleteall"},
|
||
data={"List_Selected": fd_id}, desc=f"销办{fd_id}")
|
||
text = resp.text or ""
|
||
ok = ("您的操作已成功" in text) or ('"state":"1"' in text)
|
||
return ok, "您的操作已成功" if ok else text[:200]
|
||
|
||
|
||
# ---------- 主流程 ----------
|
||
def main(dry_run=None):
|
||
dry_run = DRY_RUN if dry_run is None else dry_run
|
||
oa = _oa_session()
|
||
todos = fetch_oa_todos(oa)
|
||
if not todos:
|
||
_log("[汇总] 无「%s」待办,无事可做" % FLOW_TITLE)
|
||
return {"matched": 0, "deleted": 0, "active": 0, "other": 0,
|
||
"unmapped": 0, "failed": 0}
|
||
|
||
hr = _hr_session()
|
||
stats = {"matched": len(todos), "deleted": 0, "active": 0, "other": 0,
|
||
"unmapped": 0, "failed": 0}
|
||
for row in todos:
|
||
fid, title, tm = row["fdId"], row["title"], row["time"]
|
||
try:
|
||
tid = resolve_task_id(oa, fid)
|
||
if not tid:
|
||
stats["unmapped"] += 1
|
||
_log(f"[跳过] {title} | {tm} | 未能从 view 页取到 fkId(taskId)")
|
||
continue
|
||
task = query_hr_task(hr, tid)
|
||
if not task:
|
||
stats["unmapped"] += 1
|
||
_log(f"[跳过] {title} | taskId={tid} | HR 查不到该任务")
|
||
continue
|
||
activity = str(task.get("activityName") or "")
|
||
participant = str(task.get("participantName") or "")
|
||
pid = str(task.get("processId") or "")
|
||
if OA_ACCOUNT_NAME and participant and participant != OA_ACCOUNT_NAME:
|
||
stats["other"] += 1
|
||
_log(f"[他人待办] {title} | {activity} | 参与人={participant}(本账号"
|
||
f"{OA_ACCOUNT_NAME}无权代销,需对方账号处理或 HR 服务端撤回)")
|
||
continue
|
||
pstate = query_process_state(hr, pid) if pid else ""
|
||
should, reason = decide(task, pstate)
|
||
if not should:
|
||
stats["active"] += 1
|
||
_log(f"[保留] {title} | {reason}")
|
||
continue
|
||
if dry_run:
|
||
_log(f"[试算] {title} | {reason} -> 待销办 fdId={fid}")
|
||
continue
|
||
ok, msg = delete_todo(oa, fid)
|
||
if ok:
|
||
stats["deleted"] += 1
|
||
_log(f"[销办] {title} | {reason}")
|
||
else:
|
||
stats["failed"] += 1
|
||
_log(f"[失败] {title} | {msg}")
|
||
except Exception as exc: # noqa: BLE001
|
||
stats["failed"] += 1
|
||
_log(f"[失败] {title} | {type(exc).__name__}: {exc}")
|
||
|
||
_log("[汇总] 改签待办={} 已销={} 保留(待办中)={} 他人待办={} 无法判定={} 失败={}{}".format(
|
||
stats["matched"], stats["deleted"], stats["active"], stats["other"],
|
||
stats["unmapped"], stats["failed"], "(试算模式,未销办)" if dry_run else ""))
|
||
return stats
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|