Files
37duAutomation/aa.md
T
puddy 3862bbfab2 feat: 新增OA工作沟通推送模块,优化考勤异常查询逻辑与钉钉推送能力
1. 新增OA工作沟通推送全流程模块:
   - 实现人员搜索、多附件上传、工作沟通提交完整链路
   - 提供一键推送入口send_work_communication,支持多接收人、富文本与多类型沟通
   - 补充配套配置常量与接口封装
   - 添加抓包调试脚本与完整需求/开发文档

2. 考勤异常处理模块重构:
   - 将默认查询范围从「当月」改为「上周(周一~周日)」
   - 统一app/影刀版的日期范围计算逻辑
   - 新增班段合成、请假日期修复逻辑,优化导出报表字段
   - 更新需求文档与开发文档,同步功能变更

3. 钉钉推送工具优化:
   - 修复窗口激活逻辑,避免批量推送时抢焦点导致窗口失焦
   - 新增安全点击与鼠标状态兜底,防止左键卡死
   - 优化搜索与会话打开流程,提升稳定性
2026-08-25 17:08:44 +08:00

16 KiB
Raw Blame History

📄 OA工作沟通自动化发送 - 需求文档

1. 项目背景

通过RPA技术,模拟浏览器行为调用OA系统后台接口,实现无界面、无需人工填写的工作沟通自动发送,支持:

  • 多接收人
  • 多附件
  • 自定义标题和内容(支持HTML富文本)

2. 业务流程概览

┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│  1.登录认证  │───▶│  2.搜索接收人 │───▶│  3.上传附件  │───▶│  4.提交沟通  │───▶│  5.确认结果  │
│  (Cookie)   │    │  (获取ID)   │    │  (获取attid)│    │  (user.jsp) │    │  (返回ID)   │
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘

3. 核心接口清单

步骤 接口 方法 关键参数 返回
搜索人员 /sys/common/dataxml.jsp GET key=工号/姓名 人员ID (XML)
获取上传凭证 /sysAttMain.do GET gettype=getuserkey userkey
MD5秒传校验 /sysAttMain.do GET gettype=checkMd5 md5Exists
上传二进制 /uploaderServlet POST file (二进制) filekey
提交绑定附件 /sysAttMain.do GET gettype=submit attid
提交沟通 /sys/ui/resources/user.jsp POST participantIds, docSubject, fdContent, attachmentIds 沟通ID

4. 数据结构说明

4.1 人员搜索返回(XML)

<data id="37b1d9a5c5834a98bc4274143ab53d10" name="夏一平" ... />

4.2 附件上传最终返回

{"attid":"1a037cb5b4a66d17f7224194c9995b29","status":"1"}

4.3 沟通提交参数

参数名 类型 必填 说明
fdId string 否 新建传空
participantIds string 是 接收人ID,多个逗号分隔
participantNames string 是 接收人姓名,多个逗号分隔,顺序与ID一致
docSubject string 是 标题
fdContent string 是 内容(支持HTML)
attachmentForms.attachment.attachmentIds string 否 附件ID,多个逗号分隔
docCreatorId string 是 创建人ID
fdNotifyType string 是 固定 todo
fdRemindersDay string 否 固定 2

🐍 完整代码

"""
OA工作沟通自动化发送脚本
支持:多接收人、多附件、HTML内容
依赖:requests, xml.etree.ElementTree
"""

import requests
import hashlib
import os
import base64
import time
import xml.etree.ElementTree as ET
from typing import List, Union, Optional

# ============================================================
#  配置区域(请根据实际情况修改)
# ============================================================

OA_BASE_URL = "https://oa.37du.co"  # OA系统根地址

# 登录方式1:已有Cookie(从浏览器导出)
COOKIE_STRING = ""  # 如 "JSESSIONID=xxx; Route=xxx"

# 登录方式2:账号密码(需要自行实现登录逻辑)
USERNAME = ""  # 工号
PASSWORD = ""  # 密码

# 当前操作人的ID(可通过搜索自己的工号获取)
CREATOR_ID = "37b1d9a5c5834a98bc4274143ab53d10"  # 替换为实际值

# ============================================================
#  工具函数
# ============================================================

def get_session() -> requests.Session:
    """获取已登录的Session"""
    session = requests.Session()
    
    # 方式1:设置已有Cookie
    if COOKIE_STRING:
        for cookie in COOKIE_STRING.split("; "):
            if "=" in cookie:
                key, value = cookie.split("=", 1)
                session.cookies.set(key, value)
        print("✅ 使用已有Cookie登录")
        return session
    
    # 方式2:账号密码登录(这里需要根据实际登录接口实现)
    if USERNAME and PASSWORD:
        # TODO: 实现具体登录逻辑
        # login_url = f"{OA_BASE_URL}/login.do"
        # session.post(login_url, data={"username": USERNAME, "password": PASSWORD})
        print("⚠️ 请实现登录逻辑,或使用COOKIE_STRING方式")
        return session
    
    print("⚠️ 未配置登录信息,请设置 COOKIE_STRING 或 USERNAME/PASSWORD")
    return session


def search_person(session: requests.Session, keyword: str) -> Optional[tuple]:
    """
    根据工号或姓名搜索人员
    :return: (person_id, person_name) 或 None
    """
    url = f"{OA_BASE_URL}/sys/common/dataxml.jsp"
    params = {
        "s_bean": "organizationDialogSearch",
        "orgType": "15",
        "deptLimit": "",
        "isExternal": "",
        "key": keyword,
        "s_ajax": "true"
    }
    
    try:
        resp = session.get(url, params=params)
        if resp.status_code != 200:
            print(f"❌ 搜索人员失败: HTTP {resp.status_code}")
            return None
        
        # 解析XML
        root = ET.fromstring(resp.text)
        data = root.find(".//data")
        if data is None:
            print(f"❌ 未找到人员: {keyword}")
            return None
        
        person_id = data.get("id")
        person_name = data.get("name")
        print(f"✅ 搜索到人员: {person_name} (ID: {person_id})")
        return person_id, person_name
    
    except Exception as e:
        print(f"❌ 搜索人员异常: {e}")
        return None


def upload_attachment(session: requests.Session, file_path: str) -> Optional[str]:
    """
    上传单个附件,返回 attid(最终附件ID)
    完整模拟了OA的5步上传流程
    """
    file_name = os.path.basename(file_path)
    file_size = str(os.path.getsize(file_path))
    
    # 计算MD5
    with open(file_path, 'rb') as f:
        md5_hash = hashlib.md5(f.read()).hexdigest()
    
    # 文件修改时间
    last_modified = time.strftime("%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
    
    # fdSign = Base64(文件名)
    fd_sign = base64.b64encode(file_name.encode()).decode()
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Referer": f"{OA_BASE_URL}/",
        "X-Requested-With": "XMLHttpRequest"
    }
    session.headers.update(headers)
    
    base_att_url = f"{OA_BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
    
    # ---- 步骤1:获取 userkey ----
    params1 = {
        "method": "handleAttUpload",
        "gettype": "getuserkey",
        "format": "json",
        "filesize": file_size,
        "md5": "",
        "fileName": file_name,
        "isSupportDirect": "false",
        "s_ajax": "true"
    }
    try:
        resp1 = session.get(base_att_url, params=params1)
        userkey = resp1.json().get("token", {}).get("header", {}).get("userkey")
        if not userkey:
            print(f"❌ 获取userkey失败: {resp1.text}")
            return None
        print(f"  ✅ 1. 获取userkey成功")
    except Exception as e:
        print(f"❌ 步骤1异常: {e}")
        return None
    
    # ---- 步骤2:MD5秒传校验 ----
    params2 = {
        "method": "handleAttUpload",
        "gettype": "checkMd5",
        "format": "json",
        "filesize": file_size,
        "md5": md5_hash,
        "fileName": file_name,
        "isSupportDirect": "false",
        "s_ajax": "true"
    }
    try:
        resp2 = session.get(base_att_url, params=params2)
        result2 = resp2.json()
        md5_exists = result2.get("md5Exists", False)
        print(f"  ✅ 2. MD5校验: {'已存在(秒传)' if md5_exists else '需上传'}")
    except Exception as e:
        print(f"❌ 步骤2异常: {e}")
        return None
    
    # ---- 步骤3:上传二进制(仅当文件不存在时) ----
    if not md5_exists:
        uploader_url = f"{OA_BASE_URL}/sys/attachment/uploaderServlet?gettype=upload&format=json"
        files = {
            'file': (file_name, open(file_path, 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        }
        data3 = {
            'id': 'WU_FILE_0',
            'name': file_name,
            'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'lastModifiedDate': last_modified,
            'size': file_size
        }
        try:
            resp3 = session.post(uploader_url, files=files, data=data3)
            filekey = resp3.json().get("filekey")
            if not filekey:
                print(f"❌ 上传二进制失败: {resp3.text}")
                return None
            print(f"  ✅ 3. 二进制上传成功, filekey: {filekey[:16]}...")
        except Exception as e:
            print(f"❌ 步骤3异常: {e}")
            return None
    else:
        # 秒传成功,需要获取已存在文件的filekey
        # 这里需要额外接口,部分OA支持直接用md5做submit
        # 简化处理:调用一个获取文件信息的接口(如果有)
        filekey = md5_hash  # 尝试用md5作为filekey(不保证成功)
        print(f"  ⚠️ 3. 秒传模式,使用md5作为filekey: {filekey[:16]}...")
    
    # ---- 步骤4:提交绑定附件(获取最终attid) ----
    params4 = {
        "method": "handleAttUpload",
        "gettype": "submit",
        "format": "json",
        "filekey": filekey,
        "filename": file_name,
        "fdKey": "attachment",
        "fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
        "fdAttType": "byte",
        "width": "null",
        "height": "null",
        "proportion": "true",
        "fdSign": fd_sign,
        "s_ajax": "true"
    }
    try:
        resp4 = session.get(base_att_url, params=params4)
        result4 = resp4.json()
        attid = result4.get("attid")
        if result4.get("status") != "1" or not attid:
            print(f"❌ 提交绑定失败: {resp4.text}")
            return None
        print(f"  ✅ 4. 提交绑定成功, attid: {attid}")
        return attid
    except Exception as e:
        print(f"❌ 步骤4异常: {e}")
        return None


def send_work_communication(
    session: requests.Session,
    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
) -> Optional[str]:
    """
    发送工作沟通(新建)
    
    :param session: 已登录的Session
    :param receiver_ids: 接收人ID,单个字符串或列表
    :param receiver_names: 接收人姓名,单个字符串或列表(顺序需与ID一致)
    :param subject: 标题
    :param content: 内容(支持HTML)
    :param attachment_ids: 附件ID,单个字符串或列表
    :param creator_id: 创建人ID,默认使用全局CREATOR_ID
    :return: 沟通ID(成功时返回数字字符串)
    """
    # 类型转换
    if isinstance(receiver_ids, list):
        receiver_ids_str = ",".join(receiver_ids)
    else:
        receiver_ids_str = receiver_ids
    
    if isinstance(receiver_names, list):
        receiver_names_str = ",".join(receiver_names)
    else:
        receiver_names_str = receiver_names
    
    if isinstance(attachment_ids, list):
        attachment_ids_str = ",".join(attachment_ids)
    else:
        attachment_ids_str = attachment_ids or ""
    
    if creator_id is None:
        creator_id = CREATOR_ID
    
    # 构造参数
    data = {
        "fdId": "",  # 新建传空
        "participantIds": receiver_ids_str,
        "participantNames": receiver_names_str,
        "docSubject": subject,
        "fdContent": content,
        "docCreatorId": creator_id,
        "attachmentForms.attachment.attachmentIds": attachment_ids_str,
        "attachmentForms.attachment.fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
        "attachmentForms.attachment.fdKey": "attachment",
        "fdNotifyType": "todo",
        "fdRemindersDay": "2",
        "fdIsOnlyView": "false",
        "fdIsReminders": "false",
        "fdPartnerOperating": "true",
        "_fdPartnerOperating": "true",
        "fdCategoryId": "",
    }
    
    # 防重复提交参数(取第一个附件ID做标记)
    if attachment_ids_str:
        first_att = attachment_ids_str.split(",")[0]
        data[f"__notify_type_{first_att}"] = "todo"
    
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Referer": f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do",
        "X-Requested-With": "XMLHttpRequest"
    }
    
    url = f"{OA_BASE_URL}/sys/ui/resources/user.jsp?s_ajax=true"
    
    try:
        resp = session.post(url, data=data, headers=headers)
        
        if resp.status_code != 200:
            print(f"❌ 发送沟通失败: HTTP {resp.status_code}")
            print(f"   返回: {resp.text[:200]}")
            return None
        
        # 成功时返回数字ID(如 "37036361")
        if resp.text.strip().isdigit():
            print(f"✅ 发送沟通成功! 沟通ID: {resp.text}")
            return resp.text.strip()
        else:
            print(f"❌ 发送沟通失败: {resp.text[:200]}")
            return None
            
    except Exception as e:
        print(f"❌ 发送沟通异常: {e}")
        return None


# ============================================================
#  主流程测试
# ============================================================

def main():
    """主流程:登录 → 搜索人员 → 上传附件 → 发送沟通"""
    
    print("=" * 50)
    print("开始执行OA工作沟通自动化发送")
    print("=" * 50)
    
    # 1. 获取登录Session
    session = get_session()
    
    # 2. 搜索接收人(示例:通过工号搜索)
    print("\n--- 搜索接收人 ---")
    person_id, person_name = search_person(session, "37036801")  # 替换为实际工号
    if not person_id:
        print("❌ 未找到接收人,退出")
        return
    
    # 3. 上传附件(示例:上传一个文件)
    print("\n--- 上传附件 ---")
    # attid = upload_attachment(session, "data.xlsx")  # 替换为实际文件路径
    
    # 4. 发送沟通
    print("\n--- 发送沟通 ---")
    result = send_work_communication(
        session=session,
        receiver_ids=person_id,
        receiver_names=person_name,
        subject="【RPA测试】工作沟通",
        content="<p>这是通过RPA接口自动发送的测试内容。</p><p>如有疑问请联系IT支持。</p>",
        attachment_ids=None,  # 或传入 ["attid1", "attid2"]
        creator_id=CREATOR_ID
    )
    
    if result:
        print(f"\n🎉 全部流程完成! 沟通ID: {result}")
    else:
        print("\n❌ 流程执行失败,请检查日志")


if __name__ == "__main__":
    main()

📋 测试清单

在正式运行前,请确认以下事项:

检查项 状态 说明
✅ Cookie/登录态 ☐ 设置 COOKIE_STRING 或实现登录逻辑
✅ 创建人ID ☐ 设置 CREATOR_ID,可通过搜索自己工号获取
✅ 接收人工号 ☐ 在 main() 中替换 "37036801"
✅ 测试文件路径 ☐ 在 main() 中替换 "data.xlsx"
✅ 附件上传测试 ☐ 先测试单个小文件(<1MB)

⚠️ 常见问题

问题 可能原因 解决方案
返回302跳转 Session过期或Cookie无效 重新获取Cookie,检查登录态
participantNames 乱码 编码问题 确保传入的姓名为UTF-8编码
附件上传失败 文件路径错误或权限问题 检查文件是否存在,使用绝对路径
秒传模式 filekey 无效 MD5替代filekey不被支持 需要额外抓包获取秒传后的filekey获取方式
返回 {"msg":"参数错误"} 缺少必填参数 检查 participantNames、docCreatorId 是否填写

🚀 后续优化建议

  1. 批量发送:封装 batch_send() 函数,传入多个接收人和对应附件
  2. 模板管理:将常用标题、内容模板化
  3. 日志记录:记录每次发送的请求和响应,便于追踪
  4. 异常重试:对网络波动导致的失败自动重试