feat: 新增改签离职电子签OA待办对账销办脚本

新增步骤7脚本,实现OA待办对账销办逻辑:
1. 解析OA待办链路由fdId获取HR任务ID
2. 核对任务/流程状态,仅销办COMPLETED状态的待办
3. 校验账号权限,仅处理当前人资账号待办
4. 支持试算模式,避免误操作
同时更新XQ0035转正流程规则,将分支1回填条件从"到期能否考核通过=能"调整为"人员处理意见=直接离职/无需处理",并更新XQ0037合同模板逻辑,为超龄人员配置专用合同模板组合
This commit is contained in:
2026-10-22 13:33:57 +08:00
parent 18f3fcd11b
commit 9fd687ada8
11 changed files with 360 additions and 202 deletions
@@ -269,15 +269,16 @@ DEFER_MONTHS = 1 # 到期日顺延月数
# AI表格名单筛选规则(业务确认):
# 人员处理意见 = 离职后再入职 且 人资是否处理 未填/非「是/否」(分支1回填「否」后不再进入名单)
AITABLE_OPINION_FIELD = "人员处理意见"
AITABLE_TARGET_OPINION = "离职后再入职" # 人员处理意见 目标值
# 分支1(无需离职+入职处理):人员处理意见 = 直接离职 / 无需处理 → 人资是否处理 直接回填「否」(防遗漏)
AITABLE_NO_NEED_OPINIONS = ("直接离职", "无需处理")
AITABLE_DONE_FIELD = "人资是否处理" # 回填字段:处理标记(singleSelect)
AITABLE_DONE_VALUE = "是"
AITABLE_PUSH_DATE_FIELD = "离职推送时间" # 回填字段:离职电子签流程实际发起日期(date,毫秒时间戳)
AITABLE_CONTRACT_UNIT_FIELD = "合同签署单位" # 新签合同:合同签署单位(门店/公司名,驱动 si_area;由新签脚本读取)
AITABLE_NEW_PUSH_DATE_FIELD = "新合同推送日期" # 回填字段:新签合同后写入操作当天(date;由新签脚本回填)
# 规则:到期能否考核通过 = 能 → 无需离职+入职处理,人资是否处理 直接回填「否」(防遗漏)
AITABLE_PASS_FIELD = "到期能否考核通过"
AITABLE_PASS_VALUE = "能"
AITABLE_CANNOT_VALUE = "不能" # 分支2前置:到期能否考核通过 未填写 → 先回填「不能」再进入处理
AITABLE_NO_DONE_VALUE = "否"
@@ -1439,12 +1440,12 @@ def fetch_aitable_targets(records=None):
targets = []
for rec in records:
fields = rec.get("fields") or {}
opinion = _aitable_opt_name(fields.get("人员处理意见"))
done = _aitable_opt_name(fields.get("人资是否处理"))
opinion = _aitable_opt_name(fields.get(AITABLE_OPINION_FIELD))
done = _aitable_opt_name(fields.get(AITABLE_DONE_FIELD))
if opinion != AITABLE_TARGET_OPINION:
continue
if done in (AITABLE_DONE_VALUE, AITABLE_NO_DONE_VALUE):
# 是=已处理;否=分支1回填(到期能否考核通过=能,无需离职+入职处理)——两者都不再进入名单
# 是=已处理;否=分支1回填(人员处理意见=直接离职/无需处理,无需离职+入职处理)——两者都不再进入名单
continue
base_code = str(fields.get("员工工号") or "").strip()
if not base_code:
@@ -1464,7 +1465,7 @@ def fetch_aitable_targets(records=None):
def mark_aitable_no(record_ids):
"""把 AI表格对应行「人资是否处理」回填为「否」(到期能否考核通过=能,无需离职+入职处理)。
"""把 AI表格对应行「人资是否处理」回填为「否」(人员处理意见=直接离职/无需处理,无需离职+入职处理)。
幂等分批;仅由 main() 在读取名单前调用,作为防遗漏兜底。
@@ -1925,7 +1926,7 @@ def main(tasks=None, output_path=None, use_aitable=True, write_back=True):
人员处理意见=离职后再入职 且 人资是否处理 未填 的名单,按需求单固定参数提交变更:
延期转正、新试用期 1 个月、新到期日=原始到期日顺延 1 个月(自动计算)。
前置回填(读取名单前,防遗漏):
① 到期能否考核通过=能 → 「人资是否处理」直接回填「否」(无需离职+入职处理,分支1);
① 人员处理意见=直接离职/无需处理 → 「人资是否处理」直接回填「否」(无需离职+入职处理,分支1);
② 人员处理意见=离职后再入职 且 到期能否考核通过未填写 → 先回填「不能」再进入处理(分支2前置)。
use_aitable: 是否启用 AI表格名单兜底(默认 True)
write_back: 是否按需求回填规则回写 AI表格(默认 True)——
@@ -1955,25 +1956,25 @@ def main(tasks=None, output_path=None, use_aitable=True, write_back=True):
ret = {"results": results,
"message": f"共 {len(results)} 条,成功 {sum(1 for r in results if r['status']=='成功')} 条"}
elif use_aitable:
# AI表格名单兜底:读取 -> 前置回填(分支1「能→否」、分支2「未填→不能」)-> 再对
# AI表格名单兜底:读取 -> 前置回填(分支1「直接离职/无需处理→否」、分支2「未填→不能」)-> 再对
# 「离职后再入职」名单逐条处理(新到期日=原始到期日顺延1个月,自动计算)-> 环节全成才回填
session = _build_session()
records = fetch_aitable_records()
# 分支1:到期能否考核通过=能 → 无需离职+入职处理,人资是否处理直接回填「否」(防遗漏)
# 分支1:人员处理意见=直接离职/无需处理 → 无需离职+入职处理,人资是否处理直接回填「否」(防遗漏)
no_done_ids = []
for rec in records:
f = rec.get("fields") or {}
if (_aitable_opt_name(f.get(AITABLE_PASS_FIELD)) == AITABLE_PASS_VALUE
if (_aitable_opt_name(f.get(AITABLE_OPINION_FIELD)) in AITABLE_NO_NEED_OPINIONS
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)
logger.info("人员处理意见=直接离职/无需处理 自动回填「否」:成功 %d 条,失败 %d 条", nok, nfail)
# 分支2前置:人员处理意见=离职后再入职 且 到期能否考核通过未填写 → 先回填「不能」再进入处理
cannot_ids = []
for rec in records:
f = rec.get("fields") or {}
if (_aitable_opt_name(f.get("人员处理意见")) == AITABLE_TARGET_OPINION
if (_aitable_opt_name(f.get(AITABLE_OPINION_FIELD)) == AITABLE_TARGET_OPINION
and not _aitable_opt_name(f.get(AITABLE_PASS_FIELD))
and _aitable_opt_name(f.get(AITABLE_DONE_FIELD)) != AITABLE_DONE_VALUE):
cannot_ids.append(rec.get("id"))
@@ -7,7 +7,8 @@
2. 匹配「已发起名单」sheet 拿现单位/现四级部门/现职位序列/现岗位
3. 计算合同期限(超龄用工不分类型统一 12 个月;未达龄按序列 12/36 月)、起止日期、
签署单位(金色湖畔事业部特殊判断;后浪新天地LIFE+主题会馆按现岗位细分
(餐饮)/(非餐饮),2026-10-16 拍板)、新合同模板(按序列选劳动合同档 + 廉政协议 + 放弃社保申明)
(餐饮)/(非餐饮),2026-10-16 拍板)、新合同模板(未达龄按序列选劳动合同档 + 廉政协议
+ 放弃社保申明;已达龄按员工取超龄人员用工协议 + 超龄专用保密/廉政/食品安全承诺)
4. 未达龄但按期限签会超退休日时:实际开始日到退休日 > 3 个月 -> 直接签至退休日;
<= 3 个月才写「改签异常名单.xlsx」并跳过(2026-10-21 调整);
签署单位字典未命中的写入「改签异常名单.xlsx」并跳过;已达法定退休年龄的不算异常,正常走流程(统一签 12 个月)
@@ -34,9 +35,9 @@ for _p in (_XQ35, _SHARE, HERE):
sys.path.insert(0, _p)
from step2_sign_new_contract import ( # noqa: E402
HR_BASE_URL, SEQUENCE_1YEAR_KEYWORDS, _defer_months, _request_retry,
_retire_date, _unit_set_detail, _unit_set_id_by_name, houlang_unit_name,
query_process_tasks)
HR_BASE_URL, SEQUENCE_1YEAR_KEYWORDS, TREATY_TYPE_OVERAGE, _defer_months,
_new_contract_template_ids, _request_retry, _retire_date, _unit_set_detail,
_unit_set_id_by_name, houlang_unit_name, query_process_tasks)
from step2_transfer_initiate import ( # noqa: E402
TARGET_SHEET, _hr_session, load_pending_list, remove_pending)
@@ -58,6 +59,13 @@ TPL_LABOR_SERV = "95d5c603-a9e3-4ae4-b48c-927aeeed6128" # 1.1 劳动合同(
TPL_LABOR_TECH = "8c38d933-e967-4eb7-8541-ad2d78374d8c" # 1.2 劳动合同(中国技师)
TPL_INTEGRITY = "b269d6d6-51ff-4da9-bb0a-8a615890385d" # 4.1 廉政协议+知悉确认
TPL_SOCIAL = "3cd64878-0261-4ebc-ae03-e2d68bfca8cc" # 6.0 自愿放弃社会保险申明
# 已达法定退休年龄(超龄/退休返聘):超龄人员用工协议 + 超龄专用附件
# 优先按员工实时查(rf_hr_contract_template_select_sp_cq37du,与页面默认一致),
# 以下为查询失败时的兜底组合
TPL_OVERAGE_AGREEMENT = "09657eb9-2855-4d6c-ae4a-4f83045845ab" # 2.0 超龄人员用工协议
TPL_OVERAGE_SECRECY = "bfd69e52-d2db-4a17-a8b3-03e56df4b700" # 3.1 保密协议(超龄人员专用)
TPL_INTEGRITY_OVERAGE = "b61153a1-af58-4e51-a7a8-25b0ca8267d0" # 5.0 廉政协议(超龄人员专用)
TPL_FOOD_OVERAGE = "f53dca01-8bd9-4ea3-b3b2-adbdd0bcfdce" # 7.3 食品安全生产承诺书(超龄人员专用)
UNIT_GOLDEN_LAKESIDE = "金色湖畔事业部" # 特殊签署单位判断的现单位
UNIT_SHIQIAOPU = "石桥铺会馆"
UNIT_LAKESIDE_COMPANY = "金色湖畔企业管理公司"
@@ -288,11 +296,18 @@ def calc_plan(session, biz, roster_row):
# 期限:超龄用工(已达法定退休年龄)不分类型统一签 12 个月(2026-10-13 拍板);
# 未达龄按序列:服务/技师序列 12 个月,其他 36 个月(与 XQ0035 一致)
# 合同类型/模板:达龄必须走超龄人员用工协议(ext_8),不能沿用流程预填的劳动合同
if overage:
months = 12
_log(f"[超龄] 已达法定退休年龄({retire:%Y-%m-%d}),不分类型统一签 12 个月")
treaty_type = TREATY_TYPE_OVERAGE
templates = (_new_contract_template_ids(session, str(biz.get("staff_id") or ""))
or ",".join([TPL_OVERAGE_AGREEMENT, TPL_OVERAGE_SECRECY,
TPL_INTEGRITY_OVERAGE, TPL_FOOD_OVERAGE]))
_log(f"[超龄] 已达法定退休年龄({retire:%Y-%m-%d}),签超龄人员用工协议 12 个月")
else:
months = 12 if any(k in seq_name for k in SEQUENCE_1YEAR_KEYWORDS) else 36
treaty_type = biz.get("treaty_type") or "1"
templates = ",".join([_labor_template_id(seq_name), TPL_INTEGRITY, TPL_SOCIAL])
# 日期:起始=实际离职日期次日;终止=起始+N个月-1天(前端 calculate 同款)
lo = str(biz.get("leaveoffice_time") or "")[:10]
@@ -333,13 +348,14 @@ def calc_plan(session, biz, roster_row):
plan = {
"months": months,
"treaty_type": treaty_type,
"start": f"{start:%Y-%m-%d}",
"end_time": f"{end_time:%Y-%m-%d}",
"end": f"{end:%Y-%m-%d}",
"unit_name": unit_name,
"si_area": si_area,
"license_name": license_name,
"templates": ",".join([_labor_template_id(seq_name), TPL_INTEGRITY, TPL_SOCIAL]),
"templates": templates,
"push_time": f"{today:%Y-%m-%d}",
}
return plan, None
@@ -370,7 +386,7 @@ def submit_task(session, task, biz, plan):
payload.update({
"is_new_sign": biz.get("is_new_sign") or "1",
"trigger_type": biz.get("trigger_type") or "1",
"treaty_type": biz.get("treaty_type") or "1",
"treaty_type": plan.get("treaty_type") or biz.get("treaty_type") or "1",
"contract_type": biz.get("contract_type") or "0",
"contract_deadline": str(plan["months"]),
"contract_start_date": plan["start"],
@@ -0,0 +1,254 @@
# -*- 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()