feat(plugin): XQ0052 0.6.9 台账维护与钉钉推送拆成两步,台账支持跨月换表
- 执行方式新增「只推送台账」:不取数、不改表,定位当天台账后直接推钉钉; 其余执行方式不再自动推送,维护表与推送可分成两个定时任务 - 钉钉推送改企业内部应用工作通知(actionCard + 下载台账按钮),台账先传文件服务器拿直链 - 台账定位支持跨月换表:营业日月份的表不在时按文件名年月取最新一份,同月多份仍报错不猜 - 新增 logic/push.py,界面/配置/README/_selftest 同步
This commit is contained in:
@@ -7,13 +7,16 @@
|
||||
2. 填的是文件夹 → 只认 `.xlsx` / `.xlsm`,跳过临时文件(`~$`)、插件备份(`_备份_`)、
|
||||
同目录的导出表(`会员卡余额_*` / `会员卡明细_*`);
|
||||
3. 优先「名字同时带 会员卡/储值卡 和 统计」的;其中又优先名字带**目标年月**
|
||||
(`2026年11月` / `2026-11` / `202611`)的那一份;
|
||||
4. 只剩一份候选 → 直接用它;多份又分不清 → **报错,不猜**:
|
||||
(`2026年11月` / `2026-11` / `202611` / `2026.11`)的那一份;
|
||||
4. 目标月份的表不存在时(每月换新表、新表还没建或名字写法不同),按文件名里的年月
|
||||
取**最新月份**那一份(切月后 10 月旧表还在也不影响);
|
||||
5. 只剩一份候选 → 直接用它;同一个月多份、或全都没年月又分不清 → **报错,不猜**:
|
||||
猜错会按「自动切月」清掉另一份台账的数据,代价太大,让人先在目录里清理/改名。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
#: 台账扩展名(模板是 .xlsx;.xlsm 带宏也认)
|
||||
@@ -24,6 +27,8 @@ NAME_HINTS = ("会员卡", "储值卡")
|
||||
SKIP_HINTS = ("备份",)
|
||||
#: 与台账同目录的导出表前缀(`会员卡余额_20261108.xlsx` / `会员卡明细_20261108.xlsx`)
|
||||
EXPORT_PREFIXES = ("会员卡余额", "会员卡明细")
|
||||
#: 文件名里的年月:2026年11月 / 2026-11 / 2026.11 / 202611
|
||||
_MONTH_RE = re.compile(r"(20\d{2})\s*[年.\-_/]?\s*(\d{1,2})(?:\s*月)?")
|
||||
|
||||
|
||||
class LedgerPathError(RuntimeError):
|
||||
@@ -38,6 +43,24 @@ def _month_keys(day) -> tuple:
|
||||
"%d%02d" % (d.year, d.month))
|
||||
|
||||
|
||||
def _ym_of(name) -> tuple:
|
||||
"""从文件名里取 (年, 月);取不到返回 None(用于「按最新月份换表」)。"""
|
||||
m = _MONTH_RE.search(name)
|
||||
if not m:
|
||||
return None
|
||||
year, month = int(m.group(1)), int(m.group(2))
|
||||
return (year, month) if 1 <= month <= 12 else None
|
||||
|
||||
|
||||
def _ambiguous(pool: list, folder: str, hint: str) -> "LedgerPathError":
|
||||
"""分不清时统一的报错(宁可报错也不猜)。"""
|
||||
return LedgerPathError(
|
||||
"台账文件夹里有 %d 份 Excel,%s:%s\n%s\n"
|
||||
"请把当月那一份单独放一个文件夹(名字带「%s」最稳),"
|
||||
"或在面板里直接填完整文件路径。"
|
||||
% (len(pool), hint, folder, "\n".join(" · " + n for n in pool[:10]), hint))
|
||||
|
||||
|
||||
def _candidates(folder: str) -> list:
|
||||
"""目录里可能是台账的 Excel(已排除备份 / 临时 / 导出表)。"""
|
||||
out = []
|
||||
@@ -90,15 +113,25 @@ def resolve(raw, day=None, log=None) -> str:
|
||||
matched = [n for n in pool if any(k in n for k in keys)]
|
||||
if len(matched) == 1:
|
||||
chosen = matched[0]
|
||||
elif len(matched) > 1:
|
||||
raise _ambiguous(matched, text, "名字都带「%s」" % keys[0])
|
||||
elif len(pool) == 1:
|
||||
chosen = pool[0]
|
||||
else:
|
||||
raise LedgerPathError(
|
||||
"台账文件夹里有 %d 份 Excel,分不清该维护哪一份:%s\n%s\n"
|
||||
"请把当月那一份单独放一个文件夹(名字带「%s」最稳),"
|
||||
"或在面板里直接填完整文件路径。"
|
||||
% (len(pool), text, "\n".join(" · " + n for n in pool[:10]),
|
||||
keys[0]))
|
||||
# 目标月份的表不在(每月换表/新表还没建):按文件名年月取最新月份那份
|
||||
dated = [(n, _ym_of(n)) for n in pool]
|
||||
dated = [(n, ym) for n, ym in dated if ym]
|
||||
if dated:
|
||||
newest = max(ym for _, ym in dated)
|
||||
top = [n for n, ym in dated if ym == newest]
|
||||
if len(top) == 1:
|
||||
chosen = top[0]
|
||||
log("台账文件夹里没有 %s,按最新月份取:%s(%d年%d月)"
|
||||
% (keys[0], chosen, newest[0], newest[1]))
|
||||
else:
|
||||
raise _ambiguous(top, text, "都属于最新月份 %d年%d月" % newest)
|
||||
else:
|
||||
raise _ambiguous(pool, text, "都分不清月份")
|
||||
|
||||
log("台账自动匹配:%s(目录 %s,候选 %d 份)" % (chosen, text, len(pool)))
|
||||
return os.path.join(text, chosen)
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
# -*- 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"]}
|
||||
Reference in New Issue
Block a user