XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
181 lines
6.9 KiB
Python
181 lines
6.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0006 报告层:钉钉推送。
|
||
|
||
推送口径与影刀版一致(消息文本不改):
|
||
- 当事人:一人一条文本,按「姓名+工号」精确定位钉钉账号,走企业内部应用工作通知;
|
||
- 群汇总:条数汇总文本推送到群机器人,走 dingtalk_sdk 统一格式
|
||
(彩色标题 + 正文 + 页脚署名/时间,Markdown)。
|
||
所有发送失败只记日志与计数,不中断主流程。
|
||
"""
|
||
import time
|
||
|
||
import requests
|
||
from dingtalk_sdk.robot import Robot
|
||
|
||
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)}
|
||
|
||
|
||
def send_group_text(text, webhook="", secret="", title=""):
|
||
"""群机器人推送统一格式 Markdown(彩色标题 + 正文 + 页脚,走 dingtalk_sdk)。
|
||
|
||
正文口径与影刀版一致;消息体由 dingtalk_sdk 渲染,仅去掉与标题重复的首行标签。
|
||
返回 True/False。
|
||
"""
|
||
webhook = webhook or config.DEFAULT_WEBHOOK
|
||
secret = secret or config.DEFAULT_SECRET
|
||
if not webhook:
|
||
config.logger.warning("未配置群机器人 Webhook,跳过群汇总推送")
|
||
return False
|
||
title = title or config.DINGTALK_GROUP_TITLE
|
||
body = str(text or "").replace(f"【{title}】", "", 1).strip()
|
||
try:
|
||
Robot(webhook=webhook, secret=secret, log=config.logger.info).send(
|
||
title, body, status="info")
|
||
config.logger.info("群汇总推送成功(Markdown + 页脚)")
|
||
return True
|
||
except Exception as e: # noqa: BLE001
|
||
config.logger.error("群汇总推送失败:%s", e)
|
||
return False
|