feat(plugin): XQ0052 0.6.9 台账维护与钉钉推送拆成两步,台账支持跨月换表
- 执行方式新增「只推送台账」:不取数、不改表,定位当天台账后直接推钉钉; 其余执行方式不再自动推送,维护表与推送可分成两个定时任务 - 钉钉推送改企业内部应用工作通知(actionCard + 下载台账按钮),台账先传文件服务器拿直链 - 台账定位支持跨月换表:营业日月份的表不在时按文件名年月取最新一份,同月多份仍报错不猜 - 新增 logic/push.py,界面/配置/README/_selftest 同步
This commit is contained in:
@@ -1,6 +1,14 @@
|
||||
# XQ0052 湖畔储值卡每日导出统计
|
||||
|
||||
> 状态:v0.4.3(带界面),2026-11-11。
|
||||
> 状态:v0.6.1(带界面),2026-11-13。
|
||||
> v0.6.1:台账定位支持**跨月换表**——营业日月份的表不在时,按文件名里的年月取**最新月份**那份
|
||||
> (切月后旧表还在也不影响);同月多份仍报错不猜。维护表与推送两步共用同一套定位。
|
||||
> v0.6.0:**维护表与推送拆成两步**——执行方式新增「只推送台账」:不取数、不改表,定位当天那份台账
|
||||
> 直接推钉钉;其余执行方式不再自动推送。这样可以「先只维护台账、再只推送台账」分开定时。
|
||||
> v0.5.0:新增**钉钉推送**——把最终台账推给界面配置的接收人(`姓名/工号`,可填多个):
|
||||
> 先上传到内网文件服务器拿开放下载直链,再用**企业内部应用工作通知**(不走 dws)发
|
||||
> 带「下载台账」按钮的 actionCard;重名靠工号精确挑人。任何推送失败只记 WARN(v0.6.0 起
|
||||
> 「只推送台账」失败会直接报错),不影响导出与台账(见 §2.2)。
|
||||
> v0.4.3:导出表落盘遇到「文件被占用」(`PermissionError`,财务开着 `会员卡余额_xxx.xlsx`)
|
||||
> 不再甩一串 openpyxl 的 `Exception ignored`:等 2/4 秒重试 3 次,仍失败就给中文提示
|
||||
> (关掉 WPS/Excel 里的这份表、或结束残留 `et.exe`/`wps.exe` 后重跑)。
|
||||
@@ -65,9 +73,11 @@
|
||||
2. 填的是文件夹(选文件夹 / 旧配置)→ 只认 `.xlsx` / `.xlsm`,排除 `~$` 临时文件、`_备份_` 备份、
|
||||
`会员卡余额_*` / `会员卡明细_*` 导出表;
|
||||
3. 优先「名字带 会员卡/储值卡 + 统计」的,其中再优先名字带**营业日年月**(`2026年11月` /
|
||||
`2026-11` / `202611`)的那份;
|
||||
4. 只有一份候选 → 直接用它;多份又分不清 → **报错停止**(不猜,猜错会按自动切月清掉另一份台账),
|
||||
提示把当月那份单独放一个文件夹、或在面板里直接填完整路径。
|
||||
`2026-11` / `202611` / `2026.11`)的那份;
|
||||
4. 营业日月份的表不在(每月换新表,新表还没建/名字写法不同)→ 按文件名里的年月取**最新月份**
|
||||
那份(切月后 10 月旧表还在也不影响),日志会写明「按最新月份取」;
|
||||
5. 只有一份候选 → 直接用它;同一个月多份、或全都没年月又分不清 → **报错停止**
|
||||
(不猜,猜错会按自动切月清掉另一份台账),提示把当月那份单独放一个文件夹、或在面板里直接填完整路径。
|
||||
|
||||
> 想每月改完文件名不用再动配置,就填**文件夹**(默认就是文件夹,按年月自动跟)。
|
||||
|
||||
@@ -77,22 +87,46 @@
|
||||
`wcf.query` / `wcf.query_proc` 相邻两次请求至少间隔 `HotelConfig.min_interval`(默认 1.2s),
|
||||
本插件不需要实现(`settle_window` / `export_member` / `collect.*` 自动生效),补 7 天多等十几秒。
|
||||
|
||||
### 执行方式:导出与表维护分两步(v0.4.0)
|
||||
### 执行方式:导出、表维护、推送可分开(v0.6.0)
|
||||
|
||||
面板「执行方式」三选一(`logic/__init__.py` 的 `normalize_mode`,老配置里的
|
||||
面板「执行方式」四选一(`config.normalize_mode`,老配置里的
|
||||
`导表+维护台账` / `只导表` 会自动映射):
|
||||
|
||||
| 方式 | 做什么 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `导出+维护台账`(默认) | 取数 → 落两份 Excel + 导出快照 → 用 WPS 维护台账 | 日常一键跑完 |
|
||||
| `导出+维护台账`(默认) | 取数 → 落两份 Excel + 导出快照 → 用 WPS 维护台账(**不推送**) | 日常一键跑完导出与台账 |
|
||||
| `只导出` | 只取数落表 + 存快照,**不碰台账**(不需要装 WPS) | 台账机器没装 WPS、或先出表给财务看 |
|
||||
| `只维护台账` | **复用上一次导出**(快照),只跑 WPS 台账维护 | 表维护失败后重试;不用再取 20 万行余额 |
|
||||
| `只维护台账` | **复用上一次导出**(快照),只跑 WPS 台账维护(**不推送**) | 表维护失败后重试;推送两步里的第一步 |
|
||||
| `只推送台账` | 不取数、不动表,定位当天那份台账 → 上传文件服务器 → 钉钉工作通知 | 推送单独定时(第二步) |
|
||||
|
||||
推荐两个定时任务:先「只维护台账」,再「只推送台账」,互不影响;推送失败也不会动表。
|
||||
|
||||
导出快照:`%LOCALAPPDATA%\37duAutomation\plugin_data\xq0052\snapshot_<营业日>.pkl.gz`
|
||||
(pickle+gzip,一个营业日一份,重跑导出会覆盖;里面是两份结果表,删掉不影响任何业务数据)。
|
||||
台账阶段命中快照就用快照的余额/明细,只有要补历史天数(快照里没有那天)才回查 WCF。
|
||||
台账失败时日志会提示「改成『只维护台账』重试」,不用重新导出。
|
||||
|
||||
### 钉钉推送:把台账发给指定接收人(v0.5.0,v0.6.0 起独立成一步)
|
||||
|
||||
面板「钉钉推送 → 推送接收人」填 `姓名/工号`,多个用「、」「,」「;」或换行分隔,
|
||||
**重名必须带工号**(只写姓名又搜到多人时会报错并列出候选)。**留空 = 不推送**。
|
||||
|
||||
- 推送时机:只有执行方式=**`只推送台账`** 才推;它不取数、不改表,按营业日定位
|
||||
「台账文件」对应那份 Excel 后直接推送。其它执行方式(含 `导出+维护台账`)都不推送,
|
||||
这样「维护表」和「推送文件」可以分成两个定时任务;
|
||||
- 只推送模式失败会**直接报错**(`RuntimeError`,定时任务能看出来),不会静默成功;
|
||||
- 通道:**企业内部应用工作通知**(`topapi/message/corpconversation/asyncsend_v2`,actionCard),
|
||||
**不用 dws、不用钉钉 SDK**,只依赖执行机环境自带的 `requests`;消息正文是统计汇总,
|
||||
下载入口是卡片上的**「下载台账」按钮**(不是裸链接);
|
||||
- 文件怎么给:台账约 30MB,超过钉钉 `media/upload` 文件消息 20MB 上限,所以不直发附件——
|
||||
先 `POST http://172.30.30.243:8802/api/upload`(`X-API-Token`,内置在 `config`)上传,
|
||||
再把文件服务器的开放下载直链(`/files/<fid>?dl=文件名`)做成按钮,内网可直接下载;
|
||||
- 接收人定位:按姓名调通讯录搜索拿候选 userId,再用工号(`jobnumber`)精确挑人,
|
||||
工号为空且唯一时直接用;工号对不上会列出「姓名(工号 / userId)」候选;
|
||||
- 失败不影响主流程:解析/上传/发通知任意一步失败只记 WARN,导出与台账照常完成,
|
||||
汇总里会写「钉钉推送:跳过/失败」;通知超时(状态未知)不重试,避免重复发消息;
|
||||
- 链接是内网地址:接收人在公司内网可下载,手机 4G 直接点不开。
|
||||
|
||||
### 只用 WPS:从不调用 Microsoft Excel(v0.4.0)
|
||||
|
||||
以前用 `DispatchEx("Excel.Application")`——装了 Office 的机器上这会拉起 **Microsoft Excel**,
|
||||
@@ -183,9 +217,10 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
├─ config/ # 默认导出目录 / 默认台账文件夹 / 执行方式 / 开关常量 / 超时
|
||||
├─ logic/
|
||||
│ ├─ period.py # 营业日解析(空=今天)
|
||||
│ ├─ ledger_path.py # 台账文件/文件夹 → 实际 Excel(按营业日年月自动匹配,分不清就报错)
|
||||
│ ├─ ledger_path.py # 台账文件/文件夹 → 实际 Excel(按营业日年月匹配,缺表时取最新月份,分不清就报错)
|
||||
│ ├─ snapshot.py # 导出快照(导出与表维护两步之间的交接文件)
|
||||
│ ├─ provider.py # SDK 取数包装:SdkProvider / SnapshotProvider(优先复用快照)
|
||||
│ ├─ push.py # 台账推送(姓名+工号解析 userId → 上传文件服务器 → 工作通知发链接)
|
||||
│ └─ ledger.py # WPS 表格 COM 台账维护(四张 sheet + 核对;不乱调 Office)
|
||||
├─ ui-src/ # 前端源码(Vue3 + Element Plus + Vite,打包时排除)
|
||||
│ ├─ index.html / package.json / vite.config.js
|
||||
@@ -195,12 +230,12 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
└─ _pack.py # 打包到 dist-plugin/xq0052_v<版本>.zip
|
||||
```
|
||||
|
||||
界面按《插件 UI 开发规范 v3.1》五段式:**工具条(方案)→ 01 统计范围 → 02 导出与台账 → 说明 → 操作区**,
|
||||
界面按《插件 UI 开发规范 v3.1》五段式:**工具条(方案)→ 01 统计范围 → 02 导出与台账 → 03 钉钉推送 → 说明 → 操作区**,
|
||||
参数即 `plugin.json.fields` 的可视化编辑器(二者必须一致);`wcf_url` 属技术排障项,不出现在界面上。
|
||||
|
||||
两段都用规范的 `.rows > .row` 行卡片(左标题+说明 / 右控件),02 四行分别是:
|
||||
导出文件保存到、执行方式(导出+维护台账 / 只导出 / 只维护台账)、台账文件、
|
||||
台账选项(备份 / 重算 / 切月 一行排开,各带小标签)。
|
||||
各段都用规范的 `.rows > .row` 行卡片(左标题+说明 / 右控件),02 四行分别是:
|
||||
导出文件保存到、执行方式(导出+维护台账 / 只导出 / 只维护台账 / 只推送台账)、台账文件、
|
||||
台账选项(备份 / 重算 / 切月 一行排开,各带小标签,`只推送台账` 时隐藏);03 只有一行:推送接收人。
|
||||
|
||||
## 4. 表单字段(plugin.json 为权威)
|
||||
|
||||
@@ -209,10 +244,11 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
| `day` | 营业日,`YYYY-MM-DD`;**留空 = 今天** |
|
||||
| `save_dir` | 两份导出表保存到,默认 `D:\资料\财务\湖畔储值卡统计` |
|
||||
| `ledger_file` | 台账文件完整路径,或它所在的**文件夹**(默认 `D:\资料\财务\湖畔储值卡每日导出统计`,按年月自动匹配当月那份);留空=不维护(见 §2.1) |
|
||||
| `ledger_mode` | `导出+维护台账` / `只导出` / `只维护台账`(旧值 `导表+维护台账` / `只导表` 自动映射,见 §2「执行方式」) |
|
||||
| `ledger_mode` | `导出+维护台账` / `只导出` / `只维护台账` / `只推送台账`(旧值 `导表+维护台账` / `只导表` 自动映射,见 §2「执行方式」) |
|
||||
| `ledger_backup` | `先备份`(同目录生成 `<台账名>_备份_YYYYMMDD_HHMMSS.xlsx`)/ `不备份` |
|
||||
| `ledger_recalc` | `重算(推荐)` / `不重算(快)`;模板公式是整列引用,20 万行全量重算在 WPS 上可能要几分钟,不重算则由 Excel 打开时自行计算(核对项会读到旧值) |
|
||||
| `ledger_month_reset` | `自动切月(推荐)` / `不切月(只补数)`;月份不符时清上月明细/新办卡、汇总日期行滚到当月、期初取上月末 |
|
||||
| `push_users` | 钉钉推送接收人:`姓名/工号`,多个用「、」「,」「;」或换行分隔;留空=不推送;仅 `只推送台账` 会推送(见 §2.2) |
|
||||
| `wcf_url` | 留空=SDK 默认地址,技术排障用 |
|
||||
|
||||
## 5. 本地验收
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
取数/渲染全部由 SDK 提供(宿主按 `plugin.json.requires.sdks` 挂载 `hotel_report`),插件只负责:
|
||||
读表单 → 解析营业日 → 让 SDK 现算「前一日最晚交班 ~ 当日最晚交班」→ 导出余额 + 明细 → 维护台账。
|
||||
|
||||
执行方式分三步可选(`config.LEDGER_MODE_*`):
|
||||
· 导出+维护台账:一次跑完;
|
||||
执行方式分四步可选(`config.LEDGER_MODE_*`):
|
||||
· 导出+维护台账:一次跑完导出与台账(不推送);
|
||||
· 只导出:只取数落表 + 存导出快照,不碰台账(也不需要 WPS);
|
||||
· 只维护台账:复用上次导出的快照,只跑台账 —— 台账那步失败时重试用它,不用重新取数导出。
|
||||
· 只维护台账:复用上次导出的快照,只跑台账 —— 台账那步失败时重试用它,不用重新取数导出;
|
||||
· 只推送台账:不取数、不动表,定位当天那份台账直接推钉钉(推送单独定时用)。
|
||||
台账维护走 **WPS 表格 COM(Ket.Application)**,装了 Office 也不会去调用 Microsoft Excel。
|
||||
|
||||
业务背景:储值卡(会员卡)按**营业日**结算,营业日由交班切开,不是自然日零点的。
|
||||
@@ -26,6 +27,7 @@ from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .logic import ledger_path, period
|
||||
from .logic import push as push_mod
|
||||
from .logic import snapshot as snapshot_store
|
||||
|
||||
|
||||
@@ -72,9 +74,10 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0052"
|
||||
name = "湖畔储值卡每日导出统计"
|
||||
version = "0.4.3"
|
||||
version = "0.6.9"
|
||||
description = ("按营业日导出会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:"
|
||||
"交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对")
|
||||
"交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对;"
|
||||
"台账维护与钉钉推送拆成两个执行方式,可分开定时")
|
||||
platform = ""
|
||||
uses_month = False
|
||||
capabilities = ["xq0052"]
|
||||
@@ -99,9 +102,10 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
"ledger_mode": {
|
||||
"type": "string", "title": "执行方式", "default": config.LEDGER_MODE_FULL,
|
||||
"enum": [config.LEDGER_MODE_FULL, config.LEDGER_MODE_EXPORT_ONLY,
|
||||
config.LEDGER_MODE_LEDGER_ONLY],
|
||||
"description": "只导出=取数并出两份 Excel(留快照);只维护台账=复用上次导出,"
|
||||
"不重新取数(台账失败时用它重试)",
|
||||
config.LEDGER_MODE_LEDGER_ONLY, config.LEDGER_MODE_PUSH_ONLY],
|
||||
"description": "导出+维护台账=取数、出表并维护台账(不推送);只导出=只出两份 Excel;"
|
||||
"只维护台账=复用上次导出只维护台账;只推送台账=不取数不动表,"
|
||||
"直接把当天那份台账推到钉钉(推送单独定时用)",
|
||||
},
|
||||
"ledger_backup": {
|
||||
"type": "string", "title": "台账备份", "default": config.BACKUP_ON,
|
||||
@@ -118,6 +122,11 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
"enum": [config.RESET_ON, config.RESET_OFF],
|
||||
"description": "自动切月=月份不符时清明细/新办卡、汇总日期行滚到当月、期初取上月末",
|
||||
},
|
||||
"push_users": {
|
||||
"type": "string", "title": "钉钉推送接收人", "default": config.DEFAULT_PUSH_USERS,
|
||||
"description": "姓名/工号,多个用「、」「,」「;」或换行分隔(如同名须带工号);"
|
||||
"留空=不推送;仅「只推送台账」执行方式会推送",
|
||||
},
|
||||
"wcf_url": {
|
||||
"type": "string", "title": "取数地址", "default": "",
|
||||
"description": "留空=使用默认地址(技术排障用,一般不用填)",
|
||||
@@ -156,6 +165,10 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
ctx.log("数据源:WCF " + cfg.wcf_url)
|
||||
ctx.log("执行方式:" + mode)
|
||||
|
||||
# 「只推送台账」:不取数、不动表,定位当天那份台账直接推送(推送单独定时用)
|
||||
if mode == config.LEDGER_MODE_PUSH_ONLY:
|
||||
return self._push_only(fields, ctx, day, sdk_ver)
|
||||
|
||||
# ---------- 一、导出两份 Excel(「只维护台账」时跳过,直接复用快照) ----------
|
||||
if mode == config.LEDGER_MODE_LEDGER_ONLY:
|
||||
try:
|
||||
@@ -214,7 +227,6 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
ctx=ctx)
|
||||
elif not ledger_dir:
|
||||
ctx.log("未配置台账文件夹,跳过台账维护(只出两份导出表)", "WARN")
|
||||
ctx.progress(100)
|
||||
|
||||
summary = (
|
||||
"湖畔储值卡统计完成(营业日 %s,%s)\n"
|
||||
@@ -234,7 +246,9 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
summary += _ledger_summary(ledger)
|
||||
elif mode != config.LEDGER_MODE_EXPORT_ONLY:
|
||||
summary += "\n· 台账:跳过(未找到可用的月度统计 Excel)"
|
||||
ctx.progress(100)
|
||||
|
||||
push_res = None # 推送只走「只推送台账」执行方式
|
||||
return {
|
||||
"summary": summary,
|
||||
"files": files,
|
||||
@@ -245,6 +259,44 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
"balance": balance,
|
||||
"detail": detail,
|
||||
"ledger": ledger,
|
||||
"push": push_res,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 只推送台账
|
||||
def _push_only(self, fields, ctx, day, sdk_ver) -> dict:
|
||||
"""只推送:不取数、不动表,定位当天那份台账 → 钉钉(推送步骤单独定时用)。"""
|
||||
ledger_dir = (fields.get("ledger_file") or "").strip().strip('"')
|
||||
if not ledger_dir:
|
||||
raise RuntimeError(
|
||||
"执行方式=只推送台账,但没配置「台账文件」/文件夹,无法定位要推的表")
|
||||
try:
|
||||
ledger_file = ledger_path.resolve(ledger_dir, day, ctx.log)
|
||||
except ledger_path.LedgerPathError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
if not ledger_file:
|
||||
raise RuntimeError("没找到 %s 对应的月度统计台账,检查「台账文件」设置"
|
||||
% period.day_text(day))
|
||||
|
||||
users = (fields.get("push_users") or "").strip()
|
||||
ctx.progress(60)
|
||||
summary = "台账推送(营业日 %s)\n· 台账:%s" % (period.day_text(day), ledger_file)
|
||||
push_res = push_mod.push_ledger(ledger_file, users, summary, ctx.log)
|
||||
summary += _push_summary(push_res)
|
||||
ctx.progress(100)
|
||||
if not push_res.get("ok"):
|
||||
raise RuntimeError("台账推送失败:%s"
|
||||
% (push_res.get("skipped") or push_res.get("message") or "未知原因"))
|
||||
return {
|
||||
"summary": summary,
|
||||
"files": [ledger_file],
|
||||
"path": ledger_file,
|
||||
"sdk": sdk_ver,
|
||||
"mode": config.LEDGER_MODE_PUSH_ONLY,
|
||||
"window": {},
|
||||
"balance": {},
|
||||
"detail": {},
|
||||
"ledger": {"path": ledger_file},
|
||||
"push": push_res,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 导出
|
||||
@@ -370,4 +422,16 @@ def _ledger_summary(ledger: dict) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _push_summary(push: dict) -> str:
|
||||
"""钉钉推送结果 → 汇总文本里的一行(跳过/成功/失败各有说法)。"""
|
||||
if not push:
|
||||
return ""
|
||||
if push.get("skipped"):
|
||||
return "\n· 钉钉推送:跳过(%s)" % push["skipped"]
|
||||
text = "\n· 钉钉推送:%s" % (push.get("message") or "")
|
||||
for item in push.get("failed") or []:
|
||||
text += "\n ✗ %s" % item
|
||||
return text
|
||||
|
||||
|
||||
PLUGINS.append(HupanStoredCardPlugin())
|
||||
|
||||
@@ -126,6 +126,7 @@ def _check_mode(config) -> list:
|
||||
"导出+维护台账": "导出+维护台账",
|
||||
"只导出": "只导出",
|
||||
"只维护台账": "只维护台账",
|
||||
"只推送台账": "只推送台账",
|
||||
"导表+维护台账": "导出+维护台账",
|
||||
"只导表": "只导出",
|
||||
"": "导出+维护台账",
|
||||
@@ -138,6 +139,27 @@ def _check_mode(config) -> list:
|
||||
return problems
|
||||
|
||||
|
||||
def _check_push() -> list:
|
||||
"""接收人解析:姓名/工号各种写法与分隔符(不发消息、不读凭证)。"""
|
||||
from logic import push
|
||||
|
||||
problems = []
|
||||
cases = {
|
||||
"张三/37036361": [("张三", "37036361")],
|
||||
" 张三/37036361 、李四(37012345);王五(37099999) ": [
|
||||
("张三", "37036361"), ("李四", "37012345"), ("王五", "37099999")],
|
||||
"张三/37036361,李四/37012345\n王五": [
|
||||
("张三", "37036361"), ("李四", "37012345"), ("王五", "")],
|
||||
"": [],
|
||||
"、 , ;": [],
|
||||
}
|
||||
for raw, want in cases.items():
|
||||
got = push.parse_recipients(raw)
|
||||
if got != want:
|
||||
problems.append("parse_recipients(%r) = %r,应为 %r" % (raw, got, want))
|
||||
return problems
|
||||
|
||||
|
||||
def _check_ledger() -> list:
|
||||
"""台账维护的纯逻辑(不碰 Excel):Excel 日期序列、待补日期窗口与数据归属日。"""
|
||||
from datetime import datetime
|
||||
@@ -232,14 +254,25 @@ def _check_ledger_path() -> list:
|
||||
if ledger_path.resolve(got, day) != got:
|
||||
problems.append("填完整文件路径时应原样使用")
|
||||
|
||||
# 多份且都没当月年月 → 报错(不猜)
|
||||
# 目标月份的表不在:有年月信息 → 取最新月份那份(切月换表)
|
||||
touch("2026年10月会员卡统计.xlsx")
|
||||
touch("2026年12月会员卡统计.xlsx")
|
||||
got = ledger_path.resolve(root, day)
|
||||
if os.path.basename(got) != "2026年12月会员卡统计.xlsx":
|
||||
problems.append(f"跨月应取最新月份台账:{got}")
|
||||
|
||||
# 全都没年月又多份 → 报错(不猜)
|
||||
sub = os.path.join(root, "无年月")
|
||||
os.mkdir(sub)
|
||||
for n in ("会员卡统计.xlsx", "储值卡统计.xlsx"):
|
||||
with open(os.path.join(sub, n), "wb"):
|
||||
pass
|
||||
try:
|
||||
ledger_path.resolve(root, day)
|
||||
ledger_path.resolve(sub, day)
|
||||
except ledger_path.LedgerPathError:
|
||||
pass
|
||||
else:
|
||||
problems.append("多份台账分不清时应抛 LedgerPathError")
|
||||
problems.append("都没年月又多份时应抛 LedgerPathError")
|
||||
|
||||
# 有当月年月 → 用它
|
||||
touch("2026年11月会员卡统计-模版调整-新会员卡.xlsx")
|
||||
@@ -266,7 +299,7 @@ def main() -> int:
|
||||
import config
|
||||
from logic import period
|
||||
|
||||
problems = (_check_period(period) + _check_mode(config)
|
||||
problems = (_check_period(period) + _check_mode(config) + _check_push()
|
||||
+ _check_ledger() + _check_ledger_path())
|
||||
if problems:
|
||||
print("口径异常:\n- " + "\n- ".join(problems), file=sys.stderr)
|
||||
|
||||
@@ -16,13 +16,15 @@ WCF_TIMEOUT = 180
|
||||
#: 留空则在界面上清掉即可关闭台账维护;也支持直接填完整文件路径
|
||||
DEFAULT_LEDGER_DIR = r"D:\资料\财务\湖畔储值卡每日导出统计"
|
||||
|
||||
#: 执行方式(plugin.json fields.ledger_mode.enum 与之一致)。分两步是为了「表维护失败不用重导」:
|
||||
#: 导出+维护台账 = 一次跑完(默认)
|
||||
#: 执行方式(plugin.json fields.ledger_mode.enum 与之一致)。拆开是为了能分开定时:
|
||||
#: 导出+维护台账 = 一次跑完导出与台账(默认)
|
||||
#: 只导出 = 只取数、落两份 Excel,并留下快照(不动台账)
|
||||
#: 只维护台账 = 复用上一次导出留下的快照,只跑 WPS 台账维护(不取数、不重写两份表)
|
||||
#: 只推送台账 = 不动文件,直接把当天那份台账推到钉钉(推送步骤单独定时用)
|
||||
LEDGER_MODE_FULL = "导出+维护台账"
|
||||
LEDGER_MODE_EXPORT_ONLY = "只导出"
|
||||
LEDGER_MODE_LEDGER_ONLY = "只维护台账"
|
||||
LEDGER_MODE_PUSH_ONLY = "只推送台账"
|
||||
#: v0.3.x 的旧值(老方案/老配置里存的是这些字面量)
|
||||
_LEDGER_MODE_ALIASES = {
|
||||
"导表+维护台账": LEDGER_MODE_FULL,
|
||||
@@ -31,10 +33,11 @@ _LEDGER_MODE_ALIASES = {
|
||||
|
||||
|
||||
def normalize_mode(value) -> str:
|
||||
"""表单值 → 三种执行方式之一(旧值自动映射,空值按「导出+维护台账」)。"""
|
||||
"""表单值 → 四种执行方式之一(旧值自动映射,空值按「导出+维护台账」)。"""
|
||||
text = str(value or "").strip()
|
||||
text = _LEDGER_MODE_ALIASES.get(text, text)
|
||||
if text in (LEDGER_MODE_FULL, LEDGER_MODE_EXPORT_ONLY, LEDGER_MODE_LEDGER_ONLY):
|
||||
if text in (LEDGER_MODE_FULL, LEDGER_MODE_EXPORT_ONLY,
|
||||
LEDGER_MODE_LEDGER_ONLY, LEDGER_MODE_PUSH_ONLY):
|
||||
return text
|
||||
return LEDGER_MODE_FULL
|
||||
|
||||
@@ -51,6 +54,30 @@ RECALC_OFF = "不重算(快)"
|
||||
RESET_ON = "自动切月(推荐)"
|
||||
RESET_OFF = "不切月(只补数)"
|
||||
|
||||
#: 钉钉推送接收人(「姓名/工号」,多个用「、」/「,」/「;」/换行分隔);留空=不推送。
|
||||
#: 推送内容是本次维护后的月度台账:先上传内网文件服务器,再用企业内部应用工作通知发下载链接。
|
||||
DEFAULT_PUSH_USERS = ""
|
||||
|
||||
# ==================== 钉钉推送(企业内部应用工作通知,不用 dws) ====================
|
||||
# 台账 30MB 超过钉钉文件消息 media/upload 的 20MB 上限,所以不直发附件:
|
||||
# 先 POST 到内网文件服务器拿开放下载直链,再用「工作通知」把链接推给个人。
|
||||
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
|
||||
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
|
||||
DINGTALK_AGENT_ID = "4974749954"
|
||||
DINGTALK_TOKEN_V1_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
|
||||
DINGTALK_TOKEN_OAPI_URL = "https://oapi.dingtalk.com/gettoken"
|
||||
DINGTALK_USER_SEARCH_URL = "https://api.dingtalk.com/v1.0/contact/users/search"
|
||||
DINGTALK_USER_GET_URL = "https://oapi.dingtalk.com/user/get"
|
||||
DINGTALK_WORK_SEND_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2"
|
||||
|
||||
# 内网文件服务器(台账上传后凭开放直链下载;上传要 X-API-Token)
|
||||
FILESERVER_BASE_URL = "http://172.30.30.243:8802"
|
||||
FILESERVER_TOKEN = "SD8Fg6SAS0Df8A7F8ASFADac"
|
||||
FILESERVER_UPLOAD_URL = FILESERVER_BASE_URL + "/api/upload"
|
||||
|
||||
#: 推送相关 HTTP 超时(秒):台账 30MB 上传留足余量
|
||||
PUSH_TIMEOUT = 180
|
||||
|
||||
_log = None
|
||||
|
||||
|
||||
|
||||
@@ -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"]}
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0052",
|
||||
"name": "湖畔储值卡每日导出统计",
|
||||
"version": "0.4.3",
|
||||
"description": "按营业日导出金贵系统会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对",
|
||||
"version": "0.6.9",
|
||||
"description": "按营业日导出金贵系统会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对;台账维护与钉钉推送拆成两个执行方式,可分开定时",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
@@ -51,9 +51,10 @@
|
||||
"enum": [
|
||||
"导出+维护台账",
|
||||
"只导出",
|
||||
"只维护台账"
|
||||
"只维护台账",
|
||||
"只推送台账"
|
||||
],
|
||||
"description": "只导出=取数并出两份 Excel(留快照,不动台账);只维护台账=复用上一次导出的快照,不重新取数/导出,台账失败时用它重试"
|
||||
"description": "导出+维护台账=取数、出表并维护台账(不推送);只导出=只出两份 Excel(留快照);只维护台账=复用上一次导出的快照,不重新取数/导出;只推送台账=不取数不动表,直接把当天那份台账推到钉钉(推送单独定时用)"
|
||||
},
|
||||
"ledger_backup": {
|
||||
"type": "string",
|
||||
@@ -85,6 +86,12 @@
|
||||
],
|
||||
"description": "自动切月=检测到台账月份与营业日不符时,清空上月明细/新办卡、汇总日期行滚到当月、期初取上月末;执行前自动备份"
|
||||
},
|
||||
"push_users": {
|
||||
"type": "string",
|
||||
"title": "钉钉推送接收人",
|
||||
"default": "",
|
||||
"description": "姓名/工号,多个用「、」「,」「;」或换行分隔(重名时必须带工号);留空=不推送;仅「只推送台账」执行方式会推送"
|
||||
},
|
||||
"wcf_url": {
|
||||
"type": "string",
|
||||
"title": "取数地址",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# 本插件不直接使用第三方库:会员卡余额/明细的取数与渲染全部由 SDK hotel_report 提供
|
||||
# (SDK 的 deps: openpyxl,执行机环境包已预装)。
|
||||
# 钉钉推送(logic/push.py)用 requests 调钉钉开放接口与内网文件服务器,requests 由执行机环境包预装。
|
||||
# 此文件仅作说明,客户端不会按它安装依赖。
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">执行方式</div>
|
||||
<div class="r-desc">只导出 = 只出两份 Excel;只维护台账 = 复用上次导出,台账失败用它重试</div>
|
||||
<div class="r-desc">维护表与推送拆开:只维护台账 / 只推送台账 可分开定时</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-select v-model="form.ledger_mode" class="sel-mode" :disabled="running">
|
||||
@@ -104,7 +104,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="ledgerOn" class="row">
|
||||
<div v-if="maintainOn" class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">台账选项</div>
|
||||
<div class="r-desc">备份 / 重算 / 切月</div>
|
||||
@@ -140,6 +140,42 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 03 钉钉推送 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">钉钉推送</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<div class="rows">
|
||||
<div class="row rec-row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">推送接收人</div>
|
||||
</div>
|
||||
<div class="r-ctrl rec-ctrl">
|
||||
<div class="rec-edit">
|
||||
<el-tag v-for="(r, i) in recipients" :key="i + '-' + r.name + '-' + r.code"
|
||||
class="rec-tag" closable size="small" type="success" effect="plain"
|
||||
:disable-transitions="true" @close="removeRecipient(i)">
|
||||
{{ r.name }}<span v-if="r.code" class="rec-code-txt">/{{ r.code }}</span>
|
||||
</el-tag>
|
||||
<el-input v-model="pushName" class="rec-name" :disabled="running" clearable
|
||||
placeholder="姓名,可粘贴多人"
|
||||
@keyup.enter="addRecipient" />
|
||||
<el-input v-model="pushCode" class="rec-code" :disabled="running" clearable
|
||||
placeholder="工号(重名必填)"
|
||||
@keyup.enter="addRecipient" />
|
||||
<el-button class="ctrl-btn" :disabled="running" @click="addRecipient">添加</el-button>
|
||||
<el-button v-if="recipients.length" text size="small" :disabled="running"
|
||||
@click="clearRecipients">清空</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 说明 -->
|
||||
<details class="help">
|
||||
<summary><span>说明</span><span class="h-arrow">▾</span></summary>
|
||||
@@ -175,12 +211,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 选项必须与后端 config / plugin.json.fields 的 enum 完全一致
|
||||
const MODES = ['导出+维护台账', '只导出', '只维护台账']
|
||||
const MODES = ['导出+维护台账', '只导出', '只维护台账', '只推送台账']
|
||||
const BACKUPS = ['先备份', '不备份']
|
||||
const RECALCS = ['重算(推荐)', '不重算(快)']
|
||||
const RESETS = ['自动切月(推荐)', '不切月(只补数)']
|
||||
@@ -194,6 +230,7 @@ const DEFAULTS = () => ({
|
||||
ledger_backup: '先备份',
|
||||
ledger_recalc: '重算(推荐)',
|
||||
ledger_month_reset: '自动切月(推荐)',
|
||||
push_users: '',
|
||||
})
|
||||
|
||||
const {
|
||||
@@ -220,12 +257,15 @@ const {
|
||||
p.day = p.day || ''
|
||||
p.save_dir = String(p.save_dir || '').trim()
|
||||
p.ledger_file = String(p.ledger_file || '').trim()
|
||||
p.push_users = String(p.push_users || '').trim()
|
||||
return p
|
||||
},
|
||||
})
|
||||
|
||||
// 只导出不碰台账;「导出+维护台账」「只维护台账」都要台账
|
||||
// 只导出不碰台账;「导出+维护台账」「只维护台账」「只推送台账」都要台账
|
||||
const ledgerOn = computed(() => form.ledger_mode !== '只导出')
|
||||
// 台账备份/重算/切月只在真正维护表时才有意义(只推送不动表)
|
||||
const maintainOn = computed(() => ledgerOn.value && form.ledger_mode !== '只推送台账')
|
||||
|
||||
// 窗口提示:只描述口径,真正的时间点在执行日志里(需要查交班)
|
||||
const windowHint = computed(() => (form.day
|
||||
@@ -235,6 +275,73 @@ const windowHint = computed(() => (form.day
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框
|
||||
const picking = ref(false)
|
||||
|
||||
// ---------- 钉钉推送接收人:按「姓名 + 工号」逐个添加,存成后端约定的 "姓名/工号、…" ----------
|
||||
const pushName = ref('')
|
||||
const pushCode = ref('')
|
||||
const recipients = ref([]) // [{ name, code }]
|
||||
|
||||
const REC_SEP = /[,,、;;\n\r]+/
|
||||
const BADGE_OPEN = /[//((]/
|
||||
|
||||
// 与后端 logic/push.parse_recipients 保持同一口径
|
||||
function parseRecipients(text) {
|
||||
const out = []
|
||||
String(text || '').split(REC_SEP).forEach((raw) => {
|
||||
const item = String(raw || '').trim().replace(/^["'“”]+|["'“”]+$/g, '')
|
||||
if (!item) return
|
||||
let name = item
|
||||
let code = ''
|
||||
const idx = item.search(BADGE_OPEN)
|
||||
if (idx >= 0) {
|
||||
name = item.slice(0, idx).trim()
|
||||
code = item.slice(idx + 1).replace(/[))]/g, '').trim()
|
||||
}
|
||||
if (name) out.push({ name, code })
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
function recipientsToText(list) {
|
||||
return (list || []).map((r) => (r.code ? `${r.name}/${r.code}` : r.name)).join('、')
|
||||
}
|
||||
|
||||
// 方案加载 / 恢复默认 / 手改 form.push_users → 重建标签;自己写回时不重建(顺序不乱)
|
||||
watch(() => form.push_users, (v) => {
|
||||
if (recipientsToText(recipients.value) === String(v || '').trim()) return
|
||||
recipients.value = parseRecipients(v)
|
||||
}, { immediate: true })
|
||||
|
||||
function addRecipient() {
|
||||
const name = pushName.value.trim()
|
||||
const code = pushCode.value.trim()
|
||||
if (!name && !code) return
|
||||
// 姓名框里粘贴了多个/带工号时按原文解析,否则拼「姓名/工号」
|
||||
const text = (REC_SEP.test(name) || BADGE_OPEN.test(name)) ? name : (code ? `${name}/${code}` : name)
|
||||
const list = parseRecipients(text)
|
||||
if (!list.length) {
|
||||
ElMessage.warning('请先填接收人姓名')
|
||||
return
|
||||
}
|
||||
list.forEach((r) => {
|
||||
if (!recipients.value.some((x) => x.name === r.name && x.code === r.code)) {
|
||||
recipients.value.push(r)
|
||||
}
|
||||
})
|
||||
pushName.value = ''
|
||||
pushCode.value = ''
|
||||
form.push_users = recipientsToText(recipients.value)
|
||||
}
|
||||
|
||||
function removeRecipient(i) {
|
||||
recipients.value.splice(i, 1)
|
||||
form.push_users = recipientsToText(recipients.value)
|
||||
}
|
||||
|
||||
function clearRecipients() {
|
||||
recipients.value = []
|
||||
form.push_users = ''
|
||||
}
|
||||
|
||||
// 旧配置里台账存的是完整文件路径,选目录时回退到它所在目录
|
||||
function dirOf(v) {
|
||||
const s = String(v || '').trim()
|
||||
@@ -332,11 +439,28 @@ async function pickLedger() {
|
||||
.opt-k { font: 500 12px/1 var(--f-cn); color: var(--t3); }
|
||||
.sel-sm { width: 158px; }
|
||||
|
||||
/* 推送接收人:标题在左,控件紧跟其后(不推到行尾),紧凑不铺满 */
|
||||
.rows .rec-row { align-items: center; justify-content: flex-start; }
|
||||
.rec-ctrl { flex: 1 1 auto; min-width: 0; }
|
||||
.rec-edit {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.rec-name { width: 150px; flex: 0 0 150px; }
|
||||
.rec-code { width: 126px; flex: 0 0 126px; }
|
||||
.rec-tag { flex: 0 0 auto; }
|
||||
.rec-code-txt { color: var(--t3); font-variant-numeric: tabular-nums; }
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.rows .row { flex-direction: column; align-items: stretch; gap: var(--space-2); }
|
||||
.r-ctrl { width: 100%; justify-content: flex-start; }
|
||||
.row .r-ctrl.is-wide { margin-left: 0; }
|
||||
.day-pick, .sel-mode, .sel-sm { width: 100%; }
|
||||
.opt-line { justify-content: flex-start; }
|
||||
.rec-edit { justify-content: flex-start; }
|
||||
.rec-name, .rec-code { flex: 1 1 120px; width: auto; }
|
||||
}
|
||||
</style>
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+21
-21
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>湖畔储值卡每日导出统计</title>
|
||||
<script type="module" crossorigin src="/pui/xq0052/assets/index-LUCCty2j.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0052/assets/index-BvjwJu6v.css">
|
||||
<script type="module" crossorigin src="/pui/xq0052/assets/index-_RX4paMs.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0052/assets/index-86D5nBo2.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
|
||||
Reference in New Issue
Block a user