Files
37duAutomation/plugins/XQ0001-0100/XQ0034 续签电子签/data/xq_common.py
T

467 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""xq0034 数据层公共设施(精简自 xq0035/xq0037 同源模块的自包含副本)。
仅保留 XQ0034 续签电子签所需基础设施:
- HR 会话(底座注入 config.get_session)+ 项目级重试 + 登录态失效识别
- commonQuery 前端加密 / queryRealTimeData 参数构造
- 钉钉 AI表格 accessToken / 请求 / singleSelect 选项名解析
- 合同台账【生效中合同】查询 / 合同签署单位下拉(名 -> code)
- 员工花名册查询(联系方式核对用,字段 hr_staff_base.mobile_phone)
- 手机号唯一校验(HR 页面 ajaxValidate 同款接口;saveTableData 不校验)
- 日期工具 / 影刀全局变量兼容容器(messages)
与 xq0035/xq0037 内嵌副本同源同步维护(允许少量重复换取完全解耦)。
"""
import json
import time
import urllib.parse
from datetime import datetime, timedelta
from .. import config
try:
import requests
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(插件要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install requests\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"
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
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"}
# ---------- 项目级重试(最大 3 次,三次失败后再记录错误) ----------
MAX_ATTEMPTS = 3
RETRY_DELAY_BASE = 2.0
# ==================== 登录态(底座注入) ====================
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)。请先在壳子重新登录 HR 平台后重试。")
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
# ==================== commonQuery 前端加密(与 xq0035/xq0037 同源实现) ====================
_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",
}
# ==================== 动态日期参数 ====================
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",
}
# ==================== 合同台账(生效中合同) ====================
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")
def query_active_contract(session, base_code):
"""按工号在【劳动关系→合同台账→生效中合同】Tab 精准匹配生效合同。
Returns:
dict {contract_id, base_id, staff_name, contract_start_date, contract_end_date};未找到返回 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
# ==================== 合同签署单位(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")
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 ""
# ==================== 员工花名册(联系方式核对:hr_staff_base.mobile_phone) ====================
ROSTER_ID_STAFF_BASE = "1116da64-b094-11ea-b588-14187743d052"
TABLE_ID_STAFF_BASE = "assemble-hr_staff_base"
QUERY_STAFF_BASE_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
f"{ROSTER_ID_STAFF_BASE}/queryRealTimeData.mc")
# 花名册查询专用角色集(缺角色会返回空数据;与 CURRENT_ROLE_IDS 的差异点)
STAFF_ROSTER_ROLE_IDS = ("62367974-3904-409c-849a-2c3b0edcaf44,"
"f30200a0-2154-4692-8e58-7d2758d9bb82,"
"POST_SYS_ADMIN,renshi")
# 花名册组织树(缺则空数据)
STAFF_ROSTER_TREE_CODE = "cq37du"
def query_staff_roster(session, base_code):
"""按工号查员工花名册(queryRealTimeData.mc),返回该员工行 dict;无此人返回 None。
要点(与 xq0035/xq0037 同源):
- 响应行在 datas(非试用期台账的 jsonList,做兼容回退);
- 补 person_status in (1,4)(在职+返聘),否则服务端默认视图可能漏返聘/超龄人员;
- 联系方式字段 = hr_staff_base.mobile_phone。
Raises:
LoginRequiredError: 登录态失效(含 Nosession JSON 伪装响应)
"""
status_cond = {"queryField": "`hr_staff_base.person_status`", "leftBracket": "(",
"queryType": "in", "queryValue": "1,4", "queryText": "1,4",
"rightBracket": ")", "logic": "AND", "inputType": "multipleSelect"}
common_query = _encode_common_query(
[status_cond, _build_like_condition("hr_staff_base.base_code", str(base_code).strip())])
params = _build_query_params(ROSTER_ID_STAFF_BASE, TABLE_ID_STAFF_BASE,
common_query, menu_name="员工花名册")
params["struTreeCode"] = STAFF_ROSTER_TREE_CODE
params["currentRoleIds"] = STAFF_ROSTER_ROLE_IDS
params.update(_get_date_params())
resp = _request_retry("POST", QUERY_STAFF_BASE_URL, session, data=params)
try:
d = resp.json()
except ValueError:
raise LoginRequiredError("员工花名册查询返回非 JSON,登录态可能失效。")
if str(d.get("state")) == "Nosession":
raise LoginRequiredError(f"员工花名册查询返回 Nosession:{d.get('meg') or '会话过期,请重新登录!'}")
lst = d.get("datas") or d.get("jsonList") or []
return lst[0] if lst else None
# ==================== 手机号唯一校验(写联系方式前置闸门) ====================
# HR 花名册「编辑→保存」前端会先调本接口校验号码唯一(2026-11-09 JS 逆向 + 实测):
# 字段 hr_staff_base.mobile_phone 配置 ajaxSql=sql_hr_staff_base_mobile_phone_unique_module_conf、
# ajaxSqlType=0、ajaxValidate={"staffId":"businessKey","mobile_phone":"mobile_phone"}
# -> POST /HrTableEngine/ajaxValidate.mc?sqlId=<ajaxSql>
# data: staffId=<本人 base_id,排除自己> / mobile_phone=<号码> / version=1.0 / formParams=<表单JSON>
# -> state=="1" 通过;state=="0" 重复(meg 即提示,如「系统已存在重复的手机号!」)
# saveTableData 接口不跑这段校验,所以接口改号码前必须自己调一次,否则会写出重复号码。
VALIDATE_PHONE_SQL = "sql_hr_staff_base_mobile_phone_unique_module_conf"
VALIDATE_URL = f"{HR_BASE_URL}/RedseaPlatform/HrTableEngine/ajaxValidate.mc"
def validate_mobile_phone_unique(session, base_id, phone, form_params=None):
"""调用 HR 花名册同款手机号唯一校验(前端「编辑→保存」用的 ajaxValidate)。
Args:
base_id: 本人 hr_staff_base.base_id(前端 staffId 传它,用于排除自己)
phone: 待写入/待校验的手机号
form_params: 可选,随请求的整表单 JSON(前端传 #custom-form 序列化结果;
该 SQL 只用到 staffId/mobile_phone,缺省传必要字段即可)
Returns:
(ok, meg);ok=False 表示号码重复(meg 为服务端提示)
Raises:
LoginRequiredError: 登录态失效(非 JSON / Nosession)
"""
if not base_id:
return False, "缺少 base_id,无法做手机号唯一校验"
data = {
"staffId": base_id,
"mobile_phone": str(phone or ""),
"version": "1.0",
"formParams": json.dumps(form_params or {"mobile_phone": str(phone or "")},
ensure_ascii=False),
}
resp = _request_retry("POST", VALIDATE_URL,
session, data=data, params={"sqlId": VALIDATE_PHONE_SQL})
try:
d = resp.json()
except ValueError:
raise LoginRequiredError("手机号唯一校验返回非 JSON,登录态可能失效。")
if str(d.get("state")) == "Nosession":
raise LoginRequiredError(
f"手机号唯一校验返回 Nosession:{d.get('meg') or '会话过期,请重新登录!'}")
if str(d.get("state")) == "1":
return True, str(d.get("meg") or "")
return False, str(d.get("meg") or "系统已存在重复的手机号!")
# ==================== 日期工具 ====================
def _to_date(val):
"""统一为 date:支持毫秒时间戳 / datetime / yyyy-MM-dd 字符串;失败返回 None。"""
if val is None or val == "":
return None
if isinstance(val, datetime):
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表格(名单来源:续签名单到期跟进-月更新) ====================
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
AITABLE_BASE_ID = "YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA"
AITABLE_OPERATOR_UNIONID = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号(固定操作人,勿用测试号)
AITABLE_PAGE_SIZE = 100 # records/list 单页最大 100
AITABLE_WRITE_BATCH = 20 # 回写单次条数(≤100 即可,保守分批)
AITABLE_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
AITABLE_TOKEN_TTL = 3600 # 钉钉 accessToken 有效期兜底
_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
# ==================== 影刀全局变量兼容容器(messages) ====================
glv = {}
def _set_glv(name, value):
"""写入全局变量容器(插件环境供入口/日志读取;原影刀场景语义保持一致)。"""
try:
glv[name] = value
except Exception:
pass