Files
37duAutomation/plugins/XQ0001-0100/XQ0006 EHR系统周考勤异常处理/report/dingtalk_push.py
T
puddy a2f4e756ae feat: 更新3个插件版本并优化XQ0006考勤异常处理逻辑
- XQ0036门店员工起调薪处理:版本升至0.1.6,优化纳税单位解析逻辑,优先使用接口返回值,新增金色印象、金色湖畔、后浪会馆的纳税单位兜底规则
- XQ0047微盟数据导出:版本升至1.0.5,新增等待生成上限配置项,优化轮询超时处理逻辑
- XQ0006 EHR系统周考勤异常处理:版本升至1.4.1,重构推送逻辑,支持组织架构范围选择,新增dws推送通道,优化自动确认范围为整月轻微异常,新增组织架构同步功能
2026-11-20 13:41:03 +08:00

201 lines
7.8 KiB
Python
Raw 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 -*-
"""XQ0006 报告层:钉钉推送。
推送口径与影刀版一致(消息文本不改):
- 当事人:一人一条文本,按「姓名+工号」精确定位钉钉账号;
- 群汇总:条数汇总文本推送到群。
优先走 dws(单聊 + 群,汇总附带 Excel 底稿);未装 dws 时当事人回退
企业内部应用工作通知,群汇总不发送(群机器人无法带附件)。
所有发送失败只记日志与计数,不中断主流程。
"""
import time
import requests
from dingtalk_sdk import Dws
from .. import config
MAX_ATTEMPTS = 3
RETRY_WAIT = 1.0
_TOKEN_V1 = {"token": "", "exp": 0.0}
_TOKEN_OAPI = {"token": "", "exp": 0.0}
# ==================== 重试 ====================
def _retry(fn, what):
last = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return fn()
except Exception as e: # noqa: BLE001
last = e
config.logger.warning("%s 第 %d/%d 次失败:%s", what, attempt, MAX_ATTEMPTS, e)
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT * attempt)
raise last
# ==================== 令牌 ====================
def _token_v1():
now = time.time()
if _TOKEN_V1["token"] and now < _TOKEN_V1["exp"]:
return _TOKEN_V1["token"]
data = requests.post(config.DINGTALK_TOKEN_V1_URL,
json={"appKey": config.DINGTALK_APP_KEY,
"appSecret": config.DINGTALK_APP_SECRET},
timeout=20).json()
token = str(data.get("accessToken") or "")
if not token:
raise RuntimeError(f"钉钉 accessToken(v1) 获取失败:{data}")
ttl = int(data.get("expireIn") or 7200)
_TOKEN_V1.update(token=token, exp=now + max(ttl - 120, 60))
return token
def _token_oapi():
now = time.time()
if _TOKEN_OAPI["token"] and now < _TOKEN_OAPI["exp"]:
return _TOKEN_OAPI["token"]
data = requests.get(config.DINGTALK_TOKEN_OAPI_URL,
params={"appkey": config.DINGTALK_APP_KEY,
"appsecret": config.DINGTALK_APP_SECRET},
timeout=20).json()
token = str(data.get("access_token") or "")
if not token:
raise RuntimeError(f"钉钉 access_token(oapi) 获取失败:{data}")
ttl = int(data.get("expires_in") or 7200)
_TOKEN_OAPI.update(token=token, exp=now + max(ttl - 120, 60))
return token
# ==================== 接收人解析 ====================
def _search_by_name(name):
data = requests.post(
config.DINGTALK_USER_SEARCH_URL,
json={"queryWord": name, "offset": 0, "size": 20, "maxResults": 20},
headers={"x-acs-dingtalk-access-token": _token_v1(), "Content-Type": "application/json"},
timeout=20).json()
ids = []
for item in data.get("list") or []:
uid = item if isinstance(item, str) else (item.get("userid") or item.get("userId") or "")
if uid:
ids.append(str(uid))
return ids
def _user_detail(user_id):
data = requests.get(config.DINGTALK_USER_GET_URL,
params={"access_token": _token_oapi(), "userid": user_id},
timeout=20).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError(f"钉钉 user/get 失败:{data.get('errmsg')}")
return data
def resolve_user_id(name, code):
"""按姓名搜索,再用工号(jobnumber)精确挑人;重名且无工号时抛错。"""
ids = _search_by_name(name)
if not ids:
raise RuntimeError(f"钉钉通讯录里没搜到「{name}」")
cands = []
for uid in ids:
detail = _user_detail(uid)
cands.append({
"uid": uid,
"name": str(detail.get("name") or ""),
"jobnumber": str(detail.get("jobnumber") or "").strip(),
})
hint = ";".join(f"{c['name'] or name}(工号 {c['jobnumber'] or '无'} / userId {c['uid']})"
for c in cands)
if code:
for c in cands:
if c["jobnumber"] == code or c["uid"] == code:
return c["uid"]
raise RuntimeError(f"「{name}」的候选中没有工号 {code},请核对:{hint}")
if len(cands) == 1:
return cands[0]["uid"]
raise RuntimeError(f"「{name}」在钉钉里有多个人,请带工号重试:{hint}")
# ==================== 发送 ====================
def _send_work_notice(user_id, content):
data = requests.post(
config.DINGTALK_WORK_SEND_URL,
params={"access_token": _token_oapi()},
json={"agent_id": config.DINGTALK_AGENT_ID,
"userid_list": user_id,
"msg": {"msgtype": "text", "text": {"content": content}}},
timeout=30).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError(f"工作通知失败 errcode={data.get('errcode')} errmsg={data.get('errmsg')}")
def push_person_messages(messages, on_progress=None):
"""逐人推送工作通知。
Args:
messages: [(姓名, 工号, 文本)],一人一条(文本与影刀版一致)
on_progress: 可选回调 (done, total)
Returns:
dict: sent 成功人数 / failed 失败明细 / no_uid 未匹配到账号数
"""
sent, failed = 0, []
total = len(messages)
for idx, (name, code, content) in enumerate(messages, 1):
label = f"{name}/{code}" if code else name
try:
uid = _retry(lambda: resolve_user_id(name, code), f"解析接收人「{label}」")
_retry(lambda: _send_work_notice(uid, content), f"发送工作通知「{label}」")
sent += 1
config.logger.info("当事人推送成功:%s(userId=%s)", label, uid)
except Exception as e: # noqa: BLE001 - 单人失败不影响其他人
failed.append(f"{label}:{str(e)[:200]}")
config.logger.error("当事人推送失败:%s:%s", label, e)
if on_progress:
on_progress(idx, total)
return {"sent": sent, "failed": failed, "no_uid": len(failed)}
# ==================== dws 推送(首选通道) ====================
def push_by_dws(messages, group_text, group_name, file_path="", record_dir="",
at_all=False, dws_path="", on_progress=None):
"""用 dws 命令行推送:当事人单聊 + 汇总群(可带 Excel 底稿)。
messages: [(姓名, 工号, 正文)];返回 {sent, failed, group_sent, note}。
"""
payload = [("text", name, code, text, "") for name, code, text in messages]
if group_text:
payload.append({
"group": group_name,
"content": group_text,
"file_path": file_path,
"at_all": bool(at_all),
})
try:
client = Dws(bin=dws_path, record_dir=record_dir, log=config.logger.info)
result = client.push(payload)
except Exception as e: # noqa: BLE001
config.logger.error("dws 推送失败:%s", e)
return {"sent": 0, "failed": [f"dws 推送失败:{e}"], "group_sent": False,
"note": f"dws 推送失败:{e}"}
results = result.get("results") or []
sent, failed = 0, []
for idx, (name, code, _text) in enumerate(messages):
item = results[idx] if idx < len(results) else {}
if item.get("success"):
sent += 1
else:
failed.append(f"{name}({code}):{item.get('message') or '失败'}")
if on_progress:
on_progress(idx + 1, len(messages))
group_sent = False
if group_text and len(results) > len(messages):
group_sent = bool(results[len(messages)].get("success"))
note = str(result.get("message") or "")
config.logger.info("dws 推送完成:单聊成功 %d/%d,群汇总 %s;%s",
sent, len(messages), "成功" if group_sent else "失败", note)
return {"sent": sent, "failed": failed, "group_sent": group_sent, "note": note}