448 lines
20 KiB
Python
448 lines
20 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0037 步骤7:OA「改签离职电子签」待办对账销办(插件版)。
|
||
|
||
判据链路:
|
||
OA 待办 WebService getTodo(逐人扫描,type=0,otherCond appName=EHR)
|
||
--> doc.modelId 即 HR taskId(与旧版 view 页 gotourl 里的 fkId 一致)
|
||
--(POST WeTask.mc?method=query&task_id=)--> jsonList[0] 的
|
||
currentState / activityName / participantName / processId
|
||
--(GET WeProcess.mc?method=getWeProcess&processId=)--> result.currentState
|
||
|
||
待办发现范围:
|
||
不能只看人资号自己的待办——某个流程一旦把人资号那条销掉,该流程就再也发现不了,
|
||
而其他人的同名待办仍挂在各自列表里(实测 10 名成员名下共 171 条,历史残留居多)。
|
||
因此入口是「逐人扫描」:人资号 + NAME_TO_UID 里每个成员,各自 getTodo 后按标题过滤。
|
||
|
||
销办判据(任一成立才销,其余一律跳过):
|
||
1. HR 任务 endTime 非空 = 该节点已结束(COMPLETED 办结 / OVERDUE 超期跳过);
|
||
2. HR 流程 currentState == "COMPLETED"(流程完结,任务状态残留也清掉)。
|
||
endTime 为空且 WAITING / ACCEPTED = 仍在本人手上待办,绝不销;
|
||
取不到 modelId / 查不到 HR 任务 = 无法判定,跳过不销。
|
||
|
||
销办方式:
|
||
实测 OA 待办 modelId == 该接收人自己的 HR taskId(同一流程内每人一条独立待办),
|
||
因此不能拿「某一条待办」代表整个流程。做法是逐条待办判断:反查其 HR 任务状态,
|
||
判据成立就 deleteTodo(modelId=该待办 modelId, optType=1),只发真实存在的销办请求。
|
||
实测该接口只依赖 OA 登录 cookies、不校验身份,可跨人销办;
|
||
returnState=2 为成功(重复销办同样返回 2),0 为该 taskId 无待办。
|
||
|
||
销后回查(可选):
|
||
VERIFY_AFTER_DELETE 开启且 NAME_TO_UID 里有该参与人姓名->OA fdId 时,
|
||
用 getTodo(targets={"Id": fdId}, modelId) 独立回查「他自己名下」那条是否已清空;
|
||
未配置 fdId 的人跳过回查(仅统计 verify_skipped),不影响销办。
|
||
|
||
【插件版移植说明】由影刀版 step7_oa_todo_reconcile.py 移植:
|
||
- OA 登录态改经底座注入(config.get_oa_session -> ctx.get_session("oa")),
|
||
不再自行登录/读 cookies 文件;
|
||
- HR 登录态同样走底座注入(config.get_session -> ctx.get_session("hr"));
|
||
- 重试函数复用插件内嵌副本 xq35_step2_sign_new_contract._request_retry;
|
||
- print 日志由插件入口统一改道 ctx.log 推送前端。
|
||
"""
|
||
import time
|
||
from json import dumps as json_dumps
|
||
from json import loads as json_loads
|
||
from re import compile as re_compile
|
||
from xml.etree import ElementTree as ET
|
||
from xml.sax.saxutils import escape
|
||
|
||
import requests
|
||
|
||
from .. import config
|
||
from .step3_transfer_todo import FLOW_TITLE
|
||
from .xq35_step2_sign_new_contract import _request_retry
|
||
|
||
# ---------- 常量 ----------
|
||
OA_BASE = "https://oa.37du.co"
|
||
OA_WS_URL = f"{OA_BASE}/sys/webservice/sysNotifyTodoWebService"
|
||
OA_WS_NS = "http://webservice.notify.sys.kmss.landray.com/"
|
||
OA_HELP_URL = (f"{OA_BASE}/sys/notify/webservice/SysNotifyWebServiceHelp.jsp"
|
||
"?name=%E5%BE%85%E5%8A%9E%E6%9C%8D%E5%8A%A1&s_css=default")
|
||
HR_BASE = "https://hr.37du.co/RedseaPlatform"
|
||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||
|
||
OA_APP_NAME = "EHR" # HR 推送待办的 appName(实测值)
|
||
OA_TODO_TYPE_ALL = 0 # getTodo.type:0=所有待办
|
||
PAGE_SIZE = 200 # getTodo 每页条数
|
||
MAX_OA_PAGES = 20 # 分页上限
|
||
DELETE_OPT_TYPE = 1 # deleteTodo.optType:1=按 modelId 整条删除(实测可跨人)
|
||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||
ORG_SEARCH_URL = f"{OA_BASE}/sys/common/dataxml.jsp" # OA 通讯录人员搜索
|
||
|
||
TASK_ACTIVE_STATES = ("WAITING", "ACCEPTED")
|
||
PROCESS_DONE_STATE = "COMPLETED" # 流程完结
|
||
|
||
CURRENT_USER_RE = re_compile(r'CurrentUserId:"([^"]*)"')
|
||
_DATA_TAG_RE = re_compile(r'<data\b[^>]*>')
|
||
_ATTR_RE = re_compile(r'([A-Za-z]+)="([^"]*)"')
|
||
_SOAP_ENV = """<?xml version="1.0" encoding="utf-8"?>
|
||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
|
||
<soap:Body>
|
||
<ns:{op} xmlns:ns="{ns}"><arg0>{inner}</arg0></ns:{op}>
|
||
</soap:Body>
|
||
</soap:Envelope>"""
|
||
|
||
# 试算开关:True=试算(只打印清单,不销办);False=实跑销办(插件入口按字段 dry_run 传入)
|
||
DRY_RUN = False
|
||
|
||
# 销后按人回查(可选):姓名 -> OA 人员 fdId(通讯录 organizationDialogSearch 得到的 id)。
|
||
# 回查方式 getTodo(targets={"Id": fdId}, modelId),能独立确认「别人那条」是否真没了。
|
||
# 表里没有的姓名会运行时自动查通讯录解析(同名多人按「这条待办在谁名下」消歧,本次运行内缓存);
|
||
# 解析不出来(如通讯录无此账号)则跳过回查,不影响销办。
|
||
VERIFY_AFTER_DELETE = True
|
||
NAME_TO_UID = {
|
||
"人资专用号": "1342173e36cf416088266b17d7d084a4",
|
||
"徐红丽": "1790d12ee9cc45353998fb64403a921a",
|
||
"张玲玲": "17445313c94796b7cfd43764c3e8dcad",
|
||
"杨芸": "17ef0c892d1316151850daa402abf934",
|
||
"周卫": "17445313c00c15523dd56974b5fb8d19",
|
||
"刘纤": "17445313c2424b917a19fe144678571a",
|
||
"陈杰": "17445313c36834463e7fb444c7e8c1dc",
|
||
"赵晓雪": "17cbbf0e270b75dc4d58e9f4eaa89119",
|
||
"李泽燕": "17445313c5b0188ae035c6b42acb58b3",
|
||
"陈莲": "17445313c126283b8d2c8fe403babb0f",
|
||
}
|
||
|
||
_USER_ID = ""
|
||
_UID_CACHE = {} # 姓名 -> fdId(""=解析不出),本次运行内复用
|
||
|
||
|
||
def _log(msg):
|
||
print(msg, flush=True)
|
||
|
||
|
||
# ---------- 会话(底座注入) ----------
|
||
def _oa_session():
|
||
"""获取底座注入的共享 OA 会话(壳子运行前已按账号自动补登)。"""
|
||
try:
|
||
session = config.get_oa_session()
|
||
except Exception as exc: # noqa: BLE001
|
||
raise RuntimeError(
|
||
f"OA 登录态不可用:{exc}。请先在壳子「个人中心 → 平台账号」完成 OA 登录后重试。") from exc
|
||
session.headers.update({"User-Agent": UA})
|
||
return session
|
||
|
||
|
||
def _hr_session():
|
||
"""获取底座注入的共享 HR 会话(壳子运行前已按账号自动补登)。"""
|
||
try:
|
||
return config.get_session()
|
||
except Exception as exc: # noqa: BLE001
|
||
raise RuntimeError(f"HR 登录态不可用:{exc}。请先在壳子登录 HR 平台后重试。") from exc
|
||
|
||
|
||
def _get_with_retry(session, url, desc):
|
||
"""OA 页面 GET(全局重试 3 次)。"""
|
||
last_exc = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
resp = session.get(url, 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 _current_user_id(session):
|
||
"""当前 OA 登录账号的 EKP Id(getTodo.targets 必需)。"""
|
||
global _USER_ID
|
||
if _USER_ID:
|
||
return _USER_ID
|
||
resp = _get_with_retry(session, OA_HELP_URL, "OA当前账号")
|
||
m = CURRENT_USER_RE.search(resp.text or "")
|
||
if not m:
|
||
raise RuntimeError("未能从 OA 页面取到 CurrentUserId")
|
||
_USER_ID = m.group(1)
|
||
return _USER_ID
|
||
|
||
|
||
# ---------- 待办 WebService ----------
|
||
def _soap_call(session, op, inner, desc):
|
||
"""调用待办 WebService,返回 (returnState, message)。"""
|
||
body = _SOAP_ENV.format(op=op, ns=OA_WS_NS, inner=inner)
|
||
last_exc = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
resp = session.post(OA_WS_URL, data=body.encode("utf-8"), timeout=60,
|
||
headers={"Content-Type": "text/xml;charset=UTF-8",
|
||
"SOAPAction": ""})
|
||
resp.raise_for_status()
|
||
ret = ET.fromstring(resp.text).find(".//return")
|
||
if ret is None:
|
||
raise RuntimeError(f"无 return 节点:{(resp.text or '')[:200]}")
|
||
return ret.findtext("returnState"), ret.findtext("message") or ""
|
||
except (requests.RequestException, ET.ParseError, RuntimeError) 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, uid="", label=""):
|
||
"""getTodo 分页拉指定人员的待办(appName=EHR)-> 按 FLOW_TITLE 过滤 -> [{...doc}]。"""
|
||
who = label or "当前账号"
|
||
targets = escape(json_dumps({"Id": uid or _current_user_id(session)},
|
||
separators=(",", ":")))
|
||
cond = escape(json_dumps([{"appName": OA_APP_NAME}], separators=(",", ":")))
|
||
rows = []
|
||
for pageno in range(1, MAX_OA_PAGES + 1):
|
||
inner = (f"<targets>{targets}</targets>"
|
||
f"<type>{OA_TODO_TYPE_ALL}</type>"
|
||
f"<pageNo>{pageno}</pageNo>"
|
||
f"<rowSize>{PAGE_SIZE}</rowSize>"
|
||
f"<otherCond>{cond}</otherCond>")
|
||
state, msg = _soap_call(session, "getTodo", inner, f"OA待办第{pageno}页")
|
||
if state != "2":
|
||
raise RuntimeError(f"getTodo 返回异常 state={state}:{msg[:200]}")
|
||
data = json_loads(msg or "{}")
|
||
rows.extend(data.get("docs") or [])
|
||
if pageno >= int(data.get("pageCount") or 1):
|
||
break
|
||
hits = [r for r in rows if FLOW_TITLE in str(r.get("subject") or "")]
|
||
_log(f"[OA] {who} 待办共 {len(rows)} 条,其中「{FLOW_TITLE}」{len(hits)} 条")
|
||
return hits
|
||
|
||
|
||
def scan_oa_todos(session):
|
||
"""逐人扫描改签待办(人资号 + NAME_TO_UID 全部成员),返回 [(owner, todo)]。
|
||
|
||
只看人资号自己的待办会漏掉历史残留:流程一旦把人资号那条销掉,该流程就再也
|
||
发现不了,而其他人的同名待办还挂在各自列表里。所以要按人扫全。
|
||
"""
|
||
owners = [("当前账号", _current_user_id(session))]
|
||
owners += list(NAME_TO_UID.items())
|
||
out, seen_uid, seen_mid = [], set(), set()
|
||
for label, uid in owners:
|
||
if not uid or uid in seen_uid:
|
||
continue
|
||
seen_uid.add(uid)
|
||
try:
|
||
for todo in fetch_oa_todos(session, uid, label):
|
||
mid = str(todo.get("modelId") or "")
|
||
if mid and mid in seen_mid:
|
||
continue
|
||
seen_mid.add(mid)
|
||
out.append((label, todo))
|
||
except Exception as exc: # noqa: BLE001
|
||
_log(f"[警告] 扫描「{label}」待办失败:{type(exc).__name__}: {exc}")
|
||
_log(f"[OA] 合计发现「{FLOW_TITLE}」待办 {len(out)} 条(按 modelId 去重)")
|
||
return out
|
||
|
||
|
||
# ---------- 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):
|
||
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)。
|
||
|
||
销:endTime 非空(节点已结束,含 COMPLETED / OVERDUE)或流程已完结;
|
||
留:endTime 为空且任务在办(WAITING / ACCEPTED)。
|
||
"""
|
||
task_state = str(task.get("currentState") or "")
|
||
activity = str(task.get("activityName") or "")
|
||
ended = bool(str(task.get("endTime") or "").strip())
|
||
if ended:
|
||
return True, f"任务已结束({activity} {task_state or '空'})"
|
||
if process_state == PROCESS_DONE_STATE:
|
||
return True, f"流程已完结({activity} {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, model_id, todo_type=1):
|
||
"""deleteTodo 按 modelId 销办。返回 (returnState, message)。
|
||
|
||
returnState:2=成功(重复销办同样返回 2),0=该 modelId 无待办。
|
||
modelId 必须是「接收人自己的 HR taskId」,否则删不到别人的那条。
|
||
"""
|
||
inner = (f"<appName>{escape(OA_APP_NAME)}</appName>"
|
||
f"<modelName>{escape(OA_APP_NAME)}</modelName>"
|
||
f"<modelId>{escape(str(model_id))}</modelId>"
|
||
f"<optType>{DELETE_OPT_TYPE}</optType>"
|
||
f"<type>{int(todo_type or 1)}</type>")
|
||
state, msg = _soap_call(session, "deleteTodo", inner, f"销办{model_id}")
|
||
return state, msg or ""
|
||
|
||
|
||
def verify_deleted_for(session, uid, model_id):
|
||
"""按人回查:该 OA 人员 fdId 名下 modelId 的待办是否已清空。True/False/None(回查失败)。"""
|
||
targets = escape(json_dumps({"Id": uid}, separators=(",", ":")))
|
||
cond = escape(json_dumps([{"appName": OA_APP_NAME}, {"modelId": model_id}],
|
||
separators=(",", ":")))
|
||
inner = (f"<targets>{targets}</targets>"
|
||
f"<type>{OA_TODO_TYPE_ALL}</type>"
|
||
f"<pageNo>1</pageNo><rowSize>10</rowSize>"
|
||
f"<otherCond>{cond}</otherCond>")
|
||
state, msg = _soap_call(session, "getTodo", inner, f"回查{uid}/{model_id}")
|
||
if state != "2":
|
||
return None
|
||
return int(json_loads(msg or "{}").get("count") or 0) == 0
|
||
|
||
|
||
def _org_search(session, name):
|
||
"""OA 通讯录按姓名搜人员,返回 [{'id': fdId, 'name': 姓名, ...}]。"""
|
||
last_exc = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
resp = session.post(ORG_SEARCH_URL, timeout=30, data={
|
||
"s_bean": "organizationDialogSearch", "key": name,
|
||
"startWith": "", "orgType": "8", "times": "2"})
|
||
resp.raise_for_status()
|
||
return [dict(_ATTR_RE.findall(tag))
|
||
for tag in _DATA_TAG_RE.findall(resp.text or "")]
|
||
except requests.RequestException as exc:
|
||
last_exc = exc
|
||
if attempt < MAX_ATTEMPTS:
|
||
time.sleep(attempt)
|
||
_log(f"[警告] 通讯录查询「{name}」失败:{last_exc}")
|
||
return []
|
||
|
||
|
||
def resolve_uid(session, name, model_id):
|
||
"""姓名 -> OA fdId。先查 NAME_TO_UID;再查通讯录,同名多人时用「这条待办在谁名下」消歧。
|
||
|
||
必须在 deleteTodo 之前调用(销完就查不到归属了)。解析不出返回 ""。
|
||
"""
|
||
if not name:
|
||
return ""
|
||
if name in NAME_TO_UID:
|
||
return NAME_TO_UID[name]
|
||
if name in _UID_CACHE:
|
||
return _UID_CACHE[name]
|
||
cands = [h["id"] for h in _org_search(session, name)
|
||
if h.get("name") == name and h.get("id")]
|
||
uid = ""
|
||
if len(cands) == 1:
|
||
uid = cands[0]
|
||
elif len(cands) > 1:
|
||
hit = [c for c in cands if verify_deleted_for(session, c, model_id) is False]
|
||
if len(hit) == 1:
|
||
uid = hit[0]
|
||
if not uid:
|
||
_log(f"[回查跳过] 「{name}」未能唯一确定 OA 身份(同名候选{len(cands)}个)")
|
||
_UID_CACHE[name] = uid
|
||
return uid
|
||
|
||
|
||
# ---------- 主流程 ----------
|
||
def main(dry_run=None):
|
||
"""逐人扫描待办 -> 逐条反查 HR -> 判据成立按 modelId 销办。返回统计 dict。"""
|
||
dry_run = DRY_RUN if dry_run is None else bool(dry_run)
|
||
global _USER_ID
|
||
_USER_ID = ""
|
||
_UID_CACHE.clear()
|
||
|
||
oa = _oa_session()
|
||
todos = scan_oa_todos(oa)
|
||
if not todos:
|
||
_log("[汇总] 无「%s」待办,无事可做" % FLOW_TITLE)
|
||
return {"flows": 0, "tasks": 0, "deleted": 0, "notodo": 0, "kept": 0,
|
||
"unmapped": 0, "failed": 0, "verified": 0, "verify_bad": 0,
|
||
"verify_skipped": 0}
|
||
|
||
hr = _hr_session()
|
||
stats = {"flows": 0, "tasks": 0, "deleted": 0, "notodo": 0, "kept": 0,
|
||
"unmapped": 0, "failed": 0, "verified": 0, "verify_bad": 0,
|
||
"verify_skipped": 0}
|
||
|
||
# 逐条待办:反查 HR 任务 + 流程状态 -> 判据 -> 按 modelId 销办
|
||
# (不再枚举流程全部任务:覆盖性由逐人扫描保证,枚举会产生大量空跑)
|
||
pstate_cache = {}
|
||
hit_pids = set()
|
||
for owner, todo in todos:
|
||
title = str(todo.get("subject") or "")
|
||
tid = str(todo.get("modelId") or "")
|
||
try:
|
||
if not tid:
|
||
stats["unmapped"] += 1
|
||
_log(f"[跳过] {title} | {owner} | 待办无 modelId")
|
||
continue
|
||
task = query_hr_task(hr, tid)
|
||
if not task:
|
||
stats["unmapped"] += 1
|
||
_log(f"[跳过] {title} | {owner} | taskId={tid} | HR 查不到该任务")
|
||
continue
|
||
pid = str(task.get("processId") or "")
|
||
if not pid:
|
||
stats["unmapped"] += 1
|
||
_log(f"[跳过] {title} | {owner} | taskId={tid} | HR 任务无 processId")
|
||
continue
|
||
if pid not in pstate_cache:
|
||
pstate_cache[pid] = query_process_state(hr, pid)
|
||
should, reason = decide(task, pstate_cache[pid])
|
||
if not should:
|
||
stats["kept"] += 1
|
||
continue
|
||
stats["tasks"] += 1
|
||
if dry_run:
|
||
_log(f"[试算] {title} | {owner} | {reason} -> modelId={tid}")
|
||
continue
|
||
tname = str(task.get("participantName") or owner)
|
||
uid = resolve_uid(oa, tname, tid) if VERIFY_AFTER_DELETE else ""
|
||
state, msg = delete_todo(oa, tid)
|
||
if state == "2":
|
||
stats["deleted"] += 1
|
||
hit_pids.add(pid)
|
||
elif state == "0":
|
||
stats["notodo"] += 1
|
||
else:
|
||
stats["failed"] += 1
|
||
_log(f"[失败] {title} | 参与人={tname} | returnState={state} {msg[:120]}")
|
||
continue
|
||
_log(f"[销办] {title} | 参与人={tname} | {reason}")
|
||
if not VERIFY_AFTER_DELETE:
|
||
continue
|
||
if not uid:
|
||
stats["verify_skipped"] += 1
|
||
continue
|
||
checked = verify_deleted_for(oa, uid, tid)
|
||
if checked is True:
|
||
stats["verified"] += 1
|
||
elif checked is False:
|
||
stats["verify_bad"] += 1
|
||
_log(f"[回查异常] {title} | 参与人={tname}({uid}) | 待办仍在")
|
||
else:
|
||
stats["verify_skipped"] += 1
|
||
except Exception as exc: # noqa: BLE001
|
||
stats["failed"] += 1
|
||
_log(f"[失败] {title} | {owner} | {type(exc).__name__}: {exc}")
|
||
|
||
stats["flows"] = len(hit_pids)
|
||
_log("[汇总] 实际清空的流程={} 应销待办={} 已销={} 无待办={} 保留={} 跳过={} 失败={}"
|
||
" | 回查通过={} 回查残留={} 回查跳过={}{}".format(
|
||
stats["flows"], stats["tasks"], stats["deleted"], stats["notodo"],
|
||
stats["kept"], stats["unmapped"], stats["failed"],
|
||
stats["verified"], stats["verify_bad"], stats["verify_skipped"],
|
||
"(试算模式,未销办)" if dry_run else ""))
|
||
return stats
|