msg feat: 优化流程实例查询逻辑避免误判 msg docs: 更新文档说明及版本号至1.1.5 msg refactor: 优化提醒消息逻辑隐藏不必要部门信息
1176 lines
56 KiB
Python
1176 lines
56 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: step2_sign_new_contract.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-10-09
|
||
@Description: XQ0035 服务岗转正不通过电子签(离职+入职)——新签合同分支(影刀单文件自包含,独立排程 09:30)。
|
||
与主流程 step1_trial_period_change.py / 生效复核 step3_sign_effect_check.py 完全解耦(登录/AI表格读写等公共逻辑各自内置)。
|
||
|
||
选择条件(钉钉 AI表格「门店服务岗转正跟进-周更新」,字段对照见 aa.md):
|
||
人资是否处理 = 是 且 离职推送时间不为空 且 新合同推送日期为空,
|
||
且工号不在异常记录表「超龄需分段」名单中(未达龄但开始日距退休日不足/等于 3 个月 -> 不自动签,转人工)。
|
||
|
||
执行链(每条记录,aa.md 新签合同分支):
|
||
1. 查【劳动关系→合同台账→生效中合同】:仍有生效合同(离职解除尚未生效)-> 跳过,等下一次运行再检测;
|
||
2. 查【未签合同】按工号:查无 = 旧合同解除尚未生效/数据未同步 -> 跳过(不按"无需处理"漏掉);
|
||
3. 查该员工离职电子签流程状态:已发起且未全部办结 -> 跳过,等下一次运行再检测
|
||
(流程反查不到时视为可继续,由第 1/2 步的合同状态兜底,避免误签/漏签);
|
||
4. 存在则「新签」:已达龄签超龄用工协议、未达龄签劳动合同;期限:超龄用工不分类型统一
|
||
1 年(12 个月,2026-10-13 拍板),未达龄按序列(服务/技师序列 1 年、其他 3 年);
|
||
起始日期 = 上一份合同终止/解除日期 + 1 天,终止日期 = 起始 + 期限 - 1 天
|
||
(签署前复核:未达龄且终止日 >= 退休日时,开始日到退休日 > 3 个月 -> 直接签至退休日;
|
||
<= 3 个月才记录异常「超龄需分段」,不签,转人工);
|
||
合同签署单位 = AI表格「合同签署单位」(后浪新天地LIFE+主题会馆按 AI表「岗位」
|
||
自动细分:岗位含 小吃厨师/吧员/员工餐厨师/餐饮组长 任一 -> (餐饮)主体,
|
||
其余 -> (非餐饮)主体,2026-10-16 拍板);电子签期望推送时间 = 操作当天;
|
||
5. 成功后 AI表格写入「新合同推送日期 = 操作当天」;
|
||
6. 推送后合同是否已签署生效,由独立分支 step3_sign_effect_check.py 检测回填「签署跟进」。
|
||
|
||
超龄复核(sign_new_contract 内):已达龄 -> 正常自动签,合同类型=超龄用工协议(ext_8,不报异常);
|
||
未达龄但新合同终止日越过退休日时:开始日到退休日 > 3 个月 -> 直接签至退休日(不报异常);
|
||
<= 3 个月 -> 超龄需分段异常转人工;其余 -> 劳动合同。
|
||
|
||
异常记录表:D:\\资料\\人资\\试用期变更\\异常记录.xlsx(员工工号/姓名/异常类型/异常详情/记录时间;
|
||
类型:超龄需分段、提交报错;同工号重复出现保留最新一条)。
|
||
|
||
接口清单(抓包+前端 JS 逆向确认,详见主脚本 docstring 0e;登录态基于共享 HR cookies):
|
||
0. 查生效中合同:POST /RedseaPlatform/hrRoster/614ffe05-b4f1-11ea-b588-14187743d052/queryRealTimeData.mc
|
||
0e. 查未签合同:POST /RedseaPlatform/hrRoster/23408e2c-b470-11ea-b588-14187743d052/queryRealTimeData.mc
|
||
(行含 sex/birthday/first_type_id/lastContractInfo.last_contract_info/hr_staff_contract.contract_id)
|
||
属性页全量:POST /RedseaPlatform/HrTableEngine/23408e2c-.../d90c766c10cf44f49bcc80d17566a64c/getPropPageData.mc
|
||
提交:POST /RedseaPlatform/HrTableEngine/d90c766c10cf44f49bcc80d17566a64c/savePropPageData.mc
|
||
单位下拉:hrmodulesqlid/getList/customer_contract_unit_set_query_module_conf_sp_cq37du(名->code)
|
||
单位详情联动:redmagicapi/rf_hr_contract_unit_set_select_sp_cq37du(UNIT_SET_ID -> 营业执照名称/印章编号)
|
||
电子合同模板:redmagicapi/rf_hr_contract_template_select_sp_cq37du(base_id + sign_way=ext_1 + ext_is_esign=1)
|
||
流程状态:WeProcess.mc?method=getProcessAndData(反查流程实例)+ WeTask.mc?method=query(查活动任务判断办结)
|
||
|
||
⚠️ 安全提示:本脚本为线上写操作(真实新签劳动合同并推送电子签),执行前请务必核对员工与参数。
|
||
登录态直接读取共享 hr_cookies.json(由「37duHR登录」指令写入),缺失/失效时友好提示,不自动补登。
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install requests pandas openpyxl
|
||
|
||
运行方式:
|
||
1. 影刀:注册为自定义指令「37du新签合同」,main() 关键字传参;从 AI表格名单读取待新签记录。
|
||
2. 业务脚本:importlib 加载本模块调用 main(...)。
|
||
|
||
全局变量:messages(结果摘要文本列表,供「37du钉钉群机器人推送」指令逐条发送)
|
||
"""
|
||
import calendar
|
||
import json
|
||
import os
|
||
import re
|
||
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"
|
||
|
||
# ---------- 合同台账(生效中合同 / 未签合同) ----------
|
||
ROSTER_ID_ACTIVE_CONTRACT = "614ffe05-b4f1-11ea-b588-14187743d052" # 生效中合同 Tab
|
||
TABLE_ID_CONTRACT = "assemble-hr_staff_contract"
|
||
QUERY_ACTIVE_CONTRACT_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
|
||
f"{ROSTER_ID_ACTIVE_CONTRACT}/queryRealTimeData.mc")
|
||
ROSTER_ID_NO_CONTRACT = "23408e2c-b470-11ea-b588-14187743d052" # 未签合同 Tab
|
||
QUERY_NO_CONTRACT_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
|
||
f"{ROSTER_ID_NO_CONTRACT}/queryRealTimeData.mc")
|
||
# 新签合同属性页(真实浏览器抓包确认)
|
||
PROP_PAGE_NEW_CONTRACT = "d90c766c10cf44f49bcc80d17566a64c"
|
||
GET_PROP_PAGE_DATA_NC_URL = (f"{HR_BASE_URL}/RedseaPlatform/HrTableEngine/"
|
||
f"{ROSTER_ID_NO_CONTRACT}/{PROP_PAGE_NEW_CONTRACT}/getPropPageData.mc")
|
||
SAVE_PROP_PAGE_NC_URL = (f"{HR_BASE_URL}/RedseaPlatform/HrTableEngine/"
|
||
f"{PROP_PAGE_NEW_CONTRACT}/savePropPageData.mc")
|
||
# 合同签署单位(si_area)下拉:门店/公司名 -> code 映射
|
||
UNIT_SET_LIST_URL = (HR_BASE_URL + "/RedseaPlatform/hrmodulesqlid/getList/"
|
||
"customer_contract_unit_set_query_module_conf_sp_cq37du/common.mc?start=0")
|
||
# 职位序列(first_type_id -> 名称,判断 1年/3年)
|
||
POST_TYPE_SELECT_URL = (f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/"
|
||
"rf_s_Core_Post_pt_post_type_Select_v3_1/getExecuteResult.mc")
|
||
# 电子合同模板(按员工/签署方式返回 contract_template 逗号串)
|
||
TEMPLATE_SELECT_URL = (f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/"
|
||
"rf_hr_contract_template_select_sp_cq37du/getExecuteResult.mc")
|
||
# 签署单位详情联动(UNIT_SET_ID=si_area -> 营业执照名称/印章编号,属性页选中单位自动带出)
|
||
UNIT_SET_DETAIL_URL = (f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/"
|
||
"rf_hr_contract_unit_set_select_sp_cq37du/getExecuteResult.mc")
|
||
|
||
# ---------- 流程实例/待办查询(反查离职电子签流程 + 判断办结) ----------
|
||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||
WORKFORM_FORM_ID = "5b904505-c319-4b29-8b0b-d2c887b2469a"
|
||
|
||
# ---------- 达龄阈值(男60/女50)与合同类型码 ----------
|
||
RETIRE_AGE_MALE = 60
|
||
RETIRE_AGE_FEMALE = 50
|
||
TREATY_TYPE_LABOR = "1" # 劳动合同
|
||
TREATY_TYPE_OVERAGE = "ext_8" # 超龄用工协议(已达龄新签 + 历史合同识别)
|
||
# 序列含以下关键字 -> 1 年;其他序列 3 年
|
||
SEQUENCE_1YEAR_KEYWORDS = ("服务序列", "技师序列")
|
||
|
||
# 异常类型(error_type;非空即转人工,写入本地异常表)
|
||
ERROR_OVERAGE_SPLIT = "超龄需分段"
|
||
# 新签分支过滤:仅排除「超龄需分段」异常记录(已达龄按超龄用工协议自动签不异常;提交报错等仍可继续新签)
|
||
ABNORMAL_OVERAGE_TYPES = (ERROR_OVERAGE_SPLIT,)
|
||
|
||
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
|
||
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"}
|
||
CSRF_HEADERS = {"X-Requested-With": "XMLHttpRequest", "Csrf-Token": "RP"}
|
||
|
||
# ---------- 异常记录表(超龄/提交报错累积,同工号留最新) ----------
|
||
# 配置直接内置(影刀环境不读取 .env,统一在代码内固化,保证本地/影刀行为一致)
|
||
DEFAULT_ABNORMAL_EXCEL = r"D:\资料\人资\试用期变更\异常记录.xlsx"
|
||
|
||
# ==================== 钉钉 AI表格(名单来源:门店服务岗转正跟进-周更新) ====================
|
||
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
|
||
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
|
||
AITABLE_BASE_ID = "YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA"
|
||
AITABLE_TABLE_ID = "uchjxPW"
|
||
AITABLE_OPERATOR_UNIONID = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号(固定操作人,勿用测试号)
|
||
|
||
# AI表格字段(新签分支用;签署跟进由生效复核脚本回填)
|
||
AITABLE_DONE_FIELD = "人资是否处理"
|
||
AITABLE_DONE_VALUE = "是"
|
||
AITABLE_PUSH_DATE_FIELD = "离职推送时间"
|
||
AITABLE_NEW_PUSH_DATE_FIELD = "新合同推送日期"
|
||
AITABLE_CONTRACT_UNIT_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
|
||
|
||
# ---------- WeProcess 流程实例分页遍历(反查不再受单页条数截断) ----------
|
||
WF_PAGE_SIZE = 100 # 每页条数(原首页 15 条易截断:办结检测首页未命中会误判「可继续」提前新签)
|
||
MAX_WF_PAGES = 50 # 上限页数(50 页 × 100 条 = 5000 条运行中流程,足够)
|
||
|
||
|
||
# ==================== 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_contract(session, base_code):
|
||
"""按工号在【劳动关系→合同台账→生效中合同】Tab 精准匹配生效合同。
|
||
|
||
Returns:
|
||
dict {contract_id, base_id, staff_name, contract_start_date, contract_end_date,
|
||
row(原始行快照, XQ0034 续签提交体用)};未找到返回 None
|
||
"""
|
||
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 []
|
||
for row in datas:
|
||
if str(row.get("hr_staff_base.base_code")) == str(base_code):
|
||
return {
|
||
"contract_id": row.get("hr_staff_contract.contract_id") or "",
|
||
"base_id": (row.get("hr_staff_contract.base_id")
|
||
or row.get("hr_staff_base.base_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 "",
|
||
"row": row,
|
||
}
|
||
return None
|
||
|
||
|
||
def _query_no_contract_roster(session, base_code):
|
||
"""合同台账-未签合同 roster 按工号查询,命中返回行 dict,未命中返回 None。"""
|
||
params = _build_query_params(
|
||
ROSTER_ID_NO_CONTRACT, "assemble-hr_staff_base",
|
||
_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_NO_CONTRACT_URL, session, data=params)
|
||
for row in resp.json().get("datas") or []:
|
||
if str(row.get("hr_staff_base.base_code")) == str(base_code):
|
||
return row
|
||
return None
|
||
|
||
|
||
# ==================== 离职电子签流程状态(办结检测) ====================
|
||
def query_transfer_workflow(session, business_key=None, title="改签离职电子签"):
|
||
"""通过流程待办接口 WeProcess.mc 分页查询「改签离职电子签」流程实例,返回最新一条详情链接。
|
||
|
||
优先按 businessKey 精确匹配(=旧合同 ID,发起调动解除时流程业务主键):
|
||
分页遍历全部运行中流程(每页 WF_PAGE_SIZE=100,上限 MAX_WF_PAGES 页),命中即返回,
|
||
不再受首页 15 条截断影响(此前首页未命中会误判「流程已办结/未发起」,导致新签提前放行);
|
||
否则按 title 模糊匹配取首页 CREATE_TIME 最新一条。
|
||
⚠️ 传入 business_key 但遍历全部页仍未命中时返回 None(绝不回退到其他员工的流程,避免办结检测误判)。
|
||
|
||
Returns:
|
||
dict {url, business_key, process_id, task_id, form_id, title, create_user, create_time} 或 None
|
||
"""
|
||
base_params = {
|
||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": title,
|
||
"state": "", "startTime": "", "endTime": "",
|
||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||
"commonQuery": "[]",
|
||
}
|
||
if business_key:
|
||
rows = []
|
||
for page in range(MAX_WF_PAGES):
|
||
params = dict(base_params)
|
||
params.update({"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)
|
||
datas = resp.json().get("jsonList") or resp.json().get("datas") or []
|
||
matched = [r for r in datas if str(r.get("businessKey")) == str(business_key)]
|
||
if matched:
|
||
rows = matched
|
||
break
|
||
if len(datas) < WF_PAGE_SIZE:
|
||
break
|
||
if not rows:
|
||
return None # 全部页遍历完未命中:无该员工的运行中流程实例,不误取他人流程
|
||
else:
|
||
resp = _request_retry("POST", WE_PROCESS_QUERY_URL, session, data=base_params)
|
||
rows = resp.json().get("jsonList") or resp.json().get("datas") or []
|
||
if not rows:
|
||
return None
|
||
rec = rows[0]
|
||
bk, pid, tid = (rec.get("businessKey") or ""), (rec.get("processId") or ""), (rec.get("taskId") or "")
|
||
fid = rec.get("formId") or WORKFORM_FORM_ID
|
||
if not (bk and pid and tid):
|
||
return None
|
||
url = (f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||
f"&formId={fid}&businessKey={bk}&processId={pid}&taskId={tid}&reqType=VIEW&headType=&systemId=")
|
||
return {"url": url, "business_key": bk, "process_id": pid, "task_id": tid, "form_id": fid,
|
||
"title": rec.get("title") or "", "create_user": rec.get("createUserName") or "",
|
||
"create_time": rec.get("createTime") or ""}
|
||
|
||
|
||
def query_process_tasks(session, process_id):
|
||
"""WeTask 查询流程实例下所有任务(含各参与人/各环节)。"""
|
||
resp = _request_retry("POST",
|
||
f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc?method=query&process_id={process_id}",
|
||
session, data={})
|
||
return resp.json().get("jsonList") or []
|
||
|
||
|
||
def is_flow_completed(session, process_id):
|
||
"""离职电子签流程是否办结:流程下无任何 WAITING/ACCEPTED 活动任务。"""
|
||
rows = query_process_tasks(session, process_id)
|
||
return not any(str(t.get("currentState")) in ("WAITING", "ACCEPTED") for t in rows)
|
||
|
||
|
||
# ==================== 新签合同核心 ====================
|
||
def _resolve_sequence_name(session, first_type_id):
|
||
"""职位序列 ID -> 名称(用于 1年/3年 判断;失败返回空串按 3 年兜底)。"""
|
||
if not first_type_id:
|
||
return ""
|
||
resp = _request_retry("POST", POST_TYPE_SELECT_URL, session, data={})
|
||
d = resp.json()
|
||
for o in d.get("jsonList") or []:
|
||
if str(o.get("code")) == str(first_type_id):
|
||
return str(o.get("name") or "")
|
||
return ""
|
||
|
||
|
||
def _retire_date(sex, birthday):
|
||
"""法定退休日 = 生日 + 退休年龄整年(男60/女50,sex:1=男 2=女);生日非法返回 None。"""
|
||
d = _to_date(birthday)
|
||
if d is None:
|
||
return None
|
||
limit = RETIRE_AGE_MALE if str(sex) == "1" else RETIRE_AGE_FEMALE
|
||
try:
|
||
return d.replace(year=d.year + limit)
|
||
except ValueError: # 2-29 生日遇平年兜底 2-28
|
||
return d.replace(year=d.year + limit, day=28)
|
||
|
||
|
||
def _parse_last_contract(last_contract_info):
|
||
"""解析 last_contract_info 文本 -> {treaty_type,start_date,end_date,stop_date}。
|
||
|
||
例:'劳动合同解除 (固定期2026-07-27~2027-07-26,终止/解除时间: 2026-09-30)'
|
||
注:真实数据「终止/解除时间:」冒号后可能带空格,正则需容忍(否则 stop_date 提取不到,
|
||
导致新签起始日错误回退为上一份合同终止日+1,2026-10-09 实测踩坑)。
|
||
"""
|
||
info = str(last_contract_info or "")
|
||
m = re.search(r"(\d{4}-\d{2}-\d{2})\s*~\s*(\d{4}-\d{2}-\d{2})", info)
|
||
start = m.group(1) if m else ""
|
||
end = m.group(2) if m else ""
|
||
m2 = re.search(r"解除时间[::]\s*(\d{4}-\d{2}-\d{2})", info)
|
||
stop = m2.group(1) if m2 else ""
|
||
treaty = TREATY_TYPE_LABOR if ("劳动" in info) else (TREATY_TYPE_OVERAGE if "超龄" in info else "")
|
||
return {"treaty_type": treaty, "start_date": start, "end_date": end, "stop_date": stop}
|
||
|
||
|
||
def _unit_set_id_by_name(session, name):
|
||
"""AI表「合同签署单位」门店/公司名 -> si_area code;找不到返回 ""。"""
|
||
if not name:
|
||
return ""
|
||
resp = _request_retry("POST", UNIT_SET_LIST_URL, session, data={"inUse": "1"})
|
||
d = resp.json()
|
||
for o in d.get("jsonList") or []:
|
||
if str(o.get("name")) == str(name).strip():
|
||
return str(o.get("code") or "")
|
||
return ""
|
||
|
||
|
||
# 后浪新天地LIFE+主题会馆签署单位细分(2026-10-16 用户拍板):该店拆 餐饮/非餐饮
|
||
# 两个签约主体,按岗位二分——岗位含餐饮四岗任一关键词 -> (餐饮)主体,其余 -> (非餐饮)
|
||
HOULANG_BASE_NAME = "后浪新天地LIFE+主题会馆"
|
||
HOULANG_CATERING_POSITIONS = ("小吃厨师", "吧员", "员工餐厨师", "餐饮组长")
|
||
|
||
|
||
def houlang_unit_name(session, unit_name, position):
|
||
"""后浪新天地LIFE+主题会馆签署单位按岗位细分,返回落地单位名。
|
||
|
||
规则:岗位含 餐饮四岗(小吃厨师/吧员/员工餐厨师/餐饮组长,子串匹配容忍岗位
|
||
带前后缀)任一 -> 「后浪新天地LIFE+主题会馆(餐饮)」,其余(含岗位为空)->
|
||
「后浪新天地LIFE+主题会馆(非餐饮)」;单位名不含"后浪新天地"时原样返回(不查字典)。
|
||
变体全角/半角括号逐一试映射单位字典,命中即返回该单位名;
|
||
后浪单位但变体均未命中 -> 返回 None,由调用方走各自兜底并告警。
|
||
"""
|
||
name = str(unit_name or "").strip()
|
||
if HOULANG_BASE_NAME not in name:
|
||
return name
|
||
pos = str(position or "").strip()
|
||
suffix = "餐饮" if any(k in pos for k in HOULANG_CATERING_POSITIONS) else "非餐饮"
|
||
for cand in (f"{HOULANG_BASE_NAME}({suffix})", f"{HOULANG_BASE_NAME}({suffix})"):
|
||
if _unit_set_id_by_name(session, cand):
|
||
return cand
|
||
return None
|
||
|
||
|
||
def _new_contract_template_ids(session, base_id):
|
||
"""电子合同模板(按员工+签署方式,返回逗号串;失败返回空串)。
|
||
|
||
sign_way 必须 ext_1(属性页 contract_type_template 联动 dataGetDesc 定义),
|
||
实测 ext_1 与浏览器页面默认 3 个模板 ID 一致;ext_3 中间模板不同。
|
||
"""
|
||
try:
|
||
resp = _request_retry("POST", TEMPLATE_SELECT_URL, session,
|
||
data={"base_id": base_id, "sign_way": "ext_1", "ext_is_esign": "1"})
|
||
d = resp.json()
|
||
lst = d.get("jsonList") or []
|
||
if lst:
|
||
return str(lst[0].get("contract_template") or "")
|
||
except Exception:
|
||
pass
|
||
return ""
|
||
|
||
|
||
def _unit_set_detail(session, si_area):
|
||
"""签署单位详情:si_area -> (营业执照名称, 印章编号)。
|
||
|
||
属性页选中单位后的联动数据源(rf_hr_contract_unit_set_select_sp_cq37du,
|
||
UNIT_SET_ID 入参 -> ext_license_name/ext_seal_number/ext_is_push_esign),
|
||
实测与浏览器自动带出值一致;查询失败返回 ("", "")。
|
||
"""
|
||
if not si_area:
|
||
return "", ""
|
||
try:
|
||
resp = _request_retry("POST", UNIT_SET_DETAIL_URL, session,
|
||
data={"UNIT_SET_ID": si_area})
|
||
rows = resp.json().get("jsonList") or []
|
||
if rows:
|
||
return (str(rows[0].get("ext_license_name") or ""),
|
||
str(rows[0].get("ext_seal_number") or ""))
|
||
except Exception:
|
||
pass
|
||
return "", ""
|
||
|
||
|
||
def sign_new_contract(session, task, contract_unit_name=None, row=None):
|
||
"""新签合同:离职再入职后,在「合同台账-未签合同」为该员工签新合同。
|
||
|
||
规则(需求单/aa.md 新签合同分支):
|
||
1) 未签合同 roster 按工号查询(row 已由调用方传入时可跳过);不存在 -> 无需处理(返回跳过)
|
||
2) 超龄复核:已达龄 -> 正常自动签,合同类型=超龄用工协议(ext_8,不报异常);
|
||
未达龄但新合同终止日越过退休日 -> 开始日到退休日 > 3 个月时直接签至退休日,
|
||
<= 3 个月才转人工(超龄需分段);其余 -> 劳动合同
|
||
3) 期限:超龄用工(已达龄)不分类型统一 12 个月;
|
||
未达龄序列名含「服务序列/技师序列」-> 1 年,其他序列 -> 3 年
|
||
4) 起始日期 = 上一份合同终止/解除日期 + 1 天;终止 = 起始 + 期限 - 1 天
|
||
5) 合同签署单位 si_area = AI表「合同签署单位」(名->code;后浪新天地按岗位
|
||
细分(餐饮)/(非餐饮));电子签期望推送 = 操作当天
|
||
6) savePropPageData 整表单提交(与浏览器一致,先 getPropPageData 读全量)
|
||
|
||
Returns:
|
||
(ok: bool, msg: str, signed: bool, error_type: str):
|
||
signed=True 表示本次实际签了新合同(供回填新合同推送日期);
|
||
error_type 非空表示超龄异常(超龄需分段),供异常表与钉钉文案分类
|
||
"""
|
||
base_code = str(task["base_code"]).strip()
|
||
today = datetime.now().date()
|
||
today_s = today.strftime("%Y-%m-%d")
|
||
|
||
# 1) 未签合同存在性检查
|
||
if row is None:
|
||
row = _query_no_contract_roster(session, base_code)
|
||
if row is None:
|
||
logger.info("【%s】未签合同中无该员工,无需新签合同", base_code)
|
||
return True, "未签合同中无该员工,无需新签合同", False, ""
|
||
|
||
# 2) 超龄复核:已达龄 -> 正常自动签超龄用工协议(不报异常、不转人工)
|
||
sex = row.get("hr_staff_base.sex") or ""
|
||
birthday = row.get("hr_staff_base.birthday") or row.get("hr_staff_base.birthday_date") or ""
|
||
rd = _retire_date(sex, birthday)
|
||
treaty_type = TREATY_TYPE_LABOR
|
||
if rd is not None and today >= rd:
|
||
treaty_type = TREATY_TYPE_OVERAGE
|
||
logger.info("【%s】已达法定退休年龄(退休日 %s),按超龄用工协议自动新签",
|
||
base_code, rd.isoformat())
|
||
|
||
# 3) 期限:超龄用工(已达龄)不分类型统一 12 个月(2026-10-13 拍板);
|
||
# 未达龄按序列(服务/技师序列 1 年,其他 3 年)
|
||
first_type_id = row.get("pt_staff_stru.first_type_id") or ""
|
||
seq_name = _resolve_sequence_name(session, first_type_id)
|
||
if treaty_type == TREATY_TYPE_OVERAGE:
|
||
months = 12
|
||
else:
|
||
months = 12 if any(k in seq_name for k in SEQUENCE_1YEAR_KEYWORDS) else 36
|
||
|
||
# 4) 上一份合同 -> 起始/终止
|
||
last = _parse_last_contract(row.get("lastContractInfo.last_contract_info"))
|
||
start = None
|
||
if last["stop_date"]:
|
||
start = _to_date(last["stop_date"]) + timedelta(days=1)
|
||
if start is None and last["end_date"]:
|
||
start = _to_date(last["end_date"]) + timedelta(days=1)
|
||
if start is None:
|
||
return False, "新签合同失败:无法确定合同起始日期(无上一份合同终止/解除日期)", False, ""
|
||
start_s = start.strftime("%Y-%m-%d")
|
||
end_s = _defer_months(start, months) - timedelta(days=1)
|
||
end_s = end_s.strftime("%Y-%m-%d")
|
||
|
||
# 4.5) 超龄精确复核:未达龄但按期限签会越过退休日
|
||
# 实际开始日到退休日 > 3 个月 -> 直接签至退休日(终止日=退休日,不再转人工);
|
||
# <= 3 个月 -> 超龄需分段异常,转人工
|
||
# (已达龄走超龄用工协议整签,终止日必然越过退休日,不在此列)
|
||
if rd is not None and today < rd and _to_date(end_s) >= rd:
|
||
if _defer_months(start, 3) < rd:
|
||
months = _month_span(start, rd)
|
||
end_s = rd.strftime("%Y-%m-%d")
|
||
logger.info("【%s】未达龄但开始日 %s 距退休日 %s 超过 3 个月,"
|
||
"直接签至退休日(按 %d 个月登记期限)",
|
||
base_code, start_s, rd.isoformat(), months)
|
||
else:
|
||
msg = (f"未达龄但新合同终止日 {end_s} 越过法定退休日 {rd.isoformat()},"
|
||
f"距退休日不足/等于 3 个月,超龄需分段(先签至退休日前,"
|
||
f"退休后另签超龄用工协议),转人工处理")
|
||
logger.error("【%s】%s", base_code, msg)
|
||
return False, msg, False, ERROR_OVERAGE_SPLIT
|
||
|
||
# 5) 签署单位 si_area(AI表名 -> code;后浪新天地按岗位细分(餐饮)/(非餐饮);
|
||
# 失败兜底上一份合同单位字段,再兜底默认单位)
|
||
hl_name = houlang_unit_name(session, contract_unit_name, task.get("position") or "")
|
||
if hl_name is None:
|
||
logger.warning("【%s】后浪新天地签署单位(餐饮/非餐饮)均未命中单位字典,"
|
||
"AI表登记值「%s」不再直接映射,改走兜底单位", base_code, contract_unit_name)
|
||
hl_name = ""
|
||
si_area = _unit_set_id_by_name(session, hl_name)
|
||
pre_si_area = row.get("lastContractInfo.pre_si_area") or ""
|
||
if not si_area and pre_si_area:
|
||
si_area = pre_si_area
|
||
if not si_area:
|
||
# 兜底:取单位下拉第一个启用单位
|
||
try:
|
||
resp = _request_retry("POST", UNIT_SET_LIST_URL, session, data={"inUse": "1"})
|
||
lst = resp.json().get("jsonList") or []
|
||
if lst:
|
||
si_area = str(lst[0].get("code") or "")
|
||
except Exception:
|
||
si_area = ""
|
||
if not si_area:
|
||
return False, "新签合同失败:无法确定合同签署单位(si_area)", False, ""
|
||
|
||
# 6) 电子合同模板 + 单位详情(营业执照名称/印章编号)+ 属性页全量数据
|
||
template_ids = _new_contract_template_ids(session, row.get("hr_staff_base.base_id") or "")
|
||
license_name, seal_number = _unit_set_detail(session, si_area)
|
||
resp = _request_retry("POST", GET_PROP_PAGE_DATA_NC_URL, session,
|
||
data={"businessKey": row.get("hr_staff_base.base_id") or "",
|
||
"roleId": ""})
|
||
d = resp.json()
|
||
if str(d.get("state")) != "1":
|
||
return False, f"新签合同失败:读取属性页数据异常 {d.get('meg') or d}", False, ""
|
||
base_data = {}
|
||
for k, v in (d.get("result") or {}).items():
|
||
if v is None:
|
||
base_data[k] = ""
|
||
else:
|
||
s2 = str(v).strip()
|
||
if re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$", s2):
|
||
s2 = s2[:10]
|
||
base_data[k] = s2
|
||
|
||
# 7) 属性字段(默认值 + 业务规则结果;覆盖 base 中同名项)
|
||
prop = {
|
||
"businessKey": row.get("hr_staff_base.base_id") or "",
|
||
"table_id": "assemble-hr_staff_base",
|
||
"fkId": "", "struTreeCode": "", "belongUnitStruId": "-1", "struId": "-1",
|
||
"illegalFiletype": "js,jsp,exe,vbs,jspx,sys,dll,jspf,php,sh,bat,py,java,c,class,com,out,elf,jsf.jsp",
|
||
"uploadLimitSize": "500",
|
||
"rootId": "cq37du", "isVirtual": "", "isHrTable": "1", "compeletCount": "12",
|
||
"hr_treaty_type": treaty_type,
|
||
"hr_contract_type": "0",
|
||
"contract_start_date": start_s,
|
||
"contract_deadline": str(months),
|
||
"contract_end_date": end_s,
|
||
"contract_Sign_Date": today_s,
|
||
"sign_way": "1",
|
||
"si_area": si_area,
|
||
"ext_license_name": license_name,
|
||
"ext_seal_number": seal_number,
|
||
"contract_count": "1",
|
||
"operate_type": "1",
|
||
"status": "1",
|
||
"data_source": "2",
|
||
"create_user_id": CURRENT_USER_ID,
|
||
"create_user_name": CURRENT_USER_NAME,
|
||
"operator_id": CURRENT_USER_ID,
|
||
"operator_name": CURRENT_USER_NAME,
|
||
"create_time": today_s,
|
||
"cal_start_date": start_s,
|
||
"CalTypeOfDateAndPeriod": "1",
|
||
"suggest_sign_way": "2",
|
||
"ext_is_push_esign": "1",
|
||
"ext_push_time": today_s,
|
||
"contract_type_template": template_ids,
|
||
"current_contract_id": row.get("hr_staff_contract.contract_id") or "",
|
||
"last_contract_info": row.get("lastContractInfo.last_contract_info") or "",
|
||
"pre_treaty_type": last["treaty_type"],
|
||
"pre_start_date": last["start_date"],
|
||
"pre_end_date": last["end_date"],
|
||
"pre_stop_date": last["stop_date"],
|
||
"pre_si_area": pre_si_area,
|
||
"pre_active_status": "3",
|
||
}
|
||
params = dict(base_data)
|
||
params.update(prop)
|
||
|
||
# 8) 提交
|
||
resp = _request_retry("POST", SAVE_PROP_PAGE_NC_URL, session,
|
||
data=params, headers=CSRF_HEADERS)
|
||
d = resp.json()
|
||
if str(d.get("state")) != "1":
|
||
return False, f"新签合同失败:{d.get('meg') or d}", False, ""
|
||
treaty_name = "劳动合同" if treaty_type == TREATY_TYPE_LABOR else "超龄用工协议"
|
||
logger.info("【%s】新签合同成功:%s,%s(%s ~ %s,单位=%s,模板=%s)",
|
||
base_code, treaty_name, f"{months}个月", start_s, end_s, si_area, template_ids)
|
||
return True, (f"新签合同完成({treaty_name}{months}个月 {start_s}~{end_s},"
|
||
f"推送电子签 {today_s})"), True, ""
|
||
|
||
|
||
# ==================== 日期工具 ====================
|
||
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
|
||
|
||
|
||
def _defer_months(d, months):
|
||
"""日期顺延 months 个月:日不变,目标月无该日则取当月最后一天(如 1-31 -> 2-28)。"""
|
||
y = d.year + (d.month - 1 + months) // 12
|
||
m = (d.month - 1 + months) % 12 + 1
|
||
last_day = calendar.monthrange(y, m)[1]
|
||
return date(y, m, min(d.day, last_day))
|
||
|
||
|
||
def _month_span(start, end):
|
||
"""start -> end 的整月数(日历月差,日不足一个月的零头不计;最小 1)。"""
|
||
months = (end.year - start.year) * 12 + (end.month - start.month)
|
||
if end.day < start.day:
|
||
months -= 1
|
||
return max(1, months)
|
||
|
||
|
||
def _today_ms():
|
||
"""当天 0 点的毫秒时间戳(与 AI表格 date 字段存储格式一致)。"""
|
||
return int(datetime.combine(date.today(), datetime.min.time()).timestamp() * 1000)
|
||
|
||
|
||
# ==================== 钉钉 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_new_contract_targets(records=None):
|
||
"""从钉钉 AI表格筛选待新签名单(aa.md 新签合同分支选择条件)。
|
||
|
||
条件:人资是否处理=是 且 离职推送时间不为空 且 新合同推送日期为空,
|
||
且工号不在异常记录表「超龄需分段」名单中(未达龄但终止日越过退休日 -> 转人工不自动签)。
|
||
|
||
Returns:
|
||
list[dict]:{record_id, base_code, staff_name, contract_unit, position}
|
||
"""
|
||
records = records if records is not None else fetch_aitable_records()
|
||
abnormal_codes = read_abnormal_codes()
|
||
targets = []
|
||
for rec in records:
|
||
fields = rec.get("fields") or {}
|
||
done = _aitable_opt_name(fields.get(AITABLE_DONE_FIELD))
|
||
push_date = fields.get(AITABLE_PUSH_DATE_FIELD)
|
||
new_push = fields.get(AITABLE_NEW_PUSH_DATE_FIELD)
|
||
if done != AITABLE_DONE_VALUE:
|
||
continue
|
||
if not push_date:
|
||
continue
|
||
if new_push:
|
||
continue
|
||
base_code = str(fields.get("员工工号") or "").strip()
|
||
if not base_code:
|
||
continue
|
||
if base_code in abnormal_codes:
|
||
continue
|
||
targets.append({
|
||
"record_id": rec.get("id"),
|
||
"base_code": base_code,
|
||
"staff_name": str(fields.get("员工姓名") or "").strip(),
|
||
"contract_unit": fields.get(AITABLE_CONTRACT_UNIT_FIELD),
|
||
"position": str(fields.get("岗位") or "").strip(),
|
||
})
|
||
logger.info("新签选择:AI表格 %d 条,命中待新签 %d 条(异常表超龄需分段过滤 %d 个工号)",
|
||
len(records), len(targets), len(abnormal_codes))
|
||
return targets
|
||
|
||
|
||
def mark_new_push_date(record_ids):
|
||
"""把 AI表格对应行「新合同推送日期」回填为操作当天(date 字段写毫秒时间戳)。
|
||
|
||
仅新签成功(signed=True)的行由 main() 调用。
|
||
|
||
Returns:
|
||
(成功数, 失败数)
|
||
"""
|
||
record_ids = [r for r in record_ids if r]
|
||
if not record_ids:
|
||
return 0, 0
|
||
today_ms = _today_ms()
|
||
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_NEW_PUSH_DATE_FIELD: today_ms}}
|
||
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 read_abnormal_codes(abnormal_path=None):
|
||
"""读取异常记录表中「超龄需分段」类型的工号集合,用于新签过滤。
|
||
|
||
仅过滤超龄需分段类型:提交报错(如电子签失败)类记录不代表无需新签,不参与过滤;
|
||
已达龄按超龄用工协议自动签,不再产生/过滤「已达法定退休年龄」记录(历史记录同步失效)。
|
||
"""
|
||
path = abnormal_path or DEFAULT_ABNORMAL_EXCEL
|
||
codes = set()
|
||
if not os.path.exists(path):
|
||
return codes
|
||
try:
|
||
df = pd.read_excel(path, dtype={"员工工号": str})
|
||
if "员工工号" not in df.columns or "异常类型" not in df.columns:
|
||
return codes
|
||
mask = df["异常类型"].astype(str).isin(ABNORMAL_OVERAGE_TYPES)
|
||
codes = set(df.loc[mask, "员工工号"].astype(str).str.strip())
|
||
except Exception as e:
|
||
logger.warning("异常记录表读取失败(按无超龄过滤处理):%s", e)
|
||
return codes
|
||
|
||
|
||
def write_abnormal_excel(results, abnormal_path=None):
|
||
"""异常记录累积写入本地 Excel(超龄需分段/提交报错)。
|
||
|
||
收录口径:error_type 非空(超龄需分段转人工)或 status=失败(提交报错);
|
||
普通「跳过」(未办结/解除未生效等,等待下次运行)不收录。
|
||
追加策略:保留旧表记录,剔除本次出现的同工号旧行后追加本次记录(同工号留最新)。
|
||
"""
|
||
abnormals = [r for r in results if r.get("error_type") or r.get("status") == "失败"]
|
||
if not abnormals:
|
||
return ""
|
||
path = abnormal_path or DEFAULT_ABNORMAL_EXCEL
|
||
now_s = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
new_df = pd.DataFrame([{
|
||
"员工工号": r.get("base_code") or "",
|
||
"员工姓名": r.get("staff_name") or "",
|
||
"异常类型": r.get("error_type") or "提交报错",
|
||
"异常详情": r.get("message") or "",
|
||
"记录时间": now_s,
|
||
} for r in abnormals])
|
||
try:
|
||
out_dir = os.path.dirname(path)
|
||
if out_dir:
|
||
os.makedirs(out_dir, exist_ok=True)
|
||
if os.path.exists(path):
|
||
try:
|
||
old_df = pd.read_excel(path, dtype={"员工工号": str})
|
||
codes = set(new_df["员工工号"])
|
||
old_df = old_df[~old_df["员工工号"].astype(str).isin(codes)]
|
||
new_df = pd.concat([old_df, new_df], ignore_index=True)
|
||
except Exception as e:
|
||
logger.warning("异常表旧文件读取失败,本次将覆盖:%s", e)
|
||
new_df.to_excel(path, index=False)
|
||
logger.info("异常记录已写入:%s(本次 %d 条)", path, len(abnormals))
|
||
return path
|
||
except Exception as e:
|
||
logger.warning("异常记录写入失败(不影响处理结果):%s", e)
|
||
return ""
|
||
|
||
|
||
# ==================== 影刀全局变量 ====================
|
||
def _set_glv(name, value):
|
||
"""写入影刀全局变量;非影刀环境(本地独立运行)时静默跳过。"""
|
||
try:
|
||
glv[name] = value
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _build_messages(results):
|
||
"""按结果类型构造钉钉群推送消息列表(成功/跳过/超龄需分段异常转人工/失败各一条汇总)。"""
|
||
manual = [r for r in results if r.get("error_type")]
|
||
ok = [r for r in results if not r.get("error_type") and r["status"] == "成功"]
|
||
skip = [r for r in results if not r.get("error_type") and r["status"] == "跳过"]
|
||
fail = [r for r in results if not r.get("error_type") and r["status"] not in ("成功", "跳过")]
|
||
messages = []
|
||
if ok:
|
||
lines = [f"✅ 新签合同成功 {len(ok)} 人:"]
|
||
lines += [f" - {r['staff_name']}({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 manual:
|
||
lines = [f"🚨 超龄需分段异常转人工 {len(manual)} 人(需人工分段新签):"]
|
||
lines += [f" - {r.get('staff_name') or ''}({r['base_code']})[{r['error_type']}]:{r['message']}"
|
||
for r in manual]
|
||
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):
|
||
"""处理单条新签合同(选择条件已由 fetch_new_contract_targets 保证)。
|
||
|
||
执行链(aa.md 新签合同分支):
|
||
1) 查【生效中合同】:仍有 -> 离职解除尚未生效,跳过等下次;
|
||
2) 查【未签合同】:查无 = 旧合同解除尚未生效/数据未同步 -> 跳过(不按"无需处理"漏掉);
|
||
3) 查该员工离职电子签流程状态:已发起且未全部办结 -> 跳过等下次;
|
||
4) 新签(内部复核超龄)-> 成功则回填「新合同推送日期=操作当天」。
|
||
|
||
Returns:
|
||
dict {base_code, staff_name, status: 成功/跳过/失败, message, error_type, signed, record_id}
|
||
"""
|
||
base_code = str(task["base_code"]).strip()
|
||
result = {
|
||
"base_code": base_code,
|
||
"staff_name": task.get("staff_name") or "",
|
||
"status": "跳过",
|
||
"message": "",
|
||
"error_type": "",
|
||
"signed": False,
|
||
"record_id": task.get("record_id"),
|
||
}
|
||
|
||
# 1) 生效中合同(离职解除未生效则不能签新合同)
|
||
contract = query_active_contract(session, base_code)
|
||
if contract and contract.get("contract_id"):
|
||
result["message"] = "仍有【生效中合同】(离职解除尚未生效),跳过,等下一次运行再检测"
|
||
logger.info("【%s】%s", base_code, result["message"])
|
||
return result
|
||
|
||
# 2) 未签合同查人(查无 = 解除未生效/数据未同步,不能按"无需处理"漏掉)
|
||
row = _query_no_contract_roster(session, base_code)
|
||
if row is None:
|
||
result["message"] = "【未签合同】查无此人(旧合同解除尚未生效/数据未同步),跳过,等下一次运行"
|
||
logger.info("【%s】%s", base_code, result["message"])
|
||
return result
|
||
result["staff_name"] = row.get("hr_staff_base.staff_name") or result["staff_name"]
|
||
|
||
# 3) 离职电子签流程状态(businessKey=旧合同 ID;流程反查不到时视为可继续,由第 1/2 步兜底)
|
||
contract_id = row.get("hr_staff_contract.contract_id") or ""
|
||
if contract_id:
|
||
wf = query_transfer_workflow(session, business_key=contract_id)
|
||
if wf:
|
||
pid = wf.get("process_id") or ""
|
||
if pid and not is_flow_completed(session, pid):
|
||
result["message"] = "离职电子签流程尚未全部办结,跳过,等下一次运行再检测"
|
||
logger.info("【%s】%s", base_code, result["message"])
|
||
return result
|
||
|
||
# 4) 新签(row 已查到,直接传入避免重复查询)
|
||
ok, msg, signed, err = sign_new_contract(session, task,
|
||
contract_unit_name=task.get("contract_unit"),
|
||
row=row)
|
||
result["error_type"] = err
|
||
result["signed"] = bool(signed)
|
||
if not ok:
|
||
result["status"] = "失败"
|
||
result["message"] = msg
|
||
logger.error("【%s】%s", base_code, result["message"])
|
||
return result
|
||
result["status"] = "成功"
|
||
result["message"] = msg
|
||
logger.info("【%s】✅ %s", base_code, result["message"])
|
||
return result
|
||
|
||
|
||
# ==================== 入口 ====================
|
||
def main(records=None, write_back=True):
|
||
"""影刀自定义指令入口「37du新签合同」(独立排程:主流程后,如 09:30)。
|
||
|
||
名单来源:钉钉 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_new_contract_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.get("signed") and r.get("record_id")]
|
||
if done_ids:
|
||
wok, wfail = mark_new_push_date(done_ids)
|
||
logger.info("AI表格回填「新合同推送日期」:成功 %d 失败 %d", wok, wfail)
|
||
else:
|
||
logger.info("AI表格回填「新合同推送日期」:本次无新签成功的行")
|
||
write_abnormal_excel(results)
|
||
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__":
|
||
main()
|
||
|