feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -0,0 +1,681 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: step3_sign_effect_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-10-09
|
||||
@Description: XQ0035 服务岗转正不通过电子签(离职+入职)——签署生效复核分支(影刀单文件自包含,独立排程 10:00)。
|
||||
与主流程 step1_trial_period_change.py / 新签分支 step2_sign_new_contract.py 完全解耦(登录/AI表格读写等公共逻辑各自内置)。
|
||||
|
||||
选择条件(钉钉 AI表格「门店服务岗转正跟进-周更新」,aa.md 签署生效复核分支):
|
||||
人资是否处理 = 是 且 签署跟进 ≠ 是。
|
||||
同时覆盖自动新签与超龄人工新签两种情形(超龄人工新签生效后同样自动回填「签署跟进=是」)。
|
||||
|
||||
执行链(每条记录):
|
||||
1. 到合同台账【生效中合同】按工号查询(返回全部匹配行,含合同起始日期);
|
||||
2. 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
|
||||
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
|
||||
新合同起始日必然晚于试用期到期日(离职后才签);
|
||||
3. 查到起始日期晚于试用期到期日期的生效中合同 -> 交叉验证电子签状态:
|
||||
WeProcess 查该员工是否存在未办结的「改签离职电子签」流程(title 含「{姓名}-改签离职电子签」),
|
||||
有 -> 台账先行/流程未走完,跳过等下次;无 -> 双证据齐备;
|
||||
4. 双证据通过 -> 新合同已签署生效,AI表格回填「签署跟进 = 是」;
|
||||
5. 只查到旧合同(起始日期 <= 试用期到期日期,离职解除尚未生效)或查无 ->
|
||||
尚未生效,跳过,等下一次运行再检测。
|
||||
|
||||
接口清单(抓包确认,登录态基于共享 HR cookies):
|
||||
0. 查生效中合同:POST /RedseaPlatform/hrRoster/614ffe05-b4f1-11ea-b588-14187743d052/queryRealTimeData.mc
|
||||
(menuName=合同台账,tableId=assemble-hr_staff_contract;行含 hr_staff_contract.contract_start_date)
|
||||
0b. 电子签办结交叉验证:POST /RedseaPlatform/WeProcess.mc?method=getProcessAndData
|
||||
(title=改签离职电子签;仅含运行中流程的活动任务,title 含「{姓名}-改签离职电子签流程」)
|
||||
|
||||
⚠️ 安全提示:本脚本回填钉钉 AI表格(签署跟进=是),执行前请务必核对员工与参数。
|
||||
登录态直接读取共享 hr_cookies.json(由「37duHR登录」指令写入),缺失/失效时友好提示,不自动补登。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du签署生效复核」,main() 关键字传参;从 AI表格名单读取待复核记录。
|
||||
2. 业务脚本:importlib 加载本模块调用 main(...)。
|
||||
|
||||
全局变量:messages(结果摘要文本列表,供「37du钉钉群机器人推送」指令逐条发送)
|
||||
|
||||
【插件版移植说明】本模块由影刀版原样移植为执行机插件 data 层(xq0035):
|
||||
- HR 会话改经底座注入(config.get_session -> ctx.get_session("hr")),不再直读共享 cookies 文件;
|
||||
- print/logger 日志由插件入口统一改道 ctx.log 推送前端。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .. import config
|
||||
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
# ---------- 合同台账-生效中合同 Tab ----------
|
||||
ROSTER_ID_ACTIVE_CONTRACT = "614ffe05-b4f1-11ea-b588-14187743d052"
|
||||
TABLE_ID_CONTRACT = "assemble-hr_staff_contract"
|
||||
QUERY_ACTIVE_CONTRACT_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
|
||||
f"{ROSTER_ID_ACTIVE_CONTRACT}/queryRealTimeData.mc")
|
||||
|
||||
# ---------- 流程实例查询(电子签办结交叉验证;与 step2_sign_new_contract.py 同源抓包) ----------
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
# 完善信息表单(改签离职电子签流程;读取流程表单业务数据 base_code 用,与 step1 同源)
|
||||
WORKFORM_FORM_ID = "5b904505-c319-4b29-8b0b-d2c887b2469a"
|
||||
GET_BUSINESS_DATE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=getBusinessDate"
|
||||
# WeProcess 分页遍历(交叉验证不再受单页条数截断)
|
||||
WF_PAGE_SIZE = 100
|
||||
MAX_WF_PAGES = 50
|
||||
|
||||
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
|
||||
CURRENT_USER_ID = "178b0efa-8a65-11f1-a7d9-000c296f9469"
|
||||
CURRENT_USER_NAME = "人资专用号"
|
||||
CURRENT_STAFF_ID = "1342173e-36cf-4160-8826-6b17d7d084a4"
|
||||
CURRENT_ROLE_IDS = "POST_SYS_ADMIN,renshi"
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
|
||||
# ==================== 钉钉 AI表格(名单来源:门店服务岗转正跟进-周更新) ====================
|
||||
# 配置直接内置(影刀环境不读取 .env,统一在代码内固化,保证本地/影刀行为一致)
|
||||
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
|
||||
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
|
||||
AITABLE_BASE_ID = "YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA"
|
||||
AITABLE_TABLE_ID = "uchjxPW"
|
||||
AITABLE_OPERATOR_UNIONID = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号(固定操作人,勿用测试号)
|
||||
|
||||
# AI表格字段(生效复核分支用;AI表格已有「签署跟进」列,无需加列——已确认事项)
|
||||
AITABLE_DONE_FIELD = "人资是否处理"
|
||||
AITABLE_DONE_VALUE = "是"
|
||||
AITABLE_SIGN_FOLLOW_FIELD = "签署跟进"
|
||||
AITABLE_SIGN_FOLLOW_VALUE = "是"
|
||||
AITABLE_TRIAL_END_FIELD = "试用期到期日期"
|
||||
|
||||
# 钉钉 AI表格接口(notable OpenAPI,头 x-acs-dingtalk-access-token;operatorId=操作人 unionId)
|
||||
AITABLE_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
|
||||
AITABLE_LIST_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}/"
|
||||
f"sheets/{AITABLE_TABLE_ID}/records/list")
|
||||
AITABLE_UPDATE_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}/"
|
||||
f"sheets/{AITABLE_TABLE_ID}/records")
|
||||
AITABLE_PAGE_SIZE = 100 # records/list 单页最大 100
|
||||
AITABLE_WRITE_BATCH = 20 # 回写单次条数(≤100 即可,保守分批)
|
||||
AITABLE_TOKEN_TTL = 3600 # 钉钉 accessToken 有效期兜底
|
||||
|
||||
# ---------- 项目级重试(最大 3 次,三次失败后再记录错误) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
RETRY_DELAY_BASE = 2.0
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(与主脚本同源实现) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""自定义字符表 Base64 编码(索引0~63 数据字符,64('7')为填充字符)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def _encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery(JSON->URI编码->自定义Base64+盐值->首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
def _build_like_condition(field, value):
|
||||
"""构造 like 查询条件(等价前端 base_code like 抓包格式)。"""
|
||||
return {
|
||||
"queryField": f"`{field}`",
|
||||
"leftBracket": "",
|
||||
"queryType": "like",
|
||||
"queryValue": str(value),
|
||||
"queryText": str(value),
|
||||
"rightBracket": "",
|
||||
"logic": "AND",
|
||||
"inputType": "text",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效。"""
|
||||
|
||||
|
||||
def _build_session():
|
||||
"""经底座注入的共享 HR 登录态构建会话(壳子运行前已按账号自动补登)。"""
|
||||
try:
|
||||
return config.get_session()
|
||||
except LoginRequiredError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise LoginRequiredError(
|
||||
f"HR 登录态不可用:{exc}。请先在壳子登录 HR 平台后重试。") from exc
|
||||
|
||||
|
||||
def _is_expired(text):
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def _request_retry(method, url, session=None, retries=MAX_ATTEMPTS, **kwargs):
|
||||
"""项目级重试:POST 请求,最大 MAX_ATTEMPTS 次;登录态失效不重试直接抛 LoginRequiredError。"""
|
||||
headers = dict(kwargs.pop("headers", XHR_HEADERS))
|
||||
last_exc = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
resp = session.post(url, headers=headers, timeout=30, **kwargs)
|
||||
text = resp.text
|
||||
if _is_expired(text):
|
||||
raise LoginRequiredError(
|
||||
f"HR 登录态已失效({url} 返回非 JSON)。请先重新调用「37duHR登录」指令。")
|
||||
return resp
|
||||
except LoginRequiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= retries:
|
||||
break
|
||||
logger.warning("请求 %s 第 %d 次失败:%s,%.1f 秒后重试", url, attempt, e,
|
||||
RETRY_DELAY_BASE * attempt)
|
||||
time.sleep(RETRY_DELAY_BASE * attempt)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def _get_date_params():
|
||||
"""生成查询接口所需的当月/上月/当年首月参数。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _build_query_params(roster_id, table_id, common_query, menu_name="合同台账"):
|
||||
"""构造 queryRealTimeData.mc 完整参数(menu_name 按台账传入)。"""
|
||||
now_ms = str(int(time.time() * 1000))
|
||||
return {
|
||||
"menuName": menu_name,
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"clickFlag": "true",
|
||||
"_t": now_ms,
|
||||
"in_use": "1",
|
||||
"commonQuery": common_query,
|
||||
"newCondition": "",
|
||||
"urlConditions": f"_t:{now_ms}#clickFlag:true#treePermitType:permit#useSealTreeData:0#menuName:{menu_name}#_t:{now_ms}#",
|
||||
"exportConfig": "",
|
||||
"tableId": table_id,
|
||||
"rosterId": roster_id,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": CURRENT_USER_ID,
|
||||
"currentRoleIds": CURRENT_ROLE_IDS,
|
||||
"currentStaffId": CURRENT_STAFF_ID,
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 生效中合同查询(含起始日期,判新旧合同) ====================
|
||||
def query_active_contracts(session, base_code):
|
||||
"""按工号在【劳动关系→合同台账→生效中合同】Tab 查询所有匹配行。
|
||||
|
||||
Returns:
|
||||
list[dict]:{contract_id, staff_name, contract_start_date, contract_end_date};无匹配返回 []
|
||||
"""
|
||||
params = _build_query_params(
|
||||
ROSTER_ID_ACTIVE_CONTRACT, TABLE_ID_CONTRACT,
|
||||
_encode_common_query([_build_like_condition("hr_staff_base.base_code", base_code)]),
|
||||
menu_name="合同台账")
|
||||
params.update(_get_date_params())
|
||||
resp = _request_retry("POST", QUERY_ACTIVE_CONTRACT_URL, session, data=params)
|
||||
datas = resp.json().get("datas") or []
|
||||
rows = []
|
||||
for row in datas:
|
||||
if str(row.get("hr_staff_base.base_code")) == str(base_code):
|
||||
rows.append({
|
||||
"contract_id": row.get("hr_staff_contract.contract_id") or "",
|
||||
"staff_name": row.get("hr_staff_base.staff_name") or "",
|
||||
"contract_start_date": row.get("hr_staff_contract.contract_start_date") or "",
|
||||
"contract_end_date": row.get("hr_staff_contract.contract_end_date") or "",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def get_flow_business_data(session, business_key):
|
||||
"""读流程表单业务数据(getBusinessDate,与 step1 同款);失败返回空 dict。"""
|
||||
try:
|
||||
resp = _request_retry("POST", GET_BUSINESS_DATE_URL, session,
|
||||
data={"businessKey": business_key, "formId": WORKFORM_FORM_ID})
|
||||
d = resp.json()
|
||||
result = d.get("result")
|
||||
if isinstance(result, str):
|
||||
result = json.loads(result)
|
||||
return result if isinstance(result, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def has_running_esign_process(session, base_code, staff_name):
|
||||
"""电子签办结交叉验证:该员工是否存在未办结的「改签离职电子签」流程。
|
||||
|
||||
分页遍历运行中流程(每页 WF_PAGE_SIZE=100,上限 MAX_WF_PAGES 页,不再受首页条数截断),
|
||||
先用标题「{姓名}-改签离职电子签」粗筛(低开销第一关),再读流程表单业务数据按 base_code
|
||||
精确确认(防重名误伤:重名同事的流程不会挡住本人回填)。
|
||||
WeProcess 列表(title=改签离职电子签)仅含运行中流程的活动任务行,行 title 形如
|
||||
「门店 岗位 {姓名}-改签离职电子签流程」;已办结流程或从未发起(纯人工新签)均查不到。
|
||||
因此「查无匹配行」⟺ 流程已办结/未发起 ⟺ 交叉验证通过(保守方向:宁跳过不误回填;
|
||||
表单读取失败无法排除时仍按本人流程未办结处理,保持保守)。
|
||||
|
||||
Returns:
|
||||
(bool 是否存在未办结流程, str 描述信息)
|
||||
"""
|
||||
key = f"{(staff_name or '').strip()}-改签离职电子签"
|
||||
for page in range(MAX_WF_PAGES):
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": "改签离职电子签",
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]",
|
||||
"start": str(page * WF_PAGE_SIZE), "pageNo": str(page + 1),
|
||||
"pageSize": str(WF_PAGE_SIZE),
|
||||
}
|
||||
resp = _request_retry("POST", WE_PROCESS_QUERY_URL, session, data=params)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) == "Nosession":
|
||||
raise LoginRequiredError(f"流程查询返回 Nosession:{d.get('meg') or '会话过期,请重新登录!'}")
|
||||
rows = d.get("jsonList") or d.get("datas") or []
|
||||
for m in rows:
|
||||
if key not in str(m.get("title") or ""):
|
||||
continue
|
||||
# 标题粗筛命中后按工号精确确认:重名员工的流程不会误伤本人
|
||||
biz = get_flow_business_data(session, str(m.get("businessKey") or ""))
|
||||
biz_code = str(biz.get("base_code") or "").strip()
|
||||
if biz and biz_code and biz_code != str(base_code).strip():
|
||||
continue
|
||||
# 工号相符或表单读取失败(无法排除)→ 保守判定为本人流程未办结
|
||||
desc = (f"流程未办结:{m.get('title')}(环节 {m.get('currentActivityName') or m.get('activityName')},"
|
||||
f"发起人 {m.get('createUserName') or '未知'} {m.get('startTime') or ''})")
|
||||
return True, desc
|
||||
if len(rows) < WF_PAGE_SIZE:
|
||||
break
|
||||
return False, "无未办结的改签离职电子签流程"
|
||||
|
||||
|
||||
# ==================== 日期工具 ====================
|
||||
def _to_date(val):
|
||||
"""统一为 date:支持毫秒时间戳 / datetime / Timestamp / yyyy-MM-dd 字符串;失败返回 None。"""
|
||||
if val is None or val == "":
|
||||
return None
|
||||
if isinstance(val, datetime):
|
||||
return val.date()
|
||||
if isinstance(val, pd.Timestamp):
|
||||
return val.date()
|
||||
if isinstance(val, (int, float)):
|
||||
try:
|
||||
return datetime.fromtimestamp(float(val) / 1000.0).date() # AI表格 date 字段为毫秒时间戳
|
||||
except (ValueError, OSError, OverflowError):
|
||||
return None
|
||||
s = str(val).strip().replace("/", "-")
|
||||
for fmt in ("%Y-%m-%d", "%Y-%m-%d %H:%M:%S"):
|
||||
try:
|
||||
return datetime.strptime(s[:19], fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 钉钉 AI表格:名单读取 + 回填 ====================
|
||||
_aitable_tok = {"at": "", "exp": 0.0}
|
||||
|
||||
|
||||
def _aitable_token():
|
||||
"""获取钉钉企业内部应用 accessToken(缓存到临近过期)。"""
|
||||
now = time.time()
|
||||
if _aitable_tok["at"] and _aitable_tok["exp"] > now + 60:
|
||||
return _aitable_tok["at"]
|
||||
resp = requests.post(AITABLE_TOKEN_URL,
|
||||
json={"appKey": DINGTALK_APP_KEY, "appSecret": DINGTALK_APP_SECRET},
|
||||
timeout=15)
|
||||
d = resp.json()
|
||||
at = d.get("accessToken", "")
|
||||
if not at:
|
||||
raise RuntimeError(f"钉钉 accessToken 获取失败:{d}")
|
||||
_aitable_tok["at"] = at
|
||||
_aitable_tok["exp"] = now + int(d.get("expireIn", AITABLE_TOKEN_TTL))
|
||||
return at
|
||||
|
||||
|
||||
def _aitable_headers():
|
||||
return {"x-acs-dingtalk-access-token": _aitable_token(),
|
||||
"Content-Type": "application/json"}
|
||||
|
||||
|
||||
def _aitable_request(method, url, params=None, json_body=None, retries=MAX_ATTEMPTS):
|
||||
"""钉钉 AI表格接口请求(带项目级重试 3 次)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
resp = requests.request(method, url, headers=_aitable_headers(),
|
||||
params=params, json=json_body, timeout=20)
|
||||
d = resp.json()
|
||||
if d.get("code") not in (None, ""):
|
||||
raise RuntimeError(f"钉钉接口错误 {d.get('code')}: {d.get('message')}")
|
||||
return d
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= retries:
|
||||
break
|
||||
logger.warning("钉钉请求 %s %s 第 %d 次失败:%s,%.1f 秒后重试",
|
||||
method, url.split("/v1.0/")[-1], attempt, e,
|
||||
RETRY_DELAY_BASE * attempt)
|
||||
time.sleep(RETRY_DELAY_BASE * attempt)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def _aitable_opt_name(field_value):
|
||||
"""singleSelect 字段值 -> 选项名(记录值为 {"name": "...", "id": "..."})。"""
|
||||
if isinstance(field_value, dict):
|
||||
return field_value.get("name")
|
||||
return field_value
|
||||
|
||||
|
||||
def fetch_aitable_records():
|
||||
"""分页全量读取钉钉 AI表格原始记录(含所有字段),供筛选/回填复用。
|
||||
|
||||
Returns:
|
||||
list[dict]:原始 records 列表;失败抛 RuntimeError
|
||||
"""
|
||||
records, token = [], ""
|
||||
for _ in range(200): # 兜底上限(200 页 * 100 条)
|
||||
d = _aitable_request("POST", AITABLE_LIST_URL,
|
||||
params={"operatorId": AITABLE_OPERATOR_UNIONID},
|
||||
json_body={"maxResults": AITABLE_PAGE_SIZE, "nextToken": token})
|
||||
recs = d.get("records") or []
|
||||
records.extend(recs)
|
||||
if d.get("hasMore") and d.get("nextToken"):
|
||||
token = d["nextToken"]
|
||||
else:
|
||||
break
|
||||
return records
|
||||
|
||||
|
||||
def fetch_sign_effect_targets(records=None):
|
||||
"""从钉钉 AI表格筛选待生效复核名单(aa.md 签署生效复核分支选择条件)。
|
||||
|
||||
条件:人资是否处理 = 是 且 签署跟进 ≠ 是(同时覆盖自动新签与超龄人工新签两种情形)。
|
||||
|
||||
Returns:
|
||||
list[dict]:{record_id, base_code, staff_name, trial_end_date}
|
||||
"""
|
||||
records = records if records is not None else fetch_aitable_records()
|
||||
targets = []
|
||||
for rec in records:
|
||||
fields = rec.get("fields") or {}
|
||||
done = _aitable_opt_name(fields.get(AITABLE_DONE_FIELD))
|
||||
follow = _aitable_opt_name(fields.get(AITABLE_SIGN_FOLLOW_FIELD))
|
||||
if done != AITABLE_DONE_VALUE:
|
||||
continue
|
||||
if follow == AITABLE_SIGN_FOLLOW_VALUE:
|
||||
continue
|
||||
base_code = str(fields.get("员工工号") or "").strip()
|
||||
if not base_code:
|
||||
continue
|
||||
targets.append({
|
||||
"record_id": rec.get("id"),
|
||||
"base_code": base_code,
|
||||
"staff_name": str(fields.get("员工姓名") or "").strip(),
|
||||
"trial_end_date": fields.get(AITABLE_TRIAL_END_FIELD),
|
||||
})
|
||||
logger.info("生效复核选择:AI表格 %d 条,命中待复核 %d 条", len(records), len(targets))
|
||||
return targets
|
||||
|
||||
|
||||
def mark_sign_follow(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_SIGN_FOLLOW_FIELD: AITABLE_SIGN_FOLLOW_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 _set_glv(name, value):
|
||||
"""写入影刀全局变量;非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _build_messages(results):
|
||||
"""按结果类型构造钉钉群推送消息列表(成功/跳过各一条汇总)。"""
|
||||
ok = [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.get('staff_name') or ''}({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]
|
||||
messages.append("\n".join(lines))
|
||||
if not messages:
|
||||
messages = ["签署生效复核:无任务"]
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 单员工处理 ====================
|
||||
def process_one(session, task):
|
||||
"""复核单条记录的新合同是否已签署生效。
|
||||
|
||||
执行链(aa.md 签署生效复核分支):
|
||||
1) 生效中合同按工号查询(全部匹配行);
|
||||
2) 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
|
||||
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
|
||||
新合同起始日必然晚于试用期到期日(离职后才签);
|
||||
3) 查到起始日 > 试用期到期日的生效中合同 -> 新合同已签署生效,回填「签署跟进=是」;
|
||||
4) 只查到旧合同(起始日 <= 试用期到期日,离职解除尚未生效)或查无 -> 跳过,等下次运行。
|
||||
|
||||
Returns:
|
||||
dict {base_code, staff_name, status: 成功/跳过/失败, message, record_id}
|
||||
"""
|
||||
base_code = str(task["base_code"]).strip()
|
||||
result = {
|
||||
"base_code": base_code,
|
||||
"staff_name": task.get("staff_name") or "",
|
||||
"status": "跳过",
|
||||
"message": "",
|
||||
"record_id": task.get("record_id"),
|
||||
}
|
||||
trial_end = _to_date(task.get("trial_end_date"))
|
||||
if trial_end is None:
|
||||
result["status"] = "失败"
|
||||
result["message"] = "无法解析 AI表格「试用期到期日期」,无法判断新旧合同,请人工核查"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
contracts = query_active_contracts(session, base_code)
|
||||
if not contracts:
|
||||
result["message"] = "【生效中合同】查无记录(新合同尚未签署生效),跳过,等下一次运行"
|
||||
logger.info("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["staff_name"] = contracts[0].get("staff_name") or result["staff_name"]
|
||||
|
||||
for c in contracts:
|
||||
start = _to_date(c.get("contract_start_date"))
|
||||
if start and start > trial_end:
|
||||
# 交叉验证:台账虽显示新合同生效,仍确认无未办结的改签离职电子签流程
|
||||
# (防台账先行落行而流程实际未走完;宁跳过不误回填)
|
||||
pending, esign_desc = has_running_esign_process(session, base_code,
|
||||
result["staff_name"])
|
||||
if pending:
|
||||
result["message"] = (f"台账显示新合同生效(起始 {start.isoformat()}),但交叉验证未过:"
|
||||
f"{esign_desc},跳过,等下一次运行再检测")
|
||||
logger.info("【%s】⏳ %s", base_code, result["message"])
|
||||
return result
|
||||
result["status"] = "成功"
|
||||
result["message"] = (f"新合同已签署生效(起始 {start.isoformat()} > 试用期到期 "
|
||||
f"{trial_end.isoformat()};电子签交叉验证:{esign_desc}),"
|
||||
f"回填「签署跟进=是」")
|
||||
logger.info("【%s】✅ %s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
old = contracts[0]
|
||||
result["message"] = (f"生效中合同起始日 {old.get('contract_start_date') or '未知'} <= 试用期到期日"
|
||||
f" {trial_end.isoformat()}(旧合同,离职解除尚未生效),跳过,等下一次运行")
|
||||
logger.info("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 入口 ====================
|
||||
def main(records=None, write_back=True):
|
||||
"""影刀自定义指令入口「37du签署生效复核」(独立排程:新签脚本后,如 10:00)。
|
||||
|
||||
名单来源:钉钉 AI表格「门店服务岗转正跟进-周更新」——人资是否处理=是 且 签署跟进≠是。
|
||||
执行:生效中合同起始日 > 试用期到期日期 -> 新合同已签署生效 -> 回填「签署跟进=是」;
|
||||
只查到旧合同或查无 -> 跳过等下次。同时覆盖超龄人工新签的生效回填。
|
||||
write_back: 是否回填「签署跟进=是」(默认 True)。
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str, "results": [...]}
|
||||
"""
|
||||
try:
|
||||
session = _build_session()
|
||||
records = records if records is not None else fetch_aitable_records()
|
||||
targets = fetch_sign_effect_targets(records=records)
|
||||
if not targets:
|
||||
_set_glv("messages", ["签署生效复核:AI表格暂无待复核名单"])
|
||||
return {"success": True, "message": "签署生效复核:AI表格暂无待复核名单", "results": []}
|
||||
logger.info("生效复核待处理名单 %d 条,逐条执行……", len(targets))
|
||||
results = []
|
||||
for t in targets:
|
||||
r = process_one(session, t)
|
||||
results.append(r)
|
||||
# 回填:仅检测到新合同已生效的行写入「签署跟进=是」
|
||||
if write_back:
|
||||
done_ids = [r.get("record_id") for r in results
|
||||
if r["status"] == "成功" and r.get("record_id")]
|
||||
if done_ids:
|
||||
wok, wfail = mark_sign_follow(done_ids)
|
||||
logger.info("AI表格回填「签署跟进=是」:成功 %d 失败 %d", wok, wfail)
|
||||
else:
|
||||
logger.info("AI表格回填「签署跟进=是」:本次无新合同已生效的行")
|
||||
messages = _build_messages(results)
|
||||
_set_glv("messages", messages)
|
||||
ok_cnt = sum(1 for r in results if r["status"] == "成功")
|
||||
return {"success": True,
|
||||
"message": f"签署生效复核共 {len(results)} 条,成功 {ok_cnt} 条",
|
||||
"results": results}
|
||||
except LoginRequiredError as e:
|
||||
return {"success": False, "message": str(e), "results": []}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"签署生效复核执行异常:{e}", "results": []}
|
||||
Reference in New Issue
Block a user