feat(xq0036): 接入钉钉群机器人通知,webhook/加签界面配置

新增 report/notify.py 走 dingtalk_sdk 推送处理汇总与失败/待人工核对明细(分批、状态色、试算标题);plugin.json 增加 dingtalk_sdk 依赖与 push_enabled/robot_webhook/robot_secret 字段;UI 新增「钉钉通知」一行配置区;版本 0.1.8。
This commit is contained in:
2026-11-20 15:45:13 +08:00
parent a2f4e756ae
commit 8cab685d8f
9 changed files with 205 additions and 18 deletions
@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
"""钉钉群通知:把本次处理汇总与异常明细推送到界面配置的群机器人。
推送走 dingtalk_sdk 群机器人(Markdown 彩色标题 + 页脚、按条数分批、加签),
webhook / 加签密钥由插件界面填写;未开启或未填 webhook 时静默跳过。
推送失败只记日志,不影响处理结果与导出。
"""
from __future__ import annotations
from typing import Callable
from .. import config
#: 明细逐条列出的状态(正常提交的不列,避免消息过长)
DETAIL_STATUSES = (config.ST_FAIL, config.ST_PENDING)
#: 每个状态最多列出的明细条数
DETAIL_LIMIT = 50
def _who(record: dict) -> str:
"""姓名(工号) → 明细条目标题。"""
name = config.text(record.get("姓名")) or "未知"
code = config.text(record.get("工号"))
return f"{name}({code})" if code else name
def _detail(record: dict) -> str:
"""明细条目的引用行:异动类型 / 岗位 / 说明(只拼非空项)。"""
parts = []
change = config.text(record.get("异动类型名称")) or config.text(record.get("异动类型"))
if change:
parts.append(f"异动:{change}")
post = config.text(record.get("岗位")) or config.text(record.get("职衔"))
if post:
parts.append(f"岗位:{post}")
note = config.text(record.get("说明"))
if note:
parts.append(note)
return " | ".join(parts)
def build_blocks(records: list, counts: dict, path: str = "") -> list:
"""组装待推送的 block 列表(汇总 + 失败/待人工核对明细)。"""
summary = ["**处理结果**:" + (
",".join(f"{k} {v}" for k, v in counts.items()) or "无数据")]
if path:
summary.append(f"**结果文件**:{path}")
blocks = ["\n".join(summary)]
for status in DETAIL_STATUSES:
rows = [r for r in records if config.text(r.get("处理状态")) == status]
if not rows:
continue
blocks.append(f"**{status}({len(rows)} 条)**")
for record in rows[:DETAIL_LIMIT]:
line = f"🔹 {_who(record)}"
detail = _detail(record)
if detail:
line += f"\n> {detail}"
blocks.append(line)
if len(rows) > DETAIL_LIMIT:
blocks.append(f"… 另有 {len(rows) - DETAIL_LIMIT} 条,见结果文件")
return blocks
def notify(records: list, counts: dict, fields: dict, log: Callable, *,
dry_run: bool = False, path: str = "") -> dict:
"""推送本次处理汇总。返回 ``{"ok", "message"}``,永不抛异常。"""
fields = fields or {}
if not bool(fields.get("push_enabled")):
return {"ok": False, "message": "未开启钉钉通知"}
webhook = config.text(fields.get("robot_webhook"))
secret = config.text(fields.get("robot_secret"))
if not webhook:
log("[WARN] 已开启钉钉通知但未填写机器人 webhook,本次不推送", "WARNING")
return {"ok": False, "message": "未填写机器人 webhook"}
try:
from dingtalk_sdk import robot as dingtalk_robot
except Exception as exc: # noqa: BLE001 - 通知是附属动作
log(f"[WARN] 钉钉 SDK 不可用,跳过通知:{exc}", "WARNING")
return {"ok": False, "message": f"钉钉 SDK 不可用:{exc}"}
if counts.get(config.ST_FAIL):
status = "error"
elif counts.get(config.ST_PENDING):
status = "warning"
else:
status = "success"
title = config.PLUGIN_NAME + ("【试算】" if dry_run else "")
blocks = build_blocks(records, counts, path)
def sdk_log(msg: str) -> None:
log(msg, "WARNING" if str(msg).startswith("[WARN]") else "INFO")
result = dingtalk_robot.push(
[{"title": title, "blocks": blocks, "status": status}],
webhook=webhook, secret=secret, server_name=config.PLUGIN_NAME, log=sdk_log)
result = {"ok": bool(result.get("success")), "message": result.get("message", "")}
if result["ok"]:
log(f"[INFO] 钉钉通知:{result['message']}")
else:
log(f"[WARN] 钉钉通知未推送:{result['message']}", "WARNING")
return result