feat: 新增OA工作沟通推送模块,优化考勤异常查询逻辑与钉钉推送能力
1. 新增OA工作沟通推送全流程模块: - 实现人员搜索、多附件上传、工作沟通提交完整链路 - 提供一键推送入口send_work_communication,支持多接收人、富文本与多类型沟通 - 补充配套配置常量与接口封装 - 添加抓包调试脚本与完整需求/开发文档 2. 考勤异常处理模块重构: - 将默认查询范围从「当月」改为「上周(周一~周日)」 - 统一app/影刀版的日期范围计算逻辑 - 新增班段合成、请假日期修复逻辑,优化导出报表字段 - 更新需求文档与开发文档,同步功能变更 3. 钉钉推送工具优化: - 修复窗口激活逻辑,避免批量推送时抢焦点导致窗口失焦 - 新增安全点击与鼠标状态兜底,防止左键卡死 - 优化搜索与会话打开流程,提升稳定性
This commit is contained in:
@@ -35,6 +35,11 @@ from app.service.hrbp.oa.common.oa_api.punch import (
|
||||
fetch_punch_record_page,
|
||||
get_punch_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.work_communication import (
|
||||
search_person,
|
||||
upload_attachment,
|
||||
submit_work_communication,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
@@ -52,4 +57,7 @@ __all__ = [
|
||||
"get_leave_records",
|
||||
"fetch_punch_record_page",
|
||||
"get_punch_records",
|
||||
"search_person",
|
||||
"upload_attachment",
|
||||
"submit_work_communication",
|
||||
]
|
||||
|
||||
@@ -45,6 +45,7 @@ def oa_request_json(
|
||||
params: dict,
|
||||
label: str,
|
||||
timeout: int = 20,
|
||||
headers: dict = None,
|
||||
):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。
|
||||
|
||||
@@ -55,6 +56,8 @@ def oa_request_json(
|
||||
params: 请求参数
|
||||
label: 接口中文名(用于报错信息)
|
||||
timeout: 请求超时秒数,默认 20
|
||||
headers: 附加请求头(显式传入可规避 DrissionPage 对 session 级
|
||||
Referer 头的 KeyError 问题),可空
|
||||
|
||||
Returns:
|
||||
解析后的 JSON 字典
|
||||
@@ -63,7 +66,7 @@ def oa_request_json(
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
if method.upper() == "GET":
|
||||
session.get(url, params=params, timeout=timeout)
|
||||
session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
else:
|
||||
session.post(url, data=params, timeout=timeout)
|
||||
session.post(url, data=params, timeout=timeout, headers=headers)
|
||||
return _handle_response(session.response, label)
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: work_communication.py
|
||||
@Description: OA 工作沟通推送接口:搜索接收人 / 上传附件 / 提交工作沟通。
|
||||
对应需求文档 aa.md(OA工作沟通自动化发送)。
|
||||
附件上传采用「普通上传」流程(getuserkey → 二进制上传 → submit 绑定),
|
||||
暂不实现 MD5 秒传(文件已存在时也走完整上传,保证可用性,后续需要再优化)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
BASE_URL,
|
||||
PERSON_SEARCH_URL,
|
||||
ATT_UPLOAD_URL,
|
||||
ATT_UPLOADER_URL,
|
||||
WORK_COMMUNICATION_ADD_URL,
|
||||
KM_COLLABORATE_SAVE_URL,
|
||||
FD_CONTENT_PREFIX,
|
||||
FD_CATEGORY_MAP,
|
||||
FD_CATEGORY_DEFAULT,
|
||||
KM_COLLABORATE_MODEL,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json, OALoginExpiredError
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 附件二进制上传时的请求头(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"{BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
def _check_response(resp, label: str):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。供返回 XML 或纯文本等非 JSON 的接口使用。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或状态码异常
|
||||
OALoginExpiredError: 会话失效(接口被重定向到登录页返回 HTML)
|
||||
"""
|
||||
if not resp:
|
||||
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 search_person(session: SessionPage, keyword: str, org_type: str = "15") -> Optional[tuple]:
|
||||
"""
|
||||
按工号或姓名搜索人员,返回 (person_id, person_name)。
|
||||
|
||||
- 精确匹配优先:姓名或 ID 与关键字完全一致时直接命中;
|
||||
- 模糊命中多个时默认取第一个,并记录警告。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
keyword: 工号或姓名(支持模糊)
|
||||
org_type: 组织类型,默认 "15"(与 aa.md 一致)
|
||||
|
||||
Returns:
|
||||
(person_id, person_name) 元组;未找到返回 None
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
session.get(PERSON_SEARCH_URL, params=params, timeout=20)
|
||||
resp = _check_response(session.response, "人员搜索")
|
||||
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
logger.warning("人员搜索[%s]响应解析失败: %s", keyword, e)
|
||||
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:
|
||||
logger.warning("未搜索到人员: %s", keyword)
|
||||
return None
|
||||
|
||||
# 精确匹配优先(工号/姓名全等)
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
if len(matches) > 1:
|
||||
logger.warning("关键字[%s]模糊匹配到 %d 人,默认取第一个: %s", keyword, len(matches), matches[0])
|
||||
pid, pname = matches[0]
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
def upload_attachment(session: SessionPage, file_path: str) -> str:
|
||||
"""
|
||||
上传单个附件,返回最终附件 ID(attid)。
|
||||
|
||||
普通上传流程(不实现 MD5 秒传,保证可用性):
|
||||
1. 获取 userkey(上传凭证)
|
||||
2. 上传二进制内容,得到 filekey
|
||||
3. submit 绑定附件,得到最终 attid
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
file_path: 附件文件路径(相对路径会自动转绝对路径)
|
||||
|
||||
Returns:
|
||||
最终附件 ID(attid)
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 附件文件不存在
|
||||
RuntimeError: 上传任一步骤失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
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))
|
||||
# 按扩展名推断 MIME 类型(aa.md 原实现硬编码 xlsx,这里通用化支持任意附件类型)
|
||||
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)),
|
||||
)
|
||||
# fdSign = Base64(文件名) 并去掉 + / = 字符(与 swf_attachment.js 的 createAttMainInfo 一致)
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 上传三步统一显式带上 UA/Referer 等请求头(不设 session 级 headers,
|
||||
# 避免触发 DrissionPage 4.1.1.4 对 session 级 Referer 头的 KeyError bug)
|
||||
|
||||
# ---- 步骤1:获取 userkey ----
|
||||
params1 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "getuserkey",
|
||||
"format": "json",
|
||||
"filesize": file_size,
|
||||
"md5": "",
|
||||
"fileName": file_name,
|
||||
"isSupportDirect": "false",
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp1 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params1, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
logger.info(" 1. 获取 userkey 成功")
|
||||
|
||||
# ---- 步骤2:上传二进制(userkey 需随请求带上,否则报「附件上传密钥为空」) ----
|
||||
uploader_url = f"{ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
files = {"file": (file_name, open(file_path, "rb"), file_type)}
|
||||
data2 = {
|
||||
"id": "WU_FILE_0",
|
||||
"name": file_name,
|
||||
"type": file_type,
|
||||
"lastModifiedDate": last_modified,
|
||||
"size": file_size,
|
||||
}
|
||||
session.post(uploader_url, data=data2, files=files, timeout=60, headers=_DEFAULT_HEADERS)
|
||||
resp2 = _check_response(session.response, "附件上传-二进制")
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
logger.info(" 2. 二进制上传成功, filekey: %s...", filekey[:16])
|
||||
|
||||
# ---- 步骤3:submit 绑定附件,获取最终 attid ----
|
||||
params3 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "submit",
|
||||
"format": "json",
|
||||
"filekey": filekey,
|
||||
"filename": file_name,
|
||||
"fdKey": "attachment",
|
||||
"fdModelName": KM_COLLABORATE_MODEL,
|
||||
"fdAttType": "byte",
|
||||
"width": "null",
|
||||
"height": "null",
|
||||
"proportion": "true",
|
||||
"fdSign": fd_sign,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp3 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params3, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
logger.info(" 3. 提交绑定成功, attid: %s", attid)
|
||||
return attid
|
||||
|
||||
|
||||
def _encode_fd_content(content: str) -> str:
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。
|
||||
|
||||
真实抓包确认:CKEditor 保存时 fdContent 形如
|
||||
`䙉堠䵅䉁卅㘴{<base64(HTML)>}`,其中前缀为固定字节,花括号内是内容的 base64。
|
||||
"""
|
||||
return FD_CONTENT_PREFIX + "{" + base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session: SessionPage) -> tuple:
|
||||
"""打开新建工作沟通页(method=add),解析出草稿 fdId 与通知方式随机字段名。
|
||||
|
||||
Returns:
|
||||
(fd_id, notify_field_name):fdId 隐藏域值;`__notify_type_<随机id>` 字段名
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
RuntimeError: 页面解析失败
|
||||
"""
|
||||
session.get(WORK_COMMUNICATION_ADD_URL, timeout=20)
|
||||
resp = _check_response(session.response, "新建工作沟通-取页面")
|
||||
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 ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
logger.info("获取新建草稿 fdId: %s, 通知方式字段: %s", fd_id, notify_field)
|
||||
return fd_id, notify_field
|
||||
|
||||
|
||||
def submit_work_communication(
|
||||
session: SessionPage,
|
||||
receiver_ids: Union[str, List[str]],
|
||||
receiver_names: Union[str, List[str]],
|
||||
subject: str,
|
||||
content: str,
|
||||
attachment_ids: Union[str, List[str]] = None,
|
||||
creator_id: str = None,
|
||||
category_id: str = FD_CATEGORY_DEFAULT,
|
||||
) -> str:
|
||||
"""
|
||||
提交工作沟通(新建),成功返回沟通文档 ID(fdId)。
|
||||
|
||||
真实提交端点:`kmCollaborateMain.do?method=save&s_seq=1`(aa.md 中的 user.jsp 为错误端点)。
|
||||
流程:先打开新建页取草稿 fdId 与通知方式随机字段,再以相同表单结构 POST 保存。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
receiver_ids: 接收人 ID,单个字符串或列表(多个以「;」分号分隔)
|
||||
receiver_names: 接收人姓名,单个字符串或列表(顺序与 ID 一致)
|
||||
subject: 标题
|
||||
content: 内容(支持 HTML 富文本)
|
||||
attachment_ids: 附件 ID(attid),单个字符串或列表(多个以「;」分号分隔),可空
|
||||
creator_id: 创建人(当前操作人)ID,必填
|
||||
category_id: 沟通类型,可传中文名(如「工作安排」)或类型 ID,
|
||||
默认「工作安排」(config.FD_CATEGORY_DEFAULT)
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 提交失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,请传入当前操作人的用户 ID")
|
||||
|
||||
# 沟通类型:支持中文名 -> ID 映射,空值回退默认「工作安排」(fdCategoryId 必填)
|
||||
if category_id in FD_CATEGORY_MAP:
|
||||
category_id = FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = FD_CATEGORY_DEFAULT
|
||||
|
||||
# 真实抓包确认:多人参与人 / 多附件 ID 在表单体里以「;」分号分隔(不是逗号)
|
||||
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 ""
|
||||
|
||||
# 1) 打开新建页,取草稿 fdId 与通知方式随机字段
|
||||
fd_id, notify_field = _get_add_page_fd_info(session)
|
||||
|
||||
# 2) 组装保存请求(结构对齐真实抓包的 method=save&s_seq=1 表单体)
|
||||
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": 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)
|
||||
|
||||
# 3) POST 保存
|
||||
session.post(KM_COLLABORATE_SAVE_URL, params={"method": "save", "s_seq": "1"}, data=data, timeout=30)
|
||||
resp = _check_response(session.response, "工作沟通提交")
|
||||
text = resp.text or ""
|
||||
|
||||
# 成功标志:返回「您的操作已成功!」提示页(自动关闭),而非数字 ID
|
||||
if "您的操作已成功" in text:
|
||||
logger.info("工作沟通发送成功, 文档ID: %s", fd_id)
|
||||
return fd_id
|
||||
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
Reference in New Issue
Block a user