refactor(tests): 归档旧版HRBP测试文件,新增新版测试辅助脚本和雇主险WPS可行性验证
本次提交主要包含以下内容: 1. 归档tests/hrbp目录下的旧版测试文件至tests/_app_蓝图版归档目录 2. 新增tests/_app_蓝图版归档/hrbp目录下的新版测试辅助脚本和测试用例 3. 新增雇主险场景下的WPS COM可行性验证脚本 4. 更新README.md中关于tests目录的说明,明确各子目录用途 5. 更新XQ0035工作流相关文件中的操作人UnionID,更换为人资专用号 6. 修复试用期变更脚本中日期转换的问题,确保AI表格时间戳正确转换为日期格式 7. 归档XQ0035工作流下的旧版测试脚本至测试归档目录
This commit is contained in:
@@ -1,166 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉单聊推送(文本 / 文件)— 外部终端自测版,含重名处理"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe"
|
||||
|
||||
# ↓↓↓ 配置区(测试时改这里)↓↓↓
|
||||
RECIPIENT_USER_ID = "37036359" # 接收人 userId(发文本用)
|
||||
RECIPIENT_OPEN_ID = "" # 接收人 openDingTalkId(发文件用;留空则按 RECIPIENT_NAME 查询)
|
||||
RECIPIENT_NAME = "张峻杰" # 接收人姓名(OPEN_ID 为空时用于查询,可留空)
|
||||
MESSAGE_TEXT = "测试文件推送"
|
||||
FILE_PATH = r"C:\Users\admin\Desktop\test.xlsx" # 要推送的本地文件路径;留空则只发文本
|
||||
# ↑↑↑ ↑↑↑
|
||||
|
||||
|
||||
class DwsError(RuntimeError):
|
||||
"""dws 命令执行失败;code 为上游 server_error_code(如 11056=会话不存在)"""
|
||||
def __init__(self, message: str, code: str = ""):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _extract_error_code(text: str) -> str:
|
||||
"""从 dws 错误输出里尽量提取 server_error_code"""
|
||||
try:
|
||||
data = json.loads(text[text.find("{"):])
|
||||
return str(data.get("error", {}).get("server_error_code") or "")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _run_dws(cmd_list) -> dict:
|
||||
"""执行 dws 命令并返回完整 JSON(含 success/result 顶层字段)"""
|
||||
result = subprocess.run(cmd_list, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace")
|
||||
if result.returncode != 0:
|
||||
raise DwsError(f"命令失败: {result.stderr.strip()}",
|
||||
code=_extract_error_code(result.stderr))
|
||||
raw = result.stdout
|
||||
data = json.loads(raw[raw.find("{"):])
|
||||
if not data.get("success"):
|
||||
raise DwsError(f"命令未成功: {data}",
|
||||
code=_extract_error_code(raw))
|
||||
return data
|
||||
|
||||
|
||||
def resolve_open_id(name: str, user_id: str = "") -> str:
|
||||
"""按姓名查询 openDingTalkId;同名多人时优先用 userId 精确匹配,无 userId 才列候选"""
|
||||
data = _run_dws([DWS_BIN, "contact", "user", "search",
|
||||
"--query", name, "--format", "json"])
|
||||
users = data.get("result") or []
|
||||
if not users:
|
||||
raise RuntimeError(f"未找到姓名为「{name}」的成员")
|
||||
|
||||
if len(users) == 1:
|
||||
u = users[0]
|
||||
print(f"👤 命中 1 人: {u['name']} | userId={u['userId']} | {u.get('title') or '无职位'}")
|
||||
return u["openDingTalkId"]
|
||||
|
||||
# 同名多人:优先用 userId 精确定位(用户手上有各候选的 userId)
|
||||
if user_id:
|
||||
for u in users:
|
||||
if u.get("userId") == user_id:
|
||||
print(f"👤 按 userId 命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
|
||||
return u["openDingTalkId"]
|
||||
|
||||
# 同名多人且无匹配 userId:批量拉详情(含部门)帮助区分,禁止默认选第一个
|
||||
ids = ",".join(u["userId"] for u in users)
|
||||
detail_data = _run_dws([DWS_BIN, "contact", "user", "get",
|
||||
"--ids", ids, "--format", "json"])
|
||||
details = detail_data.get("result") or []
|
||||
info_map = {d["orgEmployeeModel"]["orgUserId"]: d for d in details}
|
||||
|
||||
hints = []
|
||||
for u in users:
|
||||
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
|
||||
depts = org_model.get("depts") or []
|
||||
dept = ",".join(x.get("deptName", "") for x in depts)
|
||||
hints.append(
|
||||
f" {u.get('name')} | userId={u.get('userId')} | "
|
||||
f"部门={dept or '未知'} | 职位={org_model.get('orgTitle') or u.get('title') or '未知'}"
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"「{name}」有 {len(users)} 个同名,请在配置里填 RECIPIENT_OPEN_ID:\n" + "\n".join(hints)
|
||||
)
|
||||
|
||||
|
||||
def get_chat_space_id(open_id: str) -> str:
|
||||
"""获取单聊会话共享空间 ID;无会话(11056 或缺字段)时返回空串"""
|
||||
data = _run_dws([DWS_BIN, "chat", "conversation-info",
|
||||
"--open-dingtalk-id", open_id, "--format", "json"])
|
||||
try:
|
||||
return data["result"]["conversationInfo"]["extension"].get("newCSpaceIdIM", "")
|
||||
except (KeyError, TypeError, AttributeError):
|
||||
return ""
|
||||
|
||||
|
||||
def upload_file(space_id: str, file_path: str) -> dict:
|
||||
data = _run_dws([DWS_BIN, "drive", "upload",
|
||||
"--file", file_path, "--space-id", space_id,
|
||||
"--format", "json"])
|
||||
return data["result"]
|
||||
|
||||
|
||||
def get_dentry(file_id: str, space_id: str) -> dict:
|
||||
data = _run_dws([DWS_BIN, "drive", "info",
|
||||
"--node", file_id, "--space-id", space_id,
|
||||
"--format", "json"])
|
||||
return data["result"]
|
||||
|
||||
|
||||
def send_text(user_id: str, text: str):
|
||||
_run_dws([DWS_BIN, "chat", "message", "send",
|
||||
"--user", user_id, "--text", text, "--format", "json"])
|
||||
print(f"✅ 文本已发送: {text}")
|
||||
|
||||
|
||||
def send_file(open_id: str, file_path: str, user_id: str = ""):
|
||||
# 获取会话空间 ID;无会话(11056 或返回缺字段)时 space_id 为空
|
||||
try:
|
||||
space_id = get_chat_space_id(open_id)
|
||||
except DwsError as e:
|
||||
if e.code != "11056":
|
||||
raise
|
||||
space_id = ""
|
||||
|
||||
if not space_id:
|
||||
if not user_id:
|
||||
raise RuntimeError("拿不到会话空间 ID 且未提供 userId,无法发文件")
|
||||
print("ℹ️ 对方未建立会话,先发送一条文本建立会话…")
|
||||
send_text(user_id, "建立会话")
|
||||
space_id = get_chat_space_id(open_id)
|
||||
|
||||
if not space_id:
|
||||
raise RuntimeError("建立会话后仍拿不到会话空间 ID(newCSpaceIdIM),请检查")
|
||||
|
||||
up = upload_file(space_id, file_path)
|
||||
info = get_dentry(up["fileId"], up["spaceId"])
|
||||
_run_dws([DWS_BIN, "chat", "message", "send",
|
||||
"--open-dingtalk-id", open_id,
|
||||
"--msg-type", "file",
|
||||
"--dentry-id", info["dentryId"],
|
||||
"--space-id", up["spaceId"],
|
||||
"--file-name", info["name"],
|
||||
"--file-type", info.get("extension", "file"),
|
||||
"--file-path", info.get("path", "/" + info["name"]),
|
||||
"--file-size", str(info["fileSize"]),
|
||||
"--format", "json"])
|
||||
print(f"✅ 文件已发送: {os.path.basename(file_path)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
open_id = RECIPIENT_OPEN_ID or (resolve_open_id(RECIPIENT_NAME, RECIPIENT_USER_ID) if RECIPIENT_NAME else "")
|
||||
|
||||
if open_id:
|
||||
print(f"🔑 接收人 openDingTalkId: {open_id}") # 打印查询到的 OPEN_ID
|
||||
|
||||
if MESSAGE_TEXT:
|
||||
send_text(RECIPIENT_USER_ID, MESSAGE_TEXT)
|
||||
|
||||
if FILE_PATH:
|
||||
if not open_id:
|
||||
raise RuntimeError("发文件需要 openDingTalkId:请填 RECIPIENT_OPEN_ID 或 RECIPIENT_NAME")
|
||||
send_file(open_id, FILE_PATH, RECIPIENT_USER_ID)
|
||||
@@ -1,181 +0,0 @@
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# 自定义 Base64 字符表(索引0~64,64为填充字符)
|
||||
CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
PAD_CHAR = '7' # 填充字符(索引64)
|
||||
SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
# 反向映射表(解码用)
|
||||
CUSTOM_REV = {ch: idx for idx, ch in enumerate(CUSTOM_CHARS)}
|
||||
|
||||
# ---------- 自定义 Base64 编码 ----------
|
||||
def custom_base64_encode(data: bytes) -> str:
|
||||
"""
|
||||
使用自定义字符表进行 Base64 编码。
|
||||
data: 已 UTF-8 编码的字节序列
|
||||
返回: 编码后的字符串(填充使用 '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)
|
||||
|
||||
# ---------- 自定义 Base64 解码 ----------
|
||||
def custom_base64_decode(s: str) -> bytes:
|
||||
"""
|
||||
使用自定义字符表解码 Base64 字符串。
|
||||
返回原始 UTF-8 字节序列。
|
||||
"""
|
||||
# 过滤掉不属于字符表的字符(与前端一致)
|
||||
filtered = ''.join(ch for ch in s if ch in CUSTOM_REV)
|
||||
result = []
|
||||
for i in range(0, len(filtered), 4):
|
||||
chunk = filtered[i:i+4]
|
||||
# 补足4个字符(使用填充字符'7')
|
||||
while len(chunk) < 4:
|
||||
chunk += PAD_CHAR
|
||||
enc1 = CUSTOM_REV[chunk[0]]
|
||||
enc2 = CUSTOM_REV[chunk[1]]
|
||||
enc3 = CUSTOM_REV[chunk[2]]
|
||||
enc4 = CUSTOM_REV[chunk[3]]
|
||||
|
||||
b1 = ((enc1 << 2) | (enc2 >> 4)) & 0xFF
|
||||
b2 = ((enc2 << 4) | (enc3 >> 2)) & 0xFF
|
||||
b3 = ((enc3 << 6) | enc4) & 0xFF
|
||||
|
||||
result.append(b1)
|
||||
if enc3 != 64:
|
||||
result.append(b2)
|
||||
if enc4 != 64:
|
||||
result.append(b3)
|
||||
return bytes(result)
|
||||
|
||||
# ---------- 加密(编码)----------
|
||||
def encode_common_query(query_list: list) -> str:
|
||||
"""
|
||||
将查询条件列表(Python 对象)加密为 commonQuery 字符串。
|
||||
参数 query_list: 与前端格式一致的列表,例如:
|
||||
[
|
||||
{"queryField": "`hr_staff_move_info.MOVE_DATE`", ...},
|
||||
...
|
||||
]
|
||||
返回: 加密后的字符串(可直接用于表单提交)
|
||||
"""
|
||||
# 1. 转为 JSON 字符串(无空格,与前端 JSON.stringify 一致)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
# 2. URI 编码(模拟 encodeURIComponent:不编码 ! ' ( ) * - . _ ~)
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 转为 UTF-8 字节
|
||||
utf8_bytes = uri_encoded.encode('utf-8')
|
||||
# 4. 自定义 Base64 编码
|
||||
base64_str = custom_base64_encode(utf8_bytes)
|
||||
# 5. 追加盐值
|
||||
en_str = base64_str + SALT
|
||||
# 6. 重排:前2位 + 后3位 + 中间部分
|
||||
first = en_str[:2]
|
||||
second = en_str[2:-3]
|
||||
third = en_str[-3:]
|
||||
return first + third + second
|
||||
|
||||
# ---------- 解密(解码)----------
|
||||
def decode_common_query(encrypted: str) -> list:
|
||||
"""
|
||||
将加密的 commonQuery 字符串还原为原始查询条件列表。
|
||||
参数 encrypted: 加密后的字符串
|
||||
返回: 原始的查询条件列表(Python 对象)
|
||||
"""
|
||||
# 1. 逆向重排:前2位 + 中间部分 + 后3位
|
||||
first = encrypted[:2]
|
||||
third = encrypted[2:5]
|
||||
second = encrypted[5:]
|
||||
orgin = first + second + third
|
||||
# 2. 去除盐值
|
||||
if orgin.endswith(SALT):
|
||||
orgin = orgin[:-len(SALT)]
|
||||
else:
|
||||
# 容错:如果盐值不完整,尝试匹配前缀(有时末尾会缺失几个字符)
|
||||
if orgin.endswith(SALT[:-3]):
|
||||
orgin = orgin[:-(len(SALT)-3)]
|
||||
# 3. 自定义 Base64 解码
|
||||
utf8_bytes = custom_base64_decode(orgin)
|
||||
uri_encoded = utf8_bytes.decode('utf-8')
|
||||
# 4. URI 解码
|
||||
json_str = urllib.parse.unquote(uri_encoded)
|
||||
# 5. 解析 JSON
|
||||
return json.loads(json_str)
|
||||
|
||||
# ---------- 辅助函数(可选)----------
|
||||
def build_date_range_query(field: str, start_date: str, end_date: str) -> list:
|
||||
"""
|
||||
构造一个标准的日期范围查询列表。
|
||||
参数:
|
||||
field: 字段名(含反引号),如 "`hr_staff_move_info.MOVE_DATE`"
|
||||
start_date: 开始日期,如 "2026-08-01"
|
||||
end_date: 结束日期,如 "2026-08-30"
|
||||
返回: 符合前端格式的查询条件列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "(",
|
||||
"queryType": ">=",
|
||||
"queryValue": start_date,
|
||||
"queryText": "",
|
||||
"rightBracket": "",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
},
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "",
|
||||
"queryType": "<=",
|
||||
"queryValue": end_date,
|
||||
"queryText": "",
|
||||
"rightBracket": ")",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
}
|
||||
]
|
||||
|
||||
# ---------- 示例 ----------
|
||||
if __name__ == "__main__":
|
||||
# 示例:查询 2026-08-01 至 2026-08-30 的调动记录
|
||||
field = "`hr_staff_move_info.MOVE_DATE`"
|
||||
query = build_date_range_query(field, "2026-08-01", "2026-08-30")
|
||||
|
||||
# 加密
|
||||
encrypted = encode_common_query(query)
|
||||
print("加密后的 commonQuery:")
|
||||
print(encrypted)
|
||||
print()
|
||||
|
||||
# 解密验证
|
||||
decoded = decode_common_query(encrypted)
|
||||
print("解密后的查询条件:")
|
||||
print(json.dumps(decoded, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
|
||||
# 验证是否与原始一致
|
||||
print("解密后与原始一致:", decoded == query)
|
||||
File diff suppressed because one or more lines are too long
@@ -1,57 +0,0 @@
|
||||
import win32com.client
|
||||
from openpyxl import load_workbook
|
||||
import os
|
||||
|
||||
|
||||
def recalc_excel_by_wps_com(file_path: str):
|
||||
"""
|
||||
使用WPS COM重算表格,保存计算缓存到文件
|
||||
仅支持 WPS专业版 / MS‑Excel
|
||||
"""
|
||||
abs_path = os.path.abspath(file_path)
|
||||
app = None
|
||||
try:
|
||||
# 尝试WPS表格 COM
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
|
||||
# UpdateLinks=2 更新外部链接;你是本文件公式也带上无妨
|
||||
wb = app.Workbooks.Open(abs_path, UpdateLinks=2)
|
||||
|
||||
# 强制完整重算全部公式
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 关键:保存,把计算结果缓存写入xlsx磁盘
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"COM执行异常: {e}")
|
||||
raise
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
del app
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
file = r"C:\Users\admin\Desktop\test.xlsx"
|
||||
|
||||
# ==========1. openpyxl写入测试数据(模拟粘贴数值到目标表)==========
|
||||
wb = load_workbook(file)
|
||||
ws = wb.active
|
||||
ws["A2"] = 10
|
||||
ws["B2"] = 20
|
||||
# C2单元格预先在文件内写好公式 =A2+B2
|
||||
wb.save(file)
|
||||
wb.close()
|
||||
|
||||
# ==========2.调用WPS COM后台重算并保存缓存==========
|
||||
recalc_excel_by_wps_com(file)
|
||||
|
||||
# ==========3. openpyxl读取计算后的值==========
|
||||
wb_final = load_workbook(file, data_only=True)
|
||||
val = wb_final.active["C2"].value
|
||||
print(f"C2计算结果 = {val}")
|
||||
wb_final.close()
|
||||
@@ -27,7 +27,7 @@ import shutil
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "desktop", "electron-shell", "python")) # 壳内置 webhost 运行时子集
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "plugins", "XQ0001-0100")) # 插件包
|
||||
|
||||
@@ -42,7 +42,7 @@ import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
# ==================== 测试目录与结果收集 ====================
|
||||
WORK_DIR = os.path.join(REPO_ROOT, "tests", "_xq0002_smoke_data")
|
||||
WORK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_xq0002_smoke_data")
|
||||
if os.path.isdir(WORK_DIR):
|
||||
shutil.rmtree(WORK_DIR)
|
||||
CATEGORY_DIR = os.path.join(WORK_DIR, "三十七度")
|
||||
Reference in New Issue
Block a user