Files
37duAutomation/plugins/XQ0001-0100/XQ0052 湖畔储值卡每日导出统计/logic/push.py
T
puddy 206f3ea226 feat(plugin): XQ0052 0.6.9 台账维护与钉钉推送拆成两步,台账支持跨月换表
- 执行方式新增「只推送台账」:不取数、不改表,定位当天台账后直接推钉钉;
  其余执行方式不再自动推送,维护表与推送可分成两个定时任务
- 钉钉推送改企业内部应用工作通知(actionCard + 下载台账按钮),台账先传文件服务器拿直链
- 台账定位支持跨月换表:营业日月份的表不在时按文件名年月取最新一份,同月多份仍报错不猜
- 新增 logic/push.py,界面/配置/README/_selftest 同步
2026-11-16 11:27:48 +08:00

301 lines
13 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 -*-
"""钉钉推送(企业内部应用工作通知,**不用 dws**):把最终台账推给指定接收人。
为什么不直发文件:台账约 30MB,钉钉 ``media/upload`` 的 file 类型上限 20MB,发不了附件。
所以走两步:
1. 台账 POST 到内网文件服务器(``/api/upload``,X-API-Token)拿开放下载直链;
2. 用企业内部应用「工作通知」(``topapi/message/corpconversation/asyncsend_v2``)
把汇总 + 下载链接推到接收人的钉钉工作通知会话。
接收人解析:
- 界面填「姓名/工号」,多个用「、」「,」「;」或换行分隔;
- 先按姓名搜索 userId(钉钉通讯录搜索会命中重名),再用工号(jobnumber)精确挑人;
- 只填姓名且搜到多个 → 报错并列出候选(姓名/工号/userId),要求补工号。
推送是附带动作:失败只记 WARN 并在汇总里说明,不影响已完成的导出/台账。
"""
from __future__ import annotations
import os
import re
import time
from urllib.parse import quote
import requests
try: # 插件内按包导入
from .. import config
except ImportError: # 自测脚本把 logic 当顶层包导入
import config # type: ignore[no-redef]
#: 项目级重试:最多 3 次(通知超时除外,见 _is_timeout)
MAX_ATTEMPTS = 3
RETRY_WAIT = 3
_ENTRY_SEP = re.compile(r"[,,、;;\n\r]+")
_CODE_OPEN = re.compile(r"[((//]")
_CODE_CLOSE = re.compile(r"[))]")
# 令牌缓存(v1 与 oapi 两套,都有 2 小时 TTL)
_TOKEN_V1 = {"token": "", "exp": 0.0}
_TOKEN_OAPI = {"token": "", "exp": 0.0}
def parse_recipients(text) -> list:
"""把界面上的接收人文本解析成 ``[(姓名, 工号), …]``。
支持 ``张三/37036361``、``张三(37036361)``、``张三(37036361)``、只写 ``张三``;
条目之间用中英文逗号、顿号、分号或换行分隔。空条目与无姓名的条目忽略。
"""
out = []
for raw in _ENTRY_SEP.split(str(text or "")):
item = raw.strip().strip("\"'“”")
if not item:
continue
name, code = item, ""
hit = _CODE_OPEN.search(item)
if hit:
name = item[:hit.start()].strip()
code = _CODE_CLOSE.sub("", item[hit.end():]).strip()
if name:
out.append((name, code))
return out
def _make_logger(log):
"""插件日志回调适配。"""
if log is None:
return lambda msg, level="INFO": None
return log
def _is_timeout(exc) -> bool:
text = str(exc or "").lower()
return "超时" in text or "timeout" in text or "timed out" in text
def _retry(fn, what, log, allow_retry=True):
"""项目级重试:最多 3 次;超时(状态未知)默认不重试。"""
last = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return fn()
except Exception as exc: # noqa: BLE001
last = exc
if _is_timeout(exc) and not allow_retry:
raise
log("[WARN] %s失败(第 %d/%d 次):%s" % (what, attempt, MAX_ATTEMPTS, exc))
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT)
raise last
# ==================== 钉钉令牌 ====================
def _token_v1() -> str:
"""新版企业内部应用 accessToken(v1.0 接口用)。"""
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("钉钉 accessToken(v1) 获取失败:%s" % data)
ttl = int(data.get("expireIn") or 7200)
_TOKEN_V1.update(token=token, exp=now + max(ttl - 120, 60))
return token
def _token_oapi() -> str:
"""旧版 oapi access_token(user/get、工作通知用)。"""
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("钉钉 access_token(oapi) 获取失败:%s" % data)
ttl = int(data.get("expires_in") or 7200)
_TOKEN_OAPI.update(token=token, exp=now + max(ttl - 120, 60))
return token
# ==================== 接收人 → userId ====================
def _search_by_name(name: str) -> list:
"""按姓名搜索 userId 列表(v1.0 通讯录搜索,会命中重名)。"""
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: str) -> dict:
"""取成员详情(工号 jobnumber 只有这个接口给)。"""
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("钉钉 user/get 失败:%s" % data.get("errmsg"))
return data
def resolve_user_id(name: str, code: str) -> str:
"""姓名 + 工号 → userId:先按姓名搜候选,再用工号精确挑;只给姓名时必须唯一。"""
ids = _search_by_name(name)
if not ids:
raise RuntimeError("钉钉通讯录里没搜到「%s」" % name)
cands = []
for uid in ids:
info = _user_detail(uid)
cands.append({"uid": uid, "name": str(info.get("name") or ""),
"jobnumber": str(info.get("jobnumber") or "").strip()})
def _hint() -> str:
return ";".join("%s(工号 %s / userId %s)"
% (c["name"] or name, c["jobnumber"] or "无", 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("「%s」的候选中没有工号 %s,请核对:%s" % (name, code, _hint()))
if len(cands) == 1:
return cands[0]["uid"]
raise RuntimeError("「%s」在钉钉里有多个人,请带工号后重试:%s" % (name, _hint()))
# ==================== 文件服务器上传 ====================
def _upload_to_fileserver(path: str) -> dict:
"""POST 台账到内网文件服务器,返回 {fid, filename, url}。"""
name = os.path.basename(path)
with open(path, "rb") as fp:
content = fp.read() # 30MB 一次读入,重试时可重复发送
resp = requests.post(
config.FILESERVER_UPLOAD_URL,
headers={"X-API-Token": config.FILESERVER_TOKEN},
files={"upload": (name, content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
timeout=config.PUSH_TIMEOUT)
data = resp.json() if resp.content else {}
if resp.status_code >= 400 or not data.get("ok") or not data.get("fid"):
raise RuntimeError("上传文件服务器失败(HTTP %s):%s"
% (resp.status_code, data.get("detail") or data))
fid = str(data["fid"])
filename = str(data.get("filename") or name)
return {"fid": fid, "filename": filename,
"url": "%s/files/%s?dl=%s" % (config.FILESERVER_BASE_URL, fid,
quote(filename))}
# ==================== 工作通知 ====================
def _send_work_notice(user_ids: list, title: str, text: str,
button_title: str, button_url: str) -> None:
"""发企业内部应用工作通知(actionCard:汇总正文 + 一个下载按钮)给多个 userId。"""
data = requests.post(
config.DINGTALK_WORK_SEND_URL,
params={"access_token": _token_oapi()},
json={"agent_id": config.DINGTALK_AGENT_ID,
"userid_list": ",".join(user_ids),
"msg": {"msgtype": "action_card",
"action_card": {"title": title,
"markdown": text,
"btn_orientation": "0",
"btn_json_list": [
{"title": button_title, "action_url": button_url}]}}},
timeout=30).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError("工作通知发送失败 errcode=%s errmsg=%s"
% (data.get("errcode"), data.get("errmsg")))
def _notice_text(summary: str) -> str:
"""工作通知正文:彩色标题 + 汇总(钉钉 markdown),下载入口走 actionCard 按钮。"""
body = str(summary or "").strip().replace("\n", " \n")
return ("**<font color='#00b300'>湖畔储值卡每日统计</font>**\n\n%s" % body)
# ==================== 对外入口 ====================
def push_ledger(file_path: str, users_text: str, message: str, log=None) -> dict:
"""把台账推到所有接收人的钉钉工作通知(上传文件服务器 → 发下载链接)。
返回 ``{"ok": bool, "sent": int, "failed": [...], "skipped": str, "message": str}``;
任何失败都不抛异常(导出/台账已落盘,推送只是附带动作)。
"""
log = _make_logger(log)
path = str(file_path or "").strip()
recipients = parse_recipients(users_text)
if not recipients:
return {"ok": False, "sent": 0, "failed": [], "skipped": "未配置接收人"}
if not path or not os.path.isfile(path):
return {"ok": False, "sent": 0, "failed": [],
"skipped": "台账文件不存在:%s" % (path or "(空)")}
# 1) 解析接收人(重名靠工号挑人)
user_ids, labels, failed = [], [], []
for name, code in recipients:
label = "%s/%s" % (name, code) if code else name
try:
uid = _retry(lambda: resolve_user_id(name, code), "解析接收人「%s」" % label,
log, allow_retry=False)
user_ids.append(uid)
labels.append(label)
log("[INFO] 接收人「%s」→ userId=%s" % (label, uid))
except Exception as exc: # noqa: BLE001 - 单人失败不影响其他人
log("[WARN] 接收人「%s」解析失败:%s" % (label, exc))
failed.append("%s:%s" % (label, exc))
if not user_ids:
return {"ok": False, "sent": 0, "failed": failed, "skipped": "",
"message": "0/%d 人匹配到钉钉账号" % len(recipients)}
# 2) 上传台账到内网文件服务器(每次运行传一份新文件,链接长期可用)
try:
uploaded = _retry(lambda: _upload_to_fileserver(path), "上传台账到文件服务器", log)
except Exception as exc: # noqa: BLE001
failed.extend("%s:%s" % (lb, exc) for lb in labels)
return {"ok": False, "sent": 0, "failed": failed, "skipped": "",
"message": "台账上传失败,未发送通知(%s)" % exc}
log("[INFO] 台账已上传文件服务器:%s" % uploaded["url"])
# 3) 发工作通知(actionCard:汇总 + 「下载台账」按钮)
size_mb = os.path.getsize(path) / 1024.0 / 1024.0
text = _notice_text(message)
button_title = "下载台账(%.1f MB)" % size_mb
try:
_retry(lambda: _send_work_notice(user_ids, "湖畔储值卡每日统计", text,
button_title, uploaded["url"]),
"发送工作通知", log, allow_retry=False)
except Exception as exc: # noqa: BLE001
failed.extend("%s:%s" % (lb, exc) for lb in labels)
return {"ok": False, "sent": 0, "failed": failed, "skipped": "",
"message": "工作通知发送失败(%s)" % exc}
sent = len(user_ids)
ok = not failed
summary = "已推送给 %d/%d 人" % (sent, len(recipients))
if failed:
summary += ",失败 %d 人" % len(failed)
return {"ok": ok, "sent": sent, "failed": failed, "skipped": "",
"message": summary, "url": uploaded["url"]}