本次提交主要包含以下内容: 1. 归档tests/hrbp目录下的旧版测试文件至tests/_app_蓝图版归档目录 2. 新增tests/_app_蓝图版归档/hrbp目录下的新版测试辅助脚本和测试用例 3. 新增雇主险场景下的WPS COM可行性验证脚本 4. 更新README.md中关于tests目录的说明,明确各子目录用途 5. 更新XQ0035工作流相关文件中的操作人UnionID,更换为人资专用号 6. 修复试用期变更脚本中日期转换的问题,确保AI表格时间戳正确转换为日期格式 7. 归档XQ0035工作流下的旧版测试脚本至测试归档目录
667 lines
30 KiB
Python
667 lines
30 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: sign_effect_check.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-10-09
|
||
@Description: XQ0035 服务岗转正不通过电子签(离职+入职)——签署生效复核分支(影刀单文件自包含,独立排程 10:00)。
|
||
与主流程 trial_period_change.py / 新签分支 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. 命令行:python sign_effect_check.py 直接运行(默认不执行,打印用法,避免误触线上写操作)。
|
||
3. 业务脚本:importlib 加载本模块调用 main(...)。
|
||
|
||
全局变量:messages(结果摘要文本列表,供「37du钉钉群机器人推送」指令逐条发送)
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
from datetime import date, datetime, timedelta
|
||
|
||
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()
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
_APP_DATA_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation')
|
||
SHARED_HR_COOKIE_FILE = os.path.join(_APP_DATA_DIR, '.sessions', 'hr_cookies.json')
|
||
|
||
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")
|
||
|
||
# ---------- 流程实例查询(电子签办结交叉验证;与 sign_new_contract.py 同源抓包) ----------
|
||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||
|
||
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
|
||
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 cookies 构造 requests 会话(仅注入 37du.co 域 cookies)。"""
|
||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||
raise LoginRequiredError(
|
||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": USER_AGENT,
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
})
|
||
for c in cookies or []:
|
||
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 _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 has_running_esign_process(session, staff_name):
|
||
"""电子签办结交叉验证:该员工是否存在未办结的「改签离职电子签」流程。
|
||
|
||
WeProcess 列表(title=改签离职电子签)仅含运行中流程的活动任务行,行 title 形如
|
||
「门店 岗位 {姓名}-改签离职电子签流程」;已办结流程或从未发起(纯人工新签)均查不到。
|
||
因此「查无匹配行」⟺ 流程已办结/未发起 ⟺ 交叉验证通过(保守方向:宁跳过不误回填)。
|
||
|
||
Returns:
|
||
(bool 是否存在未办结流程, str 描述信息)
|
||
"""
|
||
params = {
|
||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": "改签离职电子签",
|
||
"state": "", "startTime": "", "endTime": "",
|
||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||
"commonQuery": "[]", "start": "0", "pageNo": "1", "pageSize": "50",
|
||
}
|
||
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 []
|
||
key = f"{(staff_name or '').strip()}-改签离职电子签"
|
||
matched = [r for r in rows if key in str(r.get("title") or "")]
|
||
if not matched:
|
||
return False, "无未办结的改签离职电子签流程"
|
||
m = matched[0]
|
||
desc = (f"流程未办结:{m.get('title')}(环节 {m.get('currentActivityName') or m.get('activityName')},"
|
||
f"发起人 {m.get('createUserName') or '未知'} {m.get('startTime') or ''})")
|
||
return True, desc
|
||
|
||
|
||
# ==================== 日期工具 ====================
|
||
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, 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": []}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# 命令行独立运行时默认不执行(避免误触线上写操作),仅打印用法
|
||
print("本脚本为 XQ0035 签署生效复核分支(影刀指令「37du签署生效复核」,独立排程 10:00)。")
|
||
print("默认不自动执行线上写操作。请在影刀流程中调用 main() 使用:")
|
||
print(" 从钉钉 AI表格读取待复核名单(人资是否处理=是 且 签署跟进≠是),执行:")
|
||
print(" 生效中合同起始日 > 试用期到期日期 -> 新合同已签署生效 -> 回填「签署跟进=是」;")
|
||
print(" 只查到旧合同或查无 -> 跳过等下次。")
|
||
print("只读自检:python -c \"import importlib.util,sys; spec=importlib.util.spec_from_file_location('m',r'%s');"
|
||
% os.path.abspath(__file__))
|
||
print("m=importlib.util.module_from_spec(spec);sys.modules['m']=m;spec.loader.exec_module(m);")
|
||
print("print(m.fetch_sign_effect_targets())\"")
|