feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0035 数据层:XQ0035 三个生产步骤脚本(影刀版原样移植,会话/路径经 config 钩子注入)。"""
|
||||
@@ -0,0 +1,297 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0035 插件 - 钉钉群机器人推送(自 workflows/share/dingtalk_robot.py 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 执行机运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "37du 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法(业务层统一走 report/notify.py,也可直接调用):
|
||||
main("需要推送的通知文本") 即可,标题/颜色/环境等均可选;
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK )
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = '' # 测试环境加签密钥(未配置则不加签)
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 环境 → 机器人配置(main 的 env 参数选择;缺省/未知环境回退 prod)
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 推送入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
钉钉群机器人推送入口(与影刀版「37du钉钉群机器人推送」指令同一套签名/分批/页脚逻辑)。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【增员导入】异常名单(2 条)",
|
||||
"blocks": ["**🔹 三十七度‑张三**\n> 工号:...", "..."],
|
||||
"status": "error"},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省按 env 选择;显式传入则优先)
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = webhook or cfg['webhook']
|
||||
secret = secret or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置,请先在 dingtalk_robot.py 中填写'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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