feat(xq0002): 新增钉钉群通知推送功能,优化雇主险增减操作流程
This commit is contained in:
@@ -0,0 +1,357 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OA 工作沟通推送(work_communication.py 移植,适配插件底座)。
|
||||
|
||||
原影刀版用 DrissionPage SessionPage + 读共享 oa_cookies.json;插件版改为:
|
||||
- 登录态由底座注入(config.get_oa_session(),即 ctx.get_session("oa") 返回的
|
||||
requests.Session,已带 OA cookies),不读 cookie 文件
|
||||
- 请求直接用 requests.Session API(resp = session.get/post(...))
|
||||
|
||||
流程:解析接收人(工号/姓名 → 人员ID)→ 上传附件(getuserkey→二进制→submit绑定)→
|
||||
提交工作沟通(取新建页 fdId + 通知方式随机字段 → POST method=save 保存)。
|
||||
push_messages(messages) 逐条推送,返回 {success, message, doc_id, results}。
|
||||
"""
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{config.OA_BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入的 requests.Session) ====================
|
||||
def get_oa_session():
|
||||
"""取底座注入的 OA requests.Session;未登录时抛友好错误。"""
|
||||
session = config.get_oa_session()
|
||||
if session is None:
|
||||
raise RuntimeError("未注入 OA 登录态,请先在工作台(壳子)登录 OA 系统再运行本阶段")
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效。"""
|
||||
try:
|
||||
resp = session.get(config.TODO_COUNT_URL,
|
||||
params={"method": "sumTodoCount"}, timeout=10)
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text or ""
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
config.log(f"OA 会话校验异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 通用响应校验 ====================
|
||||
def _check_response(resp, label):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。返回 resp。"""
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def oa_request_json(session, method, url, params, label, timeout=20, headers=None):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验 → 返回 JSON。"""
|
||||
resp = (session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
if method.upper() == "GET"
|
||||
else session.post(url, data=params, timeout=timeout, headers=headers))
|
||||
resp = _check_response(resp, label)
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 人员搜索 ====================
|
||||
def search_person(session, keyword, org_type="15"):
|
||||
"""按工号或姓名搜索人员,返回 (person_id, person_name);未找到返回 None。"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp = _check_response(session.get(config.PERSON_SEARCH_URL, params=params, timeout=20),
|
||||
"人员搜索")
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
config.log(f"人员搜索[{keyword}]响应解析失败: {e}", "WARN")
|
||||
return None
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
if not matches:
|
||||
config.log(f"未搜索到人员: {keyword}", "WARN")
|
||||
return None
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
if len(matches) > 1:
|
||||
config.log(f"关键字[{keyword}]模糊匹配到 {len(matches)} 人,默认取第一个: {matches[0]}", "WARN")
|
||||
pid, pname = matches[0]
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
# ==================== 附件上传 ====================
|
||||
def upload_attachment(session, file_path):
|
||||
"""上传单个附件,返回最终附件 ID(attid)。getuserkey → 二进制上传 → submit 绑定。"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 1) 获取 userkey
|
||||
resp1 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "getuserkey", "format": "json",
|
||||
"filesize": file_size, "md5": "", "fileName": file_name,
|
||||
"isSupportDirect": "false", "s_ajax": "true",
|
||||
}, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
config.log(" 1. 获取 userkey 成功")
|
||||
|
||||
# 2) 上传二进制
|
||||
uploader_url = f"{config.ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
with open(file_path, "rb") as f:
|
||||
files = {"file": (file_name, f, file_type)}
|
||||
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
|
||||
"lastModifiedDate": last_modified, "size": file_size}
|
||||
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
|
||||
timeout=60, headers=_DEFAULT_HEADERS),
|
||||
"附件上传-二进制")
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
config.log(f" 2. 二进制上传成功, filekey: {filekey[:16]}...")
|
||||
|
||||
# 3) submit 绑定附件
|
||||
resp3 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "submit", "format": "json",
|
||||
"filekey": filekey, "filename": file_name, "fdKey": "attachment",
|
||||
"fdModelName": config.KM_COLLABORATE_MODEL, "fdAttType": "byte",
|
||||
"width": "null", "height": "null", "proportion": "true",
|
||||
"fdSign": fd_sign, "s_ajax": "true",
|
||||
}, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
config.log(f" 3. 提交绑定成功, attid: {attid}")
|
||||
return attid
|
||||
|
||||
|
||||
# ==================== 工作沟通提交 ====================
|
||||
def _encode_fd_content(content):
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
|
||||
return config.FD_CONTENT_PREFIX + "{" + \
|
||||
base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session):
|
||||
"""打开新建工作沟通页,解析出草稿 fdId、通知方式随机字段名、当前用户 ID。"""
|
||||
resp = _check_response(session.get(config.WORK_COMMUNICATION_ADD_URL, timeout=20),
|
||||
"新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
|
||||
creator_id = m3.group(1) if m3 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
config.log(f"获取新建草稿 fdId: {fd_id}, 通知方式字段: {notify_field}, "
|
||||
f"页面当前用户ID: {creator_id or '无'}")
|
||||
return fd_id, notify_field, creator_id
|
||||
|
||||
|
||||
def submit_work_communication(session, receiver_ids, receiver_names, subject, content,
|
||||
attachment_ids=None, creator_id=None,
|
||||
category_id=config.FD_CATEGORY_DEFAULT):
|
||||
"""提交工作沟通(新建),成功返回沟通文档 ID(fdId)。多值分隔符用「;」。"""
|
||||
if category_id in config.FD_CATEGORY_MAP:
|
||||
category_id = config.FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = config.FD_CATEGORY_DEFAULT
|
||||
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
fd_id, notify_field, page_creator_id = _get_add_page_fd_info(session)
|
||||
creator_id = creator_id or page_creator_id
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,且无法从新建页自动提取,请显式传入")
|
||||
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": config.KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo",
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
resp = _check_response(session.post(config.KM_COLLABORATE_SAVE_URL,
|
||||
params={"method": "save", "s_seq": "1"},
|
||||
data=data, timeout=30),
|
||||
"工作沟通提交")
|
||||
text = resp.text or ""
|
||||
if "您的操作已成功" in text:
|
||||
config.log(f"工作沟通发送成功, 文档ID: {fd_id}")
|
||||
return fd_id
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 一键推送入口 ====================
|
||||
def _to_list(value):
|
||||
"""把单个字符串或列表统一成列表。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(receiver_keywords, subject, content,
|
||||
attachment_paths=None, creator_id=None, category=None):
|
||||
"""发送单条工作沟通:解析接收人 → 上传附件 → 提交。返回沟通文档 ID。"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
session = get_oa_session()
|
||||
if not is_session_valid(session):
|
||||
raise OALoginExpiredError("OA 登录态已失效,请重新在工作台登录 OA")
|
||||
|
||||
# 1. 解析接收人
|
||||
receiver_ids, receiver_names, unresolved = [], [], []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
config.log(f"接收人[{kw}] -> {pname} (ID: {pid})")
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# 2. 上传附件(任一失败即整体失败)
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
config.log(f"附件[{path}] -> attid: {attid}")
|
||||
|
||||
# 3. 提交沟通
|
||||
return submit_work_communication(
|
||||
session=session, receiver_ids=receiver_ids, receiver_names=receiver_names,
|
||||
subject=subject, content=content, attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id, category_id=category)
|
||||
|
||||
|
||||
def _send_wrapped(receiver_keywords, subject, content, attachment_paths="",
|
||||
creator_id="", category="工作安排"):
|
||||
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
|
||||
try:
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=receiver_keywords, subject=subject, content=content,
|
||||
attachment_paths=attachment_paths or None, creator_id=creator_id or None,
|
||||
category=category)
|
||||
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
except Exception as e:
|
||||
config.log(f"工作沟通推送失败: {e}", "ERROR")
|
||||
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
|
||||
|
||||
def push_messages(messages):
|
||||
"""逐条推送工作沟通(messages 结构同告知书模块产出的 OA 推送数据)。
|
||||
messages 每条含 {receivers, subject, content, attachment_paths, category}。
|
||||
返回 {success, message, doc_id, results}。"""
|
||||
results = []
|
||||
for i, msg in enumerate(messages or [], 1):
|
||||
r = _send_wrapped(
|
||||
receiver_keywords=msg.get("receivers", []),
|
||||
subject=msg.get("subject", ""),
|
||||
content=msg.get("content", ""),
|
||||
attachment_paths=msg.get("attachment_paths", ""),
|
||||
creator_id=msg.get("creator_id", ""),
|
||||
category=msg.get("category", "工作安排"))
|
||||
results.append(r)
|
||||
config.log(f"[{i}/{len(messages or [])}] {r.get('message')}")
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
return {
|
||||
"success": ok == len(results),
|
||||
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
|
||||
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
|
||||
"results": results,
|
||||
}
|
||||
Reference in New Issue
Block a user