Files
puddy 53913f0c7d refactor(workflows): 统一替换 yingdao 目录引用为 workflows
1.  将所有文档、代码中对 `yingdao/` 目录的引用替换为 `workflows/`,统一影刀版代码的命名空间
2.  调整 workflows/share 模块内的路径引用与文档注释,确保一致性
3.  同步更新测试代码与配置文件中的旧目录引用
2026-09-08 16:16:35 +08:00

654 lines
28 KiB
Python
Raw Permalink 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 -*-
"""
@FileName: work_communication.py
@Author: 小布丁
@CreateTime: 2026-08-25
@Description: OA 工作沟通推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
作为「OA工作沟通推送」影刀自定义指令的模块源码,供所有需要 OA 工作沟通推送的
业务脚本/流程复用(告知书下发、参保通知等),避免各自内联搜索/上传/提交逻辑。
合并自 app 公共模块 app/service/hrbp/oa/common/
(work_communication.py + oa_api/work_communication.py + config.py),
业务逻辑与接口调用完全一致。具体业务逻辑见 docs/工作沟通推送/需求文档.md、开发文档.md。
单文件自包含:不 import 任何共享指令模块,只读共享 cookies 文件、只写影刀全局变量。
@Version: 1.0.0
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
pip install DrissionPage requests
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
用法(作为影刀指令/业务脚本被调用):
from workflows.share.work_communication import send_work_communication
doc_id = send_work_communication(
receiver_keywords=["37001166", "37036361"], # 工号或姓名,列表或单个字符串
subject="【通知】...",
content="<p>正文支持 HTML</p>",
attachment_paths=[r"D:\\资料\\附件.xlsx"], # 可选,多个
creator_id="1342173e36cf416088266b17d7d084a4", # 当前操作人 ID;不传则尝试从新建页自动提取
category="工作安排", # 可选:工作交流/信息传递/工作安排/项目沟通/温馨提示/其他
)
main() 入口返回 {"success", "message", "doc_id"},并写入影刀全局变量 push_result。
"""
# ==================== 标准库导入 ====================
import base64
import json
import mimetypes
import os
import re
import time
import xml.etree.ElementTree as ET
from typing import List, Optional, Union
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
try:
from DrissionPage import SessionPage
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install DrissionPage requests\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== 路径 & 常量配置 ====================
# 数据目录固定放在 AppData\Local\37duAutomation,登录态由「37duOA登录」指令写入
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
BASE_URL = "https://oa.37du.co"
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
# 附件上传接口:getuserkey / submit 两步共用
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
# 附件二进制上传接口
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
FD_CATEGORY_MAP = {
"工作交流": FD_CATEGORY_COMMUNICATION,
"信息传递": FD_CATEGORY_INFO,
"工作安排": FD_CATEGORY_WORK_ARRANGE,
"项目沟通": FD_CATEGORY_PROJECT,
"温馨提示": FD_CATEGORY_REMINDER,
"其他": FD_CATEGORY_OTHER,
}
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
# 附件二进制上传时的请求头(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",
}
# ==================== 日志(影刀环境用 print 替代 logging) ====================
class _PrintLogger:
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
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()
def _set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
# ==================== 登录态(共享 cookies 文件) ====================
def _load_shared_oa_cookies():
"""读取共享 OA 登录 cookies(由「37duOA登录」指令写入)。"""
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
return json.load(f) or None
def _ensure_oa_cookies():
"""确保存在有效的 OA 登录态文件;缺失/失效时友好提示先运行「37duOA登录」指令。"""
if _load_shared_oa_cookies():
return True
if not os.path.exists(COOKIE_FILE):
raise SystemExit(
"未找到 OA 登录态文件(oa_cookies.json)。\n"
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
"或本地运行: python workflows/share/oa_login.py\n"
"登录完成后再运行本流程。")
raise SystemExit(
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
"请先重新运行「37duOA登录」指令完成登录,"
"或本地运行: python workflows/share/oa_login.py\n"
"重新登录后再运行本流程。")
def is_session_valid(session):
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
try:
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
resp = session.response
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:
logger.info("会话已失效,需重新登录: %s", e)
return False
def build_session():
"""用共享 oa_cookies.json 构建 SessionPage(纯接口,不开浏览器),并校验会话有效。"""
_ensure_oa_cookies()
session = SessionPage()
session.set.timeout(10)
cookies = _load_shared_oa_cookies()
if cookies:
session.set.cookies(cookies)
if is_session_valid(session):
return session
raise SystemExit(
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
"请先重新运行「37duOA登录」指令完成登录,"
"或本地运行: python workflows/share/oa_login.py\n"
"重新登录后再运行本流程。")
# ==================== 通用响应校验 ====================
class OALoginExpiredError(Exception):
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
def _check_response(resp, label):
"""校验响应:存在性 / 状态码 / 登录态。供返回 XML 或纯文本等非 JSON 的接口使用。"""
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 oa_request_json(session, method, url, params, label, timeout=20, headers=None):
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。"""
if method.upper() == "GET":
session.get(url, params=params, timeout=timeout, headers=headers)
else:
session.post(url, data=params, timeout=timeout, headers=headers)
resp = _check_response(session.response, 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",
}
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, file_path):
"""
上传单个附件,返回最终附件 ID(attid)。
普通上传流程(不实现 MD5 秒传):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)),
)
# 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("=", "")
# ---- 步骤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):
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
return FD_CONTENT_PREFIX + "{" + base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
def _get_add_page_fd_info(session):
"""打开新建工作沟通页(method=add),解析出草稿 fdId、通知方式随机字段名、当前用户 ID。
Returns:
(fd_id, notify_field, creator_id):fdId 隐藏域值;`__notify_type_<随机id>` 字段名;
页面里 docCreatorId 隐藏域值(当前登录用户 ID,可能为空)
"""
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 ""
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
creator_id = m3.group(1) if m3 else ""
if not fd_id:
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
logger.info("获取新建草稿 fdId: %s, 通知方式字段: %s, 页面当前用户ID: %s", fd_id, notify_field, 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=FD_CATEGORY_DEFAULT,
):
"""
提交工作沟通(新建),成功返回沟通文档 ID(fdId)。
真实提交端点:kmCollaborateMain.do?method=save&s_seq=1(aa.md 中 user.jsp 为错误端点)。
流程:打开新建页取草稿 fdId 与通知方式随机字段 → 以真实表单结构 POST 保存。
多值分隔符:多人参与人 / 多附件 ID 以「;」分号拼接(真实抓包确认,非逗号)。
Args:
session: 已登录的 SessionPage 对象
receiver_ids: 接收人 ID,单个字符串或列表(多个以「;」分号分隔)
receiver_names: 接收人姓名,单个字符串或列表(顺序与 ID 一致)
subject: 标题
content: 内容(支持 HTML 富文本)
attachment_ids: 附件 ID(attid),单个字符串或列表(多个以「;」分号分隔),可空
creator_id: 创建人(当前操作人)ID,必填;为空时尝试从新建页自动提取
category_id: 沟通类型,可传中文名(如「工作安排」)或类型 ID,默认「工作安排」
Returns:
沟通文档 ID(fdId,字符串)
Raises:
ValueError: 缺少必填参数
RuntimeError: 提交失败
OALoginExpiredError: OA 登录态已失效
"""
# 沟通类型:支持中文名 -> 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
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、通知方式随机字段、当前用户 ID(creator_id 兜底来源)
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) 必填,且无法从新建页自动提取,请显式传入当前操作人的用户 ID")
# 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]}")
# ==================== 一键推送入口 ====================
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(fdId)。
Args:
receiver_keywords: 接收人工号或姓名,单个字符串或列表
subject: 沟通标题
content: 沟通内容(支持 HTML 富文本)
attachment_paths: 附件文件路径,单个字符串或列表,可空
creator_id: 创建人(当前操作人)用户 ID;为空时尝试从新建页自动提取
category: 沟通类型,可传中文名(如「工作安排」「信息传递」)或类型 ID,默认「工作安排」
Returns:
沟通文档 ID(fdId,字符串)
Raises:
ValueError: 缺少必填参数
RuntimeError: 接收人解析失败 / 附件上传失败 / 提交失败(含具体原因)
OALoginExpiredError: OA 登录态已失效
"""
if not subject or not subject.strip():
raise ValueError("subject(标题) 不能为空")
if not content or not content.strip():
raise ValueError("content(内容) 不能为空")
session = build_session()
# ---- 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)
logger.info("接收人[%s] -> %s (ID: %s)", kw, pname, 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)
logger.info("附件[%s] -> attid: %s", path, 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_work_communication_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 SystemExit as e:
return {"success": False, "message": str(e), "doc_id": ""}
except Exception as e:
logger.error("工作沟通推送失败: %s", e)
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
# ==================== 主入口(影刀指令) ====================
def main(messages=None, receiver_keywords=None, subject=None, content=None,
attachment_paths="", creator_id="", category="工作安排"):
"""
影刀指令入口:发送工作沟通推送。
支持两种调用方式:
1) main(messages):messages 为列表,每条含字段
{receivers, subject, content, attachment_paths, creator_id, category},
对应 notice 模块 oa_work_communications 全局变量结构,逐条推送
2) main(receiver_keywords=..., subject=..., content=..., ...):单条推送(向后兼容)
Returns:
{"success": bool, "message": str, "doc_id": str};并写入影刀全局变量 push_result。
"""
if isinstance(messages, list) and messages:
results = []
for i, msg in enumerate(messages, 1):
r = _send_work_communication_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)
logger.info("[%d/%d] %s", i, len(messages), r.get("message"))
ok = sum(1 for r in results if r.get("success"))
result = {
"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")),
}
else:
result = _send_work_communication_wrapped(
receiver_keywords=receiver_keywords or [],
subject=subject or "",
content=content or "",
attachment_paths=attachment_paths,
creator_id=creator_id,
category=category,
)
_set_glv("push_result", result)
logger.info("推送结果: %s", result)
return result
if __name__ == "__main__":
# 本地独立运行调试示例:messages 结构同 notice 模块的 oa_work_communications 全局变量,
# 逐条调用 main 推送(影刀中同样按该结构循环推送)。
messages = [
{
"receivers": ["37036361", "37001166"], # 测试接收人(多人)
"subject": "2026年8月员工参保结果告知书",
"content": "<p>【测试】重庆区域门店8月新参保已完成,请各门店传达告知。</p>",
"attachment_paths": [],
"category": "工作安排",
},
{
"receivers": ["37036361", "37001166"],
"subject": "2026年8月员工参保单位变更确认",
"content": "<p>【测试】本月人力资源部已输出“工作与参保单位不一致”人员,请完成转移确认。</p>",
"attachment_paths": [],
"category": "工作安排",
},
]
main(messages)
result = main(messages)
print("RESULT:", result)