feat(xq0052): 台账改用 WPS 维护并新增导出快照,支持只导出/只维护台账(0.4.0)
- 新增 logic/snapshot.py:导出后落快照,台账失败可复用上次导出数据重试,不用重新取数 - 台账只走 WPS 表格(不调 Office),字段提示同步改为关闭 WPS - 新增 通联扫码统计 支付数据追加 / 流程 两个测试;前端重建(ui 产物 + usePluginUI/style 拆分)
This commit is contained in:
@@ -1,9 +1,13 @@
|
||||
# XQ0052 湖畔储值卡每日导出统计
|
||||
|
||||
> 状态:v0.3.0(带界面),2026-11-09。
|
||||
> 状态:v0.4.0(带界面),2026-11-10。
|
||||
> v0.4.0:① 台账**只连 WPS 表格**(`Ket.Application`),装没装 Office 都不会去调 Microsoft Excel;
|
||||
> ② 流程拆成「导出」和「表维护」两步(见 §2「执行方式」):台账失败不用重新取数导出;
|
||||
> ③ v0.3.1 的「服务器忙」COM 重试保留(见 §2「只用 WPS」)。
|
||||
> 两件事:① 按营业日导出会员卡余额/明细两份 Excel;② 维护月度统计台账
|
||||
> `2026年11月会员卡统计-模版调整-新会员卡.xlsx`(交班时间/余额/明细/新办卡 + 汇总核对)。
|
||||
> 取数/渲染由 SDK `hotel_report`(0.3.0 起)提供;台账维护走 Excel/WPS COM(openpyxl 会丢模板图表)。
|
||||
> 取数/渲染由 SDK `hotel_report`(0.3.0 起)提供;台账维护走 WPS 表格 COM
|
||||
> (不用 openpyxl 保存:会丢模板里的 4 个图表和 15 张图)。
|
||||
> v0.3.0 起面板「台账文件」可选文件(壳子 `/api/dialog/file`,旧壳子退化为选文件夹),
|
||||
> 填文件夹时由 `logic/ledger_path.py` 按营业日年月自动匹配当月那份,见 §2.1。
|
||||
> 取数节流在 SDK 里(`hotel_report` 0.3.1 起,`wcf.query` 自带 ≥1.2s/次),插件不做、也不用管。
|
||||
@@ -63,6 +67,52 @@
|
||||
`wcf.query` / `wcf.query_proc` 相邻两次请求至少间隔 `HotelConfig.min_interval`(默认 1.2s),
|
||||
本插件不需要实现(`settle_window` / `export_member` / `collect.*` 自动生效),补 7 天多等十几秒。
|
||||
|
||||
### 执行方式:导出与表维护分两步(v0.4.0)
|
||||
|
||||
面板「执行方式」三选一(`logic/__init__.py` 的 `normalize_mode`,老配置里的
|
||||
`导表+维护台账` / `只导表` 会自动映射):
|
||||
|
||||
| 方式 | 做什么 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `导出+维护台账`(默认) | 取数 → 落两份 Excel + 导出快照 → 用 WPS 维护台账 | 日常一键跑完 |
|
||||
| `只导出` | 只取数落表 + 存快照,**不碰台账**(不需要装 WPS) | 台账机器没装 WPS、或先出表给财务看 |
|
||||
| `只维护台账` | **复用上一次导出**(快照),只跑 WPS 台账维护 | 表维护失败后重试;不用再取 20 万行余额 |
|
||||
|
||||
导出快照:`%LOCALAPPDATA%\37duAutomation\plugin_data\xq0052\snapshot_<营业日>.pkl.gz`
|
||||
(pickle+gzip,一个营业日一份,重跑导出会覆盖;里面是两份结果表,删掉不影响任何业务数据)。
|
||||
台账阶段命中快照就用快照的余额/明细,只有要补历史天数(快照里没有那天)才回查 WCF。
|
||||
台账失败时日志会提示「改成『只维护台账』重试」,不用重新导出。
|
||||
|
||||
### 只用 WPS:从不调用 Microsoft Excel(v0.4.0)
|
||||
|
||||
以前用 `DispatchEx("Excel.Application")`——装了 Office 的机器上这会拉起 **Microsoft Excel**,
|
||||
既会跟用户自己开着的 Excel 抢那份台账、也和本插件验证过的环境不一致。现在只用 WPS 表格:
|
||||
|
||||
- 按顺序试 `Ket.Application`(WPS 官方 ProgID)/ `KET.Application`,**绝不回退 Excel 的 ProgID**;
|
||||
- 连上后校验 `app.Path` 落在 WPS 安装目录(`kingsoft` / `wps`),被别的办公软件接管就换下一个;
|
||||
- 都失败 → 报「没有找到可用的 WPS 表格 COM 接口」并列出每个 ProgID 的失败原因;
|
||||
- 日志首行会写「表格引擎:WPS(Ket.Application)<WPS 安装目录>」,便于确认没走错。
|
||||
|
||||
### COM 稳定性:服务器忙自动重试(v0.3.1 起)
|
||||
|
||||
台账是 31MB / 20 万行 + 4 张图表的工作簿,WPS 会在这几个时刻把 COM 请求**直接打回**
|
||||
(`pywintypes.com_error -2147418111 被呼叫方拒绝接收呼叫`):
|
||||
|
||||
- `Workbooks.Open` 刚刚返回、工作簿还在装配内存(实测 09:43:33 打开 → 09:43:49 访问 sheet 被拒);
|
||||
- 整簿重算(20 万行公式)、被安全软件扫描、弹模态框。
|
||||
|
||||
这类错误表示**调用没有被执行**,等对方空闲重发是安全的。做法:
|
||||
|
||||
| 位置 | 处理 |
|
||||
|---|---|
|
||||
| `_com_call()` | 统一重试「服务器忙」类 HRESULT(`CALL_REJECTED` / `SERVERCALL_RETRYLATER` / …),1 秒一次、最长 5 分钟;其它 COM 错误(如文件被占用)**不重试**,原样抛出 |
|
||||
| `_wait_ready()` | Open 之后先探 `wb.Name` 探通再往下走(Open 返回 ≠ 可用),等了多久会写日志 |
|
||||
| sheet / 单元格 / 整块写入 / 插删行 / 公式填充 / 重算 / Save / Close / Quit | 全部走 `_com_call` |
|
||||
| 收尾 | `Close`/`Quit` 失败只告警,不再把真正的异常盖掉(以前一抛就看不到根因) |
|
||||
|
||||
在 WPS 上实测(2026-11-10,模板副本):开表 → 补 1 天(交班 1 + 明细 159 + 新办卡 72)→
|
||||
余额 207,211 人覆盖 → 核对 → 保存,全程 1.4 分钟无异常。
|
||||
|
||||
### 切月初始化(每月第一次跑自动做)
|
||||
|
||||
模板每月一份,里面残留着上个月的数据。检测到「本月汇总数」的日期行不在目标月份时,先做一次初始化(**执行前已备份**):
|
||||
@@ -92,13 +142,14 @@
|
||||
```
|
||||
XQ0052 湖畔储值卡每日导出统计/
|
||||
├─ plugin.json # ui:true + requires.sdks(^0.3) + 台账字段
|
||||
├─ __init__.py # 导表 → 维护台账 → 汇总(含核对结果)
|
||||
├─ config/ # 默认导出目录 / 默认台账文件夹 / 开关常量 / 超时
|
||||
├─ __init__.py # 导出(取数+落表+快照)→ 维护台账 → 汇总(含核对结果)
|
||||
├─ config/ # 默认导出目录 / 默认台账文件夹 / 执行方式 / 开关常量 / 超时
|
||||
├─ logic/
|
||||
│ ├─ period.py # 营业日解析(空=今天)
|
||||
│ ├─ ledger_path.py # 台账文件/文件夹 → 实际 Excel(按营业日年月自动匹配,分不清就报错)
|
||||
│ ├─ provider.py # 把 SDK 包成台账要的三个取数接口(带缓存)
|
||||
│ └─ ledger.py # Excel COM 台账维护(四张 sheet + 核对)
|
||||
│ ├─ snapshot.py # 导出快照(导出与表维护两步之间的交接文件)
|
||||
│ ├─ provider.py # SDK 取数包装:SdkProvider / SnapshotProvider(优先复用快照)
|
||||
│ └─ ledger.py # WPS 表格 COM 台账维护(四张 sheet + 核对;不乱调 Office)
|
||||
├─ ui-src/ # 前端源码(Vue3 + Element Plus + Vite,打包时排除)
|
||||
│ ├─ index.html / package.json / vite.config.js
|
||||
│ └─ src/{main.js, style.css, api.js, usePluginUI.js, App.vue}
|
||||
@@ -111,7 +162,8 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
参数即 `plugin.json.fields` 的可视化编辑器(二者必须一致);`wcf_url` 属技术排障项,不出现在界面上。
|
||||
|
||||
两段都用规范的 `.rows > .row` 行卡片(左标题+说明 / 右控件),02 四行分别是:
|
||||
导出文件保存到、台账维护、台账文件、台账选项(备份 / 重算 / 切月 一行排开,各带小标签)。
|
||||
导出文件保存到、执行方式(导出+维护台账 / 只导出 / 只维护台账)、台账文件、
|
||||
台账选项(备份 / 重算 / 切月 一行排开,各带小标签)。
|
||||
|
||||
## 4. 表单字段(plugin.json 为权威)
|
||||
|
||||
@@ -120,7 +172,7 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
| `day` | 营业日,`YYYY-MM-DD`;**留空 = 今天** |
|
||||
| `save_dir` | 两份导出表保存到,默认 `D:\资料\财务\湖畔储值卡统计` |
|
||||
| `ledger_file` | 台账文件完整路径,或它所在的**文件夹**(默认 `D:\资料\财务\湖畔储值卡每日导出统计`,按年月自动匹配当月那份);留空=不维护(见 §2.1) |
|
||||
| `ledger_mode` | `导表+维护台账` / `只导表` |
|
||||
| `ledger_mode` | `导出+维护台账` / `只导出` / `只维护台账`(旧值 `导表+维护台账` / `只导表` 自动映射,见 §2「执行方式」) |
|
||||
| `ledger_backup` | `先备份`(同目录生成 `<台账名>_备份_YYYYMMDD_HHMMSS.xlsx`)/ `不备份` |
|
||||
| `ledger_recalc` | `重算(推荐)` / `不重算(快)`;模板公式是整列引用,20 万行全量重算在 WPS 上可能要几分钟,不重算则由 Excel 打开时自行计算(核对项会读到旧值) |
|
||||
| `ledger_month_reset` | `自动切月(推荐)` / `不切月(只补数)`;月份不符时清上月明细/新办卡、汇总日期行滚到当月、期初取上月末 |
|
||||
@@ -141,7 +193,7 @@ XQ0052 湖畔储值卡每日导出统计/
|
||||
# 4. 台账维护(在模板副本上跑,不碰生产文件;加 --inplace 才动生产台账并自动备份)
|
||||
.venv\Scripts\python.exe tests\xq0052_湖畔储值卡\ledger_e2e.py --day 2026-11-02
|
||||
|
||||
# 5. 前端构建(改了 ui-src 才需要;借用 XQ0081 的 node_modules,不重复安装)
|
||||
# 5. 前端构建(改了 ui-src 才需要;脚本会在 ui-src 里 npm install,再 vite build 到 ../ui)
|
||||
powershell -ExecutionPolicy Bypass -File "plugins\XQ0001-0100\XQ0052 湖畔储值卡每日导出统计\ui-src\_build.ps1"
|
||||
```
|
||||
|
||||
@@ -165,7 +217,7 @@ powershell -ExecutionPolicy Bypass -File "plugins\XQ0001-0100\XQ0052 湖畔储
|
||||
```powershell
|
||||
.venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0052 湖畔储值卡每日导出统计\_pack.py"
|
||||
.venv\Scripts\python.exe tools\agent_cli.py --base http://172.30.30.243:8800 --admin puddy --password 123456 `
|
||||
publish dist-plugin\xq0052_v0.3.0.zip --id xq0052 --name 湖畔储值卡每日导出统计 --version 0.3.0
|
||||
publish dist-plugin\xq0052_v0.4.0.zip --id xq0052 --name 湖畔储值卡每日导出统计 --version 0.4.0
|
||||
```
|
||||
|
||||
> `publish` 默认进**测试通道**,人工验证通过后由人执行 `plugin-status xq0052 --status published` 转正。
|
||||
@@ -173,8 +225,12 @@ powershell -ExecutionPolicy Bypass -File "plugins\XQ0001-0100\XQ0052 湖畔储
|
||||
|
||||
## 7. 已知限制 / 注意
|
||||
|
||||
- 台账维护需要 **Excel 或 WPS**(走 COM;openpyxl 保存会丢模板里的 4 个图表);
|
||||
- 运行前**必须关闭该 Excel 文件**,否则打开失败并报「文件被占用」;
|
||||
- 台账维护**只走 WPS 表格**(`Ket.Application`),执行机必须装 WPS;装没装 Office 都不影响,
|
||||
没有 WPS 时只跑「只导出」也能出两份表(openpyxl 保存会丢模板里的 4 个图表和 15 张图,所以不用它);
|
||||
- 运行前**必须关闭该台账**(WPS 里打开着会报「文件被占用」,改动也可能丢);
|
||||
- 等满重试(5 分钟)仍报「被呼叫方拒绝接收呼叫」→ 多半是 WPS 弹了模态框(受保护视图、
|
||||
宏/链接提示、恢复窗格)或进程卡死:手工打开该台账把提示点掉(或结束残留 wps/et 进程)后重跑;
|
||||
失败时不会保存,磁盘上的台账没被改(备份已自动生成),改成「只维护台账」重跑即可;
|
||||
- 余额每天整体覆盖(20 万行 / 写入约 30 秒);明细、新办卡是按天**累积追加**;
|
||||
- 台账落后多天时会自动逐日补齐(每天一次 WCF 明细查询,很快);某天无总交班则跳过并告警;
|
||||
- 所有 WCF 查询按 **≥1.2s/次** 节流(SDK `hotel_report` 0.3.1 起,`HotelConfig.min_interval`):
|
||||
|
||||
@@ -2,7 +2,13 @@
|
||||
"""XQ0052 湖畔储值卡每日导出统计 —— 消费 SDK `hotel_report` 的会员卡统计插件。
|
||||
|
||||
取数/渲染全部由 SDK 提供(宿主按 `plugin.json.requires.sdks` 挂载 `hotel_report`),插件只负责:
|
||||
读表单 → 解析营业日 → 让 SDK 现算「前一日最晚交班 ~ 当日最晚交班」→ 一次导出余额 + 明细。
|
||||
读表单 → 解析营业日 → 让 SDK 现算「前一日最晚交班 ~ 当日最晚交班」→ 导出余额 + 明细 → 维护台账。
|
||||
|
||||
执行方式分三步可选(`config.LEDGER_MODE_*`):
|
||||
· 导出+维护台账:一次跑完;
|
||||
· 只导出:只取数落表 + 存导出快照,不碰台账(也不需要 WPS);
|
||||
· 只维护台账:复用上次导出的快照,只跑台账 —— 台账那步失败时重试用它,不用重新取数导出。
|
||||
台账维护走 **WPS 表格 COM(Ket.Application)**,装了 Office 也不会去调用 Microsoft Excel。
|
||||
|
||||
业务背景:储值卡(会员卡)按**营业日**结算,营业日由交班切开,不是自然日零点的。
|
||||
所以窗口必须用两天的**最晚总交班时间**(`dt_changeclass` 里 `ChangeClassId like 'Z%'` 的最大值):
|
||||
@@ -19,6 +25,7 @@ from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .logic import ledger_path, period
|
||||
from .logic import snapshot as snapshot_store
|
||||
|
||||
|
||||
def _sdk_versions() -> dict:
|
||||
@@ -34,7 +41,7 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0052"
|
||||
name = "湖畔储值卡每日导出统计"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
description = ("按营业日导出会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:"
|
||||
"交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对")
|
||||
platform = ""
|
||||
@@ -55,12 +62,15 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
"type": "string", "title": "台账文件",
|
||||
"default": config.DEFAULT_LEDGER_DIR,
|
||||
"description": "当月那份月度统计 Excel 的完整路径;也可填它所在的文件夹"
|
||||
"(运行时按营业日年月自动匹配当月那份);留空=不维护台账;需关闭 Excel 后运行",
|
||||
"(运行时按营业日年月自动匹配当月那份);留空=不维护台账;"
|
||||
"需在 WPS 里关掉这份台账(只用 WPS 维护,不调用 Office)",
|
||||
},
|
||||
"ledger_mode": {
|
||||
"type": "string", "title": "台账维护", "default": config.LEDGER_MODE_FULL,
|
||||
"enum": [config.LEDGER_MODE_FULL, config.LEDGER_MODE_EXPORT_ONLY],
|
||||
"description": "只导表=仅产出两份 Excel,不动台账",
|
||||
"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(留快照);只维护台账=复用上次导出,"
|
||||
"不重新取数(台账失败时用它重试)",
|
||||
},
|
||||
"ledger_backup": {
|
||||
"type": "string", "title": "台账备份", "default": config.BACKUP_ON,
|
||||
@@ -70,7 +80,7 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
"ledger_recalc": {
|
||||
"type": "string", "title": "台账重算", "default": config.RECALC_ON,
|
||||
"enum": [config.RECALC_ON, config.RECALC_OFF],
|
||||
"description": "不重算则由 Excel 打开文件时自行计算(核对项会读到旧值)",
|
||||
"description": "不重算则由 WPS 打开文件时自行计算(核对项会读到旧值)",
|
||||
},
|
||||
"ledger_month_reset": {
|
||||
"type": "string", "title": "切月初始化", "default": config.RESET_ON,
|
||||
@@ -108,51 +118,64 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
save_dir = config.ensure_dir((fields.get("save_dir") or "").strip().strip('"')
|
||||
or config.DEFAULT_SAVE_DIR)
|
||||
cfg = hotel_report.HotelConfig.resolve(str(fields.get("wcf_url") or ""), config.WCF_TIMEOUT)
|
||||
mode = config.normalize_mode(fields.get("ledger_mode"))
|
||||
|
||||
ctx.log("营业日:" + period.day_text(day))
|
||||
ctx.log("输出目录:" + save_dir)
|
||||
ctx.log("数据源:WCF " + cfg.wcf_url)
|
||||
ctx.log("执行方式:" + mode)
|
||||
|
||||
# ---------- 结算窗口:前一日最晚总交班 ~ 当日最晚总交班 ----------
|
||||
try:
|
||||
window = hotel_report.settle_window(cfg, day)
|
||||
except hotel_report.SDKError as e:
|
||||
raise RuntimeError(f"取最晚交班时间失败:{e}") from e
|
||||
# ---------- 一、导出两份 Excel(「只维护台账」时跳过,直接复用快照) ----------
|
||||
if mode == config.LEDGER_MODE_LEDGER_ONLY:
|
||||
try:
|
||||
snapshot = snapshot_store.load(day, log=ctx.log)
|
||||
except snapshot_store.SnapshotError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
window = snapshot.get("window") or {}
|
||||
files = list(snapshot.get("files") or [])
|
||||
if not window.get("end"):
|
||||
raise RuntimeError("导出快照里没有结算窗口,请重新跑「只导出」")
|
||||
ctx.log("统计窗口(快照):%s ~ %s" % (window.get("start"), window.get("end")))
|
||||
balance = _table_info(snapshot.get("balance"))
|
||||
detail = _table_info(snapshot.get("detail"))
|
||||
ctx.progress(55)
|
||||
else:
|
||||
# 结算窗口:前一日最晚总交班 ~ 当日最晚总交班
|
||||
try:
|
||||
window = hotel_report.settle_window(cfg, day)
|
||||
except hotel_report.SDKError as e:
|
||||
raise RuntimeError(f"取最晚交班时间失败:{e}") from e
|
||||
|
||||
ctx.log("最晚交班:前一日 %s / 当日 %s" % (
|
||||
window.get("prev_latest") or "无记录", window.get("latest") or "尚未交班"))
|
||||
if not window["closed"]:
|
||||
raise RuntimeError(
|
||||
"%s 还没有交班记录,结算窗口未闭合:等夜审交班后再跑" % period.day_text(day))
|
||||
ctx.log("统计窗口:%s ~ %s" % (window["start"], window["end"]))
|
||||
ctx.log("最晚交班:前一日 %s / 当日 %s" % (
|
||||
window.get("prev_latest") or "无记录", window.get("latest") or "尚未交班"))
|
||||
if not window["closed"]:
|
||||
raise RuntimeError(
|
||||
"%s 还没有交班记录,结算窗口未闭合:等夜审交班后再跑" % period.day_text(day))
|
||||
ctx.log("统计窗口:%s ~ %s" % (window["start"], window["end"]))
|
||||
|
||||
# ---------- 一、导出两份 Excel(余额 + 明细) ----------
|
||||
ctx.progress(5)
|
||||
try:
|
||||
res = hotel_report.export_member(cfg, day, save_dir, window=window,
|
||||
log=ctx.log, progress=_sub(5, 55))
|
||||
except hotel_report.DataError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
|
||||
balance = res.get("balance") or {}
|
||||
detail = res.get("detail") or {}
|
||||
files = res.get("files") or []
|
||||
if not files:
|
||||
raise RuntimeError("没有导出任何文件:余额与明细都为空,请检查数据源")
|
||||
try:
|
||||
exported = self._export(hotel_report, cfg, day, window, save_dir, ctx)
|
||||
except hotel_report.DataError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
files = exported["files"]
|
||||
balance = exported["balance"]
|
||||
detail = exported["detail"]
|
||||
snapshot = {"window": window, "files": files,
|
||||
"balance": exported["balance_table"],
|
||||
"detail": exported["detail_table"]}
|
||||
|
||||
# ---------- 二、维护月度统计台账(交班时间/余额/明细/新办卡 + 核对) ----------
|
||||
# 面板只能选文件夹(壳子没有选文件接口),台账 Excel 由 ledger_path 在目录里按年月自动匹配
|
||||
ledger_dir = (fields.get("ledger_file") or "").strip().strip('"')
|
||||
mode = str(fields.get("ledger_mode") or config.LEDGER_MODE_FULL)
|
||||
ledger = None
|
||||
if mode == config.LEDGER_MODE_FULL:
|
||||
if mode != config.LEDGER_MODE_EXPORT_ONLY:
|
||||
try:
|
||||
ledger_file = ledger_path.resolve(ledger_dir, day, ctx.log)
|
||||
except ledger_path.LedgerPathError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
if ledger_file:
|
||||
ledger = self._maintain_ledger(
|
||||
hotel_report, cfg, day, ledger_file,
|
||||
hotel_report, cfg, day, ledger_file, snapshot,
|
||||
backup=str(fields.get("ledger_backup") or config.BACKUP_ON) == config.BACKUP_ON,
|
||||
recalc=str(fields.get("ledger_recalc") or config.RECALC_ON) == config.RECALC_ON,
|
||||
month_reset=str(fields.get("ledger_month_reset")
|
||||
@@ -163,14 +186,14 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
ctx.progress(100)
|
||||
|
||||
summary = (
|
||||
"湖畔储值卡统计完成(营业日 %s)\n"
|
||||
"湖畔储值卡统计完成(营业日 %s,%s)\n"
|
||||
"· 结算窗口:%s ~ %s\n"
|
||||
"· 会员卡余额:%s 人,卡内余额合计 %s\n"
|
||||
"· 会员卡明细:%s 行\n"
|
||||
"· 导出目录:%s"
|
||||
) % (
|
||||
period.day_text(day),
|
||||
window["start"], window["end"],
|
||||
period.day_text(day), mode,
|
||||
window.get("start", ""), window.get("end", ""),
|
||||
f"{int(balance.get('count') or 0):,}",
|
||||
f"{(balance.get('totals') or {}).get('卡内余额', 0.0):,.2f}",
|
||||
f"{int(detail.get('count') or 0):,}",
|
||||
@@ -178,25 +201,69 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
)
|
||||
if ledger:
|
||||
summary += _ledger_summary(ledger)
|
||||
elif mode == config.LEDGER_MODE_FULL:
|
||||
elif mode != config.LEDGER_MODE_EXPORT_ONLY:
|
||||
summary += "\n· 台账:跳过(未找到可用的月度统计 Excel)"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"files": files,
|
||||
"path": files[0],
|
||||
"path": files[0] if files else "",
|
||||
"sdk": sdk_ver,
|
||||
"mode": mode,
|
||||
"window": window,
|
||||
"balance": balance,
|
||||
"detail": detail,
|
||||
"ledger": ledger,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 导出
|
||||
def _export(self, hotel_report, cfg, day, window: dict, save_dir: str, ctx) -> dict:
|
||||
"""取数 + 落两份 Excel + 存导出快照。
|
||||
|
||||
和「维护台账」拆开跑:台账是唯一会跟本机 WPS 打架的一步,它失败时导出成果
|
||||
(两份表 + 快照)已经落盘,重试只需「只维护台账」,不用重新取 20 万行余额。
|
||||
"""
|
||||
stamp = period.file_stamp(day)
|
||||
|
||||
ctx.progress(5)
|
||||
ctx.log("取会员卡余额:截至 %s" % window["end"])
|
||||
balance = hotel_report.collect.collect_member_balance(
|
||||
window["end"], cfg, window=(window["start"], window["end"]))
|
||||
bpath = hotel_report.render.write_member_balance_xlsx(
|
||||
balance, os.path.join(save_dir, "会员卡余额_%s.xlsx" % stamp))
|
||||
ctx.log("会员卡余额已导出:%d 人,卡内余额合计 %.2f → %s"
|
||||
% (balance.count, (balance.totals or {}).get("卡内余额", 0.0), bpath))
|
||||
ctx.progress(45)
|
||||
|
||||
ctx.log("取会员卡明细:%s ~ %s" % (window["start"], window["end"]))
|
||||
detail = hotel_report.collect.collect_member_detail(
|
||||
window["start"], window["end"], cfg, window=(window["start"], window["end"]))
|
||||
dpath = hotel_report.render.write_member_detail_xlsx(
|
||||
detail, os.path.join(save_dir, "会员卡明细_%s.xlsx" % stamp))
|
||||
ctx.log("会员卡明细已导出:%d 行 × %d 列 → %s"
|
||||
% (detail.count, len(detail.headers), dpath))
|
||||
ctx.progress(55)
|
||||
|
||||
files = [p for p in (bpath, dpath) if p]
|
||||
if not files:
|
||||
raise RuntimeError("没有导出任何文件:余额与明细都为空,请检查数据源")
|
||||
snapshot_store.save(day, window=window, files=files, balance=balance, detail=detail,
|
||||
sdk=str(getattr(hotel_report, "__version__", "")), log=ctx.log)
|
||||
|
||||
return {
|
||||
"files": files,
|
||||
"balance": {"count": balance.count, "totals": dict(balance.totals or {}),
|
||||
"empty": balance.count == 0},
|
||||
"detail": {"count": detail.count, "empty": detail.count == 0},
|
||||
"balance_table": balance,
|
||||
"detail_table": detail,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 台账
|
||||
def _maintain_ledger(self, hotel_report, cfg, day, path, backup: bool, recalc: bool,
|
||||
month_reset: bool, ctx) -> dict:
|
||||
def _maintain_ledger(self, hotel_report, cfg, day, path, snapshot: dict,
|
||||
backup: bool, recalc: bool, month_reset: bool, ctx) -> dict:
|
||||
from .logic.ledger import LedgerError, LedgerMaintainer
|
||||
from .logic.provider import SdkProvider
|
||||
from .logic.provider import SnapshotProvider
|
||||
|
||||
if not os.path.isfile(path):
|
||||
ctx.log("台账文件不存在,跳过维护:%s" % path, "WARN")
|
||||
@@ -205,17 +272,31 @@ class HupanStoredCardPlugin(ScenePlugin):
|
||||
maint = LedgerMaintainer(path, log=ctx.log,
|
||||
progress=lambda p: ctx.progress(55 + int(p * 0.45)),
|
||||
backup=backup, recalc=recalc, month_reset=month_reset)
|
||||
provider = SnapshotProvider(hotel_report, cfg, snapshot, log=ctx.log)
|
||||
try:
|
||||
return maint.run(day, SdkProvider(hotel_report, cfg))
|
||||
return maint.run(day, provider)
|
||||
except LedgerError as e:
|
||||
raise RuntimeError(f"台账维护失败:{e}") from e
|
||||
ctx.log(_RETRY_TIP, "WARN")
|
||||
raise RuntimeError("台账维护失败:%s" % e) from e
|
||||
except Exception: # noqa: BLE001 含 WPS 的 com_error
|
||||
ctx.log(_RETRY_TIP, "WARN")
|
||||
raise
|
||||
|
||||
|
||||
def _sub(base: float, span: float):
|
||||
"""把 SDK 的 0~100 进度映射到 [base, base+span]。"""
|
||||
def _fn(pct):
|
||||
return int(base + span * max(0, min(100, int(pct))) / 100.0)
|
||||
return _fn
|
||||
#: 台账阶段失败时的下一步提示(导出成果已经落盘,不用重导)
|
||||
_RETRY_TIP = ("台账这一步失败了,但导出成果(两份 Excel + 导出快照)已经在,"
|
||||
"把「执行方式」改成「%s」可以直接重试台账,不用重新取数/导出"
|
||||
% config.LEDGER_MODE_LEDGER_ONLY)
|
||||
|
||||
|
||||
def _table_info(table) -> dict:
|
||||
"""快照里的结果表 → 汇总用的统计(count / totals / empty)。"""
|
||||
if table is None:
|
||||
return {"count": 0, "totals": {}, "empty": True}
|
||||
count = int(getattr(table, "count", 0) or 0)
|
||||
totals = getattr(table, "totals", None)
|
||||
return {"count": count, "totals": dict(totals) if isinstance(totals, dict) else {},
|
||||
"empty": count == 0}
|
||||
|
||||
|
||||
def _ledger_summary(ledger: dict) -> str:
|
||||
|
||||
@@ -75,13 +75,82 @@ def _check_period(period) -> list:
|
||||
return problems
|
||||
|
||||
|
||||
def _check_com_retry(ledger_mod) -> str:
|
||||
"""COM 忙碌(「被呼叫方拒绝接收呼叫」)必须能识别并自动重发,其它错误必须直抛。"""
|
||||
try:
|
||||
import pywintypes
|
||||
except ImportError: # 非 Windows:没有 COM,跳过
|
||||
return ""
|
||||
|
||||
def _err(code, text):
|
||||
return pywintypes.com_error(code, text, None, None)
|
||||
|
||||
busy = _err(-2147418111, "被呼叫方拒绝接收呼叫。")
|
||||
if not ledger_mod._is_busy(busy):
|
||||
return "COM「被呼叫方拒绝接收呼叫」未被识别为可重试"
|
||||
if ledger_mod._is_busy(_err(-2147221005, "无效的类字符串")):
|
||||
return "非忙碌的 COM 错误不应重试"
|
||||
|
||||
old_delay = ledger_mod._COM_DELAY
|
||||
ledger_mod._COM_DELAY = 0.01
|
||||
try:
|
||||
calls = {"n": 0}
|
||||
|
||||
def _flaky():
|
||||
calls["n"] += 1
|
||||
if calls["n"] < 3:
|
||||
raise busy
|
||||
return "ok"
|
||||
|
||||
if ledger_mod._com_call(_flaky) != "ok" or calls["n"] != 3:
|
||||
return "COM 忙碌重试没有生效(调用了 %d 次)" % calls["n"]
|
||||
|
||||
def _fatal():
|
||||
raise _err(-2147221005, "无效的类字符串")
|
||||
|
||||
try:
|
||||
ledger_mod._com_call(_fatal)
|
||||
except pywintypes.com_error:
|
||||
pass
|
||||
else:
|
||||
return "非忙碌的 COM 错误被重试吞掉了"
|
||||
finally:
|
||||
ledger_mod._COM_DELAY = old_delay
|
||||
return ""
|
||||
|
||||
|
||||
def _check_mode(config) -> list:
|
||||
"""执行方式:新三值原样返回,v0.3.x 旧值(面板/老配置里存着)要映射过来。"""
|
||||
problems = []
|
||||
cases = {
|
||||
"导出+维护台账": "导出+维护台账",
|
||||
"只导出": "只导出",
|
||||
"只维护台账": "只维护台账",
|
||||
"导表+维护台账": "导出+维护台账",
|
||||
"只导表": "只导出",
|
||||
"": "导出+维护台账",
|
||||
"随便写的": "导出+维护台账",
|
||||
}
|
||||
for raw, want in cases.items():
|
||||
got = config.normalize_mode(raw)
|
||||
if got != want:
|
||||
problems.append("normalize_mode(%r) = %r,应为 %r" % (raw, got, want))
|
||||
return problems
|
||||
|
||||
|
||||
def _check_ledger() -> list:
|
||||
"""台账维护的纯逻辑(不碰 Excel):Excel 日期序列、待补日期窗口与数据归属日。"""
|
||||
from datetime import datetime
|
||||
|
||||
from logic import ledger as ledger_mod
|
||||
from logic.ledger import DataProvider, LedgerMaintainer, LedgerError, _time
|
||||
|
||||
problems = []
|
||||
# COM「被呼叫方拒绝接收呼叫」要能识别并自动重试(Excel/WPS 忙时整趟会白跑)
|
||||
busy = _check_com_retry(ledger_mod)
|
||||
if busy:
|
||||
problems.append(busy)
|
||||
|
||||
# 2026-11-01 的 Excel 序列是 46327(写成 pywintypes.Time 会少 8 小时,这里锁死)
|
||||
if int(_time(datetime(2026, 11, 1))) != 46327:
|
||||
problems.append(f"日期序列错误:{_time(datetime(2026, 11, 1))}")
|
||||
@@ -191,9 +260,11 @@ def main() -> int:
|
||||
return 2
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import config
|
||||
from logic import period
|
||||
|
||||
problems = _check_period(period) + _check_ledger() + _check_ledger_path()
|
||||
problems = (_check_period(period) + _check_mode(config)
|
||||
+ _check_ledger() + _check_ledger_path())
|
||||
if problems:
|
||||
print("口径异常:\n- " + "\n- ".join(problems), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -16,9 +16,27 @@ WCF_TIMEOUT = 180
|
||||
#: 留空则在界面上清掉即可关闭台账维护;也支持直接填完整文件路径
|
||||
DEFAULT_LEDGER_DIR = r"D:\资料\财务\湖畔储值卡每日导出统计"
|
||||
|
||||
#: 台账维护开关(plugin.json fields.ledger_mode.enum 与之一致)
|
||||
LEDGER_MODE_FULL = "导表+维护台账"
|
||||
LEDGER_MODE_EXPORT_ONLY = "只导表"
|
||||
#: 执行方式(plugin.json fields.ledger_mode.enum 与之一致)。分两步是为了「表维护失败不用重导」:
|
||||
#: 导出+维护台账 = 一次跑完(默认)
|
||||
#: 只导出 = 只取数、落两份 Excel,并留下快照(不动台账)
|
||||
#: 只维护台账 = 复用上一次导出留下的快照,只跑 WPS 台账维护(不取数、不重写两份表)
|
||||
LEDGER_MODE_FULL = "导出+维护台账"
|
||||
LEDGER_MODE_EXPORT_ONLY = "只导出"
|
||||
LEDGER_MODE_LEDGER_ONLY = "只维护台账"
|
||||
#: v0.3.x 的旧值(老方案/老配置里存的是这些字面量)
|
||||
_LEDGER_MODE_ALIASES = {
|
||||
"导表+维护台账": LEDGER_MODE_FULL,
|
||||
"只导表": LEDGER_MODE_EXPORT_ONLY,
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
return text
|
||||
return LEDGER_MODE_FULL
|
||||
|
||||
#: 台账备份开关
|
||||
BACKUP_ON = "先备份"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""会员卡统计台账维护(Excel / WPS COM)。
|
||||
"""会员卡统计台账维护(**只连 WPS 表格 COM,不调用 Microsoft Excel**)。
|
||||
|
||||
台账 `2026年11月会员卡统计-模版调整-新会员卡.xlsx` 有 5 个要维护的 sheet:
|
||||
|
||||
@@ -27,12 +27,15 @@ import calendar
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
try: # 仅 Windows;导入失败时在 run() 里给可读错误
|
||||
import pywintypes
|
||||
import win32com.client as win32
|
||||
except ImportError: # pragma: no cover
|
||||
win32 = None
|
||||
pywintypes = None
|
||||
|
||||
SHIFT = "交班时间"
|
||||
BALANCE = "会员卡余额"
|
||||
@@ -58,6 +61,133 @@ DETAIL_FORMULA_FIRST, DETAIL_FORMULA_LAST = 55, 75
|
||||
NEWCARD_COLS = 26
|
||||
|
||||
|
||||
#: COM「服务器忙」类 HRESULT。这类错误表示调用**没有被执行**,等对方空闲后重发安全:
|
||||
#: -2147418111 RPC_E_CALL_REJECTED 被呼叫方拒绝接收呼叫
|
||||
#: -2147417846 RPC_E_SERVERCALL_RETRYLATER 服务器忙,请稍后重试
|
||||
#: -2147417845 RPC_E_SERVERCALL_REJECTED
|
||||
#: -2147417848 RPC_E_DISCONNECTED
|
||||
#: -2147220991 CO_E_OBJNOTCONNECTED
|
||||
_COM_BUSY_CODES = (-2147418111, -2147417846, -2147417845, -2147417848, -2147220991)
|
||||
#: 单个 COM 调用的重试上限(次)与间隔(秒):Excel/WPS 加载 30MB 台账要 20 秒以上
|
||||
_COM_RETRY = 300
|
||||
_COM_DELAY = 1.0
|
||||
|
||||
_log_hook = lambda msg, level="INFO": None
|
||||
|
||||
|
||||
def set_log_hook(fn) -> None:
|
||||
"""让 COM 重试过程也能写进插件日志(由 LedgerMaintainer 注入 ctx.log)。"""
|
||||
global _log_hook
|
||||
_log_hook = fn or (lambda msg, level="INFO": None)
|
||||
|
||||
|
||||
def _com_text(e) -> str:
|
||||
"""com_error → 「被呼叫方拒绝接收呼叫」这类可读文字。"""
|
||||
args = getattr(e, "args", ()) or ()
|
||||
return str(args[1]) if len(args) > 1 and args[1] else str(e)
|
||||
|
||||
|
||||
def _hresult(e) -> int:
|
||||
"""取 com_error 的 HRESULT(统一成无符号 32 位)。"""
|
||||
code = getattr(e, "hresult", None)
|
||||
if code is None:
|
||||
args = getattr(e, "args", ()) or ()
|
||||
code = args[0] if args else 0
|
||||
try:
|
||||
return int(code) & 0xFFFFFFFF
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _is_busy(e) -> bool:
|
||||
"""是不是「服务器忙 → 拒绝接收呼叫」这一类(可安全重试的)错误。"""
|
||||
busy = {c & 0xFFFFFFFF for c in _COM_BUSY_CODES}
|
||||
return _hresult(e) in busy
|
||||
|
||||
|
||||
def _com_call(fn, *args, **kwargs):
|
||||
"""执行一次 COM 调用;「被呼叫方拒绝接收呼叫」时等它空闲再重发。
|
||||
|
||||
为什么必须有:Excel/WPS 打开 31MB / 20 万行 + 4 张图表的台账、整簿重算、或被安全
|
||||
软件扫描期间,会把这期间进来的 COM 请求直接打回(`pywintypes.com_error
|
||||
-2147418111 被呼叫方拒绝接收呼叫`)。`Workbooks.Open` 返回**不代表**工作簿可用,
|
||||
紧随其后的 `Worksheets(...)` 就经常被拒;原来的实现一遇到就整趟白跑(备份都做完
|
||||
了、台账却没动)。这类错误表示调用没有执行,重发不会写重数据。
|
||||
|
||||
`fn` 用零参可调用对象(lambda/闭包)传参,保证重试时整条调用链重新解析一次。
|
||||
"""
|
||||
if pywintypes is None:
|
||||
return fn(*args, **kwargs)
|
||||
for i in range(_COM_RETRY):
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except pywintypes.com_error as e:
|
||||
if not _is_busy(e) or i >= _COM_RETRY - 1:
|
||||
raise
|
||||
if i == 0:
|
||||
_log_hook("Excel/WPS 忙(%s),等它空闲后重试(最长 %d 秒)"
|
||||
% (_com_text(e), _COM_RETRY))
|
||||
time.sleep(_COM_DELAY)
|
||||
|
||||
|
||||
def _sheet(wb, name: str):
|
||||
"""取 sheet:Open 之后最先被打回的调用就是它。"""
|
||||
return _com_call(lambda: wb.Worksheets(name))
|
||||
|
||||
|
||||
def _last_row(ws, col: int) -> int:
|
||||
"""某列最后一个非空行号(End(xlUp))。"""
|
||||
return int(_com_call(lambda: ws.Cells(ws.Rows.Count, col).End(XL_UP).Row))
|
||||
|
||||
|
||||
def _cell(ws, row: int, col: int):
|
||||
"""读单元格值。"""
|
||||
return _com_call(lambda: ws.Cells(row, col).Value)
|
||||
|
||||
|
||||
def _put(ws, row: int, col: int, value) -> None:
|
||||
"""写单元格值。"""
|
||||
def _do():
|
||||
ws.Cells(row, col).Value = value
|
||||
_com_call(_do)
|
||||
|
||||
|
||||
#: WPS 表格(ET)的 COM ProgID。**只用 WPS**:`Excel.Application` 在装了 Office 的机器上
|
||||
#: 会拉起 Microsoft Excel(还会跟用户自己开着的 Excel 抢同一份台账/弹窗),而本插件只在
|
||||
#: WPS 上验证过;所以这里绝不回退到 Excel 的 ProgID。
|
||||
WPS_PROGIDS = ("Ket.Application", "KET.Application")
|
||||
#: WPS 安装目录特征,用来确认这个 ProgID 没被别的办公软件接管
|
||||
WPS_PATH_HINTS = ("kingsoft", "wps")
|
||||
|
||||
|
||||
def _dispatch_wps():
|
||||
"""只启动 WPS 表格实例(不碰 Microsoft Excel),返回 (app, progid, path)。"""
|
||||
problems = []
|
||||
for prog in WPS_PROGIDS:
|
||||
try:
|
||||
app = _com_call(lambda prog=prog: win32.DispatchEx(prog))
|
||||
except Exception as e: # noqa: BLE001
|
||||
problems.append("%s → %s" % (prog, _com_text(e)))
|
||||
continue
|
||||
try:
|
||||
path = str(_com_call(getattr, app, "Path") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
path = ""
|
||||
low = path.lower().replace("\\", "/")
|
||||
if path and not any(h in low for h in WPS_PATH_HINTS):
|
||||
try: # ProgID 被别的办公软件占用:关掉再用下一个
|
||||
_com_call(lambda: app.Quit())
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
problems.append("%s → 指向 %s(不是 WPS)" % (prog, path))
|
||||
continue
|
||||
return app, prog, path
|
||||
raise LedgerError(
|
||||
"没有找到可用的 WPS 表格 COM 接口(本插件只用 WPS,不调用 Office):%s。"
|
||||
"请在执行机上装好 WPS Office(能用它正常打开 xlsx),再重跑"
|
||||
% ";".join(problems))
|
||||
|
||||
|
||||
class LedgerError(RuntimeError):
|
||||
"""台账维护失败(文件被占用 / 结构不符 / 当日未交班等)。"""
|
||||
|
||||
@@ -123,7 +253,9 @@ def _num(v):
|
||||
def _as_text_columns(ws, start_row: int, n: int, cols) -> None:
|
||||
"""把编码类列强制成文本,避免 `00000001` 被 Excel 吃掉前导零、手机号变科学计数。"""
|
||||
for c in cols:
|
||||
ws.Range(ws.Cells(start_row, c), ws.Cells(start_row + n - 1, c)).NumberFormat = "@"
|
||||
def _do(c=c):
|
||||
ws.Range(ws.Cells(start_row, c), ws.Cells(start_row + n - 1, c)).NumberFormat = "@"
|
||||
_com_call(_do)
|
||||
|
||||
|
||||
def _copy_number_formats(ws, src_row: int, start_row: int, n: int,
|
||||
@@ -134,9 +266,13 @@ def _copy_number_formats(ws, src_row: int, start_row: int, n: int,
|
||||
交班时间/明细时间看起来就不对了。逐列复制 NumberFormat 比 Copy/Paste 稳(不占剪贴板)。
|
||||
"""
|
||||
for c in range(first_col, last_col + 1):
|
||||
fmt = ws.Cells(src_row, c).NumberFormat
|
||||
ws.Range(ws.Cells(start_row, c),
|
||||
ws.Cells(start_row + n - 1, c)).NumberFormat = fmt
|
||||
fmt = _com_call(lambda c=c: ws.Cells(src_row, c).NumberFormat)
|
||||
|
||||
def _do(c=c, fmt=fmt):
|
||||
ws.Range(ws.Cells(start_row, c),
|
||||
ws.Cells(start_row + n - 1, c)).NumberFormat = fmt
|
||||
|
||||
_com_call(_do)
|
||||
|
||||
|
||||
class DataProvider:
|
||||
@@ -163,11 +299,12 @@ class LedgerMaintainer:
|
||||
self.backup = backup
|
||||
self.recalc = recalc
|
||||
self.month_reset = month_reset
|
||||
set_log_hook(self.log) # COM 重试/等待也走插件日志
|
||||
|
||||
# ------------------------------------------------------------ 入口
|
||||
def run(self, day: date, provider: DataProvider) -> dict:
|
||||
if win32 is None:
|
||||
raise LedgerError("缺少 pywin32(win32com),无法用 Excel/WPS 维护台账")
|
||||
raise LedgerError("缺少 pywin32(win32com),无法用 WPS 维护台账")
|
||||
if not os.path.isfile(self.path):
|
||||
raise LedgerError("台账文件不存在:%s" % self.path)
|
||||
|
||||
@@ -180,26 +317,28 @@ class LedgerMaintainer:
|
||||
self.log("备份台账 → %s" % backup_path)
|
||||
shutil.copy2(self.path, backup_path)
|
||||
|
||||
app = win32.DispatchEx("Excel.Application")
|
||||
app, progid, app_path = _dispatch_wps()
|
||||
self.log("表格引擎:WPS(%s)%s" % (progid, (" " + app_path) if app_path else ""))
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
try:
|
||||
app.AskToUpdateLinks = False
|
||||
except Exception: # noqa: BLE001 WPS 可能不支持
|
||||
pass
|
||||
try:
|
||||
app.Calculation = XL_CALC_MANUAL
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
for name, value in (("AskToUpdateLinks", False), ("EnableEvents", False),
|
||||
("ScreenUpdating", False), ("Calculation", XL_CALC_MANUAL)):
|
||||
try: # WPS 个别版本不支持其中某项
|
||||
setattr(app, name, value)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
wb = None
|
||||
try:
|
||||
self.log("打开台账(约 20 秒):%s" % self.path)
|
||||
try:
|
||||
wb = app.Workbooks.Open(self.path, UpdateLinks=0)
|
||||
wb = _com_call(lambda: app.Workbooks.Open(self.path, UpdateLinks=0))
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise LedgerError(
|
||||
"打开台账失败(文件被 Excel 打开占用?请先关闭):%s" % e) from e
|
||||
"打开台账失败(文件被 Excel 打开占用?请先关闭):%s" % _com_text(e)) from e
|
||||
|
||||
# Open 返回 ≠ 可用:31MB / 20 万行的台账还在装配,这段时间的调用会被打回
|
||||
self._wait_ready(wb)
|
||||
|
||||
state = self._read_state(wb)
|
||||
self.log("台账现状:交班时间最后 %s(r%d)、明细最后 r%d、新办卡最后 r%d"
|
||||
@@ -232,39 +371,57 @@ class LedgerMaintainer:
|
||||
self.progress(95)
|
||||
|
||||
self.log("保存台账…")
|
||||
wb.Save()
|
||||
_com_call(lambda: wb.Save())
|
||||
return {"path": self.path, "backup": backup_path, "days": [d["day"] for d in days],
|
||||
"detail_rows": sum(d["rows"] for d in detail), "new_cards": cards["count"],
|
||||
"balance_rows": bal["count"], "balance_total": bal["total"],
|
||||
"checks": checks, "reset": reset}
|
||||
finally:
|
||||
try:
|
||||
if wb is not None:
|
||||
wb.Close(SaveChanges=False)
|
||||
finally:
|
||||
# 收尾也要重试,且**不能**把原始异常盖掉:Excel 忙时 Close/Quit 同样会
|
||||
# 「被呼叫方拒绝接收呼叫」,以前这里一抛,真正的原因就永远看不到了
|
||||
if wb is not None:
|
||||
try:
|
||||
app.Calculation = XL_CALC_AUTO
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
app.Quit()
|
||||
_com_call(lambda: wb.Close(SaveChanges=False))
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.log("关闭台账失败(忽略):%s" % _com_text(e), "WARN")
|
||||
try:
|
||||
app.Calculation = XL_CALC_AUTO
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
_com_call(lambda: app.Quit())
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.log("退出 Excel/WPS 失败(可能残留进程,需手工清理):%s"
|
||||
% _com_text(e), "WARN")
|
||||
|
||||
def _wait_ready(self, wb) -> None:
|
||||
"""等 Excel/WPS 把工作簿装配完(`Workbooks.Open` 返回不代表可用)。
|
||||
|
||||
探最便宜的一个属性,通了再往下走;探的过程本身就是 `_com_call` 的重试。
|
||||
"""
|
||||
t0 = time.time()
|
||||
_com_call(getattr, wb, "Name")
|
||||
cost = time.time() - t0
|
||||
if cost >= 2:
|
||||
self.log("台账已就绪(Open 之后又等了 %.0f 秒)" % cost)
|
||||
|
||||
# ------------------------------------------------------------ 读现状
|
||||
def _read_state(self, wb) -> dict:
|
||||
ws_shift = wb.Worksheets(SHIFT)
|
||||
shift_row = int(ws_shift.Cells(ws_shift.Rows.Count, 2).End(XL_UP).Row)
|
||||
shift_day = _as_date(ws_shift.Cells(shift_row, 7).Value) # G=今日日期
|
||||
ws_shift = _sheet(wb, SHIFT)
|
||||
shift_row = _last_row(ws_shift, 2)
|
||||
shift_day = _as_date(_cell(ws_shift, shift_row, 7)) # G=今日日期
|
||||
if shift_day is None:
|
||||
raise LedgerError("「%s」r%d 的 G 列不是日期,模板结构不符" % (SHIFT, shift_row))
|
||||
|
||||
ws_detail = wb.Worksheets(DETAIL)
|
||||
detail_row = int(ws_detail.Cells(ws_detail.Rows.Count, 2).End(XL_UP).Row)
|
||||
ws_detail = _sheet(wb, DETAIL)
|
||||
detail_row = _last_row(ws_detail, 2)
|
||||
|
||||
ws_card = wb.Worksheets(NEWCARD)
|
||||
newcard_row = int(ws_card.Cells(ws_card.Rows.Count, 2).End(XL_UP).Row)
|
||||
ws_card = _sheet(wb, NEWCARD)
|
||||
newcard_row = _last_row(ws_card, 2)
|
||||
|
||||
ws_bal = wb.Worksheets(BALANCE)
|
||||
bal_last = int(ws_bal.Cells(ws_bal.Rows.Count, 2).End(XL_UP).Row)
|
||||
bal_total_row = bal_last if str(ws_bal.Cells(bal_last, 2).Value or "").strip() == "合计" else 0
|
||||
ws_bal = _sheet(wb, BALANCE)
|
||||
bal_last = _last_row(ws_bal, 2)
|
||||
bal_total_row = bal_last if str(_cell(ws_bal, bal_last, 2) or "").strip() == "合计" else 0
|
||||
bal_data_last = (bal_total_row - 1) if bal_total_row else bal_last
|
||||
|
||||
return {"shift_row": shift_row, "shift_day": shift_day,
|
||||
@@ -278,15 +435,14 @@ class LedgerMaintainer:
|
||||
|
||||
def _ensure_title(self, wb, day: date) -> None:
|
||||
"""汇总表标题(如「26年10月份会员统计」)跟着营业日所在月份走。"""
|
||||
ws = wb.Worksheets(SUMMARY)
|
||||
cell = ws.Cells(1, 2)
|
||||
title = str(cell.Value or "")
|
||||
ws = _sheet(wb, SUMMARY)
|
||||
title = str(_cell(ws, 1, 2) or "")
|
||||
if not title:
|
||||
return
|
||||
new = re.sub(r"\d{1,2}月份", "%d月份" % day.month, title)
|
||||
new = re.sub(r"\d{2,4}年(?=\d{1,2}月份)", "%d年" % (day.year % 100), new)
|
||||
if new != title:
|
||||
cell.Value = new
|
||||
_put(ws, 1, 2, new)
|
||||
self.log("汇总标题已更新:%s → %s" % (title, new))
|
||||
|
||||
def _maybe_reset_month(self, app, wb, day: date) -> dict | None:
|
||||
@@ -297,10 +453,10 @@ class LedgerMaintainer:
|
||||
- 期初行 r4 抄上月末(汇总行)的累计值;
|
||||
- 「交班时间」「公众号」「会员卡余额」不动(交班历史是明细 LOOKUP 的起点)。
|
||||
"""
|
||||
ws = wb.Worksheets(SUMMARY)
|
||||
ws = _sheet(wb, SUMMARY)
|
||||
months, total_row = set(), 0
|
||||
for r in range(4, 45):
|
||||
v = ws.Cells(r, 2).Value
|
||||
v = _cell(ws, r, 2)
|
||||
if str(v or "").strip() == "汇总":
|
||||
total_row = r
|
||||
continue
|
||||
@@ -319,35 +475,38 @@ class LedgerMaintainer:
|
||||
init = {}
|
||||
if total_row:
|
||||
for col, name in self.INIT_COLUMNS:
|
||||
init[name] = _num(ws.Cells(total_row, col).Value)
|
||||
init[name] = _num(_cell(ws, total_row, col))
|
||||
|
||||
days_in_month = calendar.monthrange(day.year, day.month)[1]
|
||||
for i in range(31):
|
||||
r = 5 + i
|
||||
if i < days_in_month:
|
||||
ws.Cells(r, 1).Value = i + 1
|
||||
ws.Cells(r, 2).Value = _time(datetime(day.year, day.month, i + 1))
|
||||
_put(ws, r, 1, i + 1)
|
||||
_put(ws, r, 2, _time(datetime(day.year, day.month, i + 1)))
|
||||
else:
|
||||
ws.Cells(r, 1).ClearContents()
|
||||
ws.Cells(r, 2).ClearContents()
|
||||
ws.Range("AU5:AV35").ClearContents() # 营业日报实收/消费(人工填)
|
||||
ws.Range("AZ5:AZ35").ClearContents() # 调整备注
|
||||
_com_call(lambda r=r: ws.Cells(r, 1).ClearContents())
|
||||
_com_call(lambda r=r: ws.Cells(r, 2).ClearContents())
|
||||
_com_call(lambda: ws.Range("AU5:AV35").ClearContents()) # 营业日报实收/消费(人工填)
|
||||
_com_call(lambda: ws.Range("AZ5:AZ35").ClearContents()) # 调整备注
|
||||
for col, name in self.INIT_COLUMNS:
|
||||
if name in init:
|
||||
ws.Cells(4, col).Value = init[name]
|
||||
_put(ws, 4, col, init[name])
|
||||
|
||||
detail = wb.Worksheets(DETAIL)
|
||||
last = int(detail.Cells(detail.Rows.Count, 2).End(XL_UP).Row)
|
||||
detail = _sheet(wb, DETAIL)
|
||||
last = _last_row(detail, 2)
|
||||
cleared = max(0, last - 2)
|
||||
if cleared:
|
||||
detail.Range(detail.Cells(3, 2), detail.Cells(last, 33)).ClearContents() # B~AG
|
||||
detail.Range(detail.Cells(3, 34), detail.Cells(last, 52)).ClearContents() # AH~AZ
|
||||
_com_call(lambda: detail.Range(detail.Cells(3, 2),
|
||||
detail.Cells(last, 33)).ClearContents()) # B~AG
|
||||
_com_call(lambda: detail.Range(detail.Cells(3, 34),
|
||||
detail.Cells(last, 52)).ClearContents()) # AH~AZ
|
||||
|
||||
card = wb.Worksheets(NEWCARD)
|
||||
last = int(card.Cells(card.Rows.Count, 2).End(XL_UP).Row)
|
||||
card = _sheet(wb, NEWCARD)
|
||||
last = _last_row(card, 2)
|
||||
nc_cleared = max(0, last - 2)
|
||||
if nc_cleared:
|
||||
card.Range(card.Cells(3, 1), card.Cells(last, NEWCARD_COLS)).ClearContents()
|
||||
_com_call(lambda: card.Range(card.Cells(3, 1),
|
||||
card.Cells(last, NEWCARD_COLS)).ClearContents())
|
||||
|
||||
self.log("切月完成:清明细 %d 行、清新办卡 %d 行、日期行 %s-01~%s-%02d、期初 %s"
|
||||
% (cleared, nc_cleared, day.strftime("%Y-%m"), day.strftime("%Y-%m"),
|
||||
@@ -400,25 +559,25 @@ class LedgerMaintainer:
|
||||
|
||||
# ------------------------------------------------------------ 交班时间
|
||||
def _write_shift(self, wb, state: dict, days: list) -> None:
|
||||
ws = wb.Worksheets(SHIFT)
|
||||
ws = _sheet(wb, SHIFT)
|
||||
r = state["shift_row"]
|
||||
for item in days:
|
||||
r += 1
|
||||
prev_day = item["day"] - timedelta(days=1)
|
||||
_copy_number_formats(ws, r - 1, r, 1, 2, 7)
|
||||
ws.Cells(r, 2).Value = _time(datetime.combine(prev_day, datetime.min.time()))
|
||||
ws.Cells(r, 3).Value = _time(_as_datetime(item["start"]))
|
||||
ws.Cells(r, 4).Value = _time(_as_datetime(item["end"]))
|
||||
ws.Cells(r, 5).Formula = "=C%d*1" % r
|
||||
ws.Cells(r, 6).Formula = "=D%d*1" % r
|
||||
ws.Cells(r, 7).Value = _time(datetime.combine(item["day"], datetime.min.time()))
|
||||
_put(ws, r, 2, _time(datetime.combine(prev_day, datetime.min.time())))
|
||||
_put(ws, r, 3, _time(_as_datetime(item["start"])))
|
||||
_put(ws, r, 4, _time(_as_datetime(item["end"])))
|
||||
_com_call(lambda r=r: setattr(ws.Cells(r, 5), "Formula", "=C%d*1" % r))
|
||||
_com_call(lambda r=r: setattr(ws.Cells(r, 6), "Formula", "=D%d*1" % r))
|
||||
_put(ws, r, 7, _time(datetime.combine(item["day"], datetime.min.time())))
|
||||
if days:
|
||||
self.log("交班时间已追加 %d 行(r%d~r%d)"
|
||||
% (len(days), state["shift_row"] + 1, r))
|
||||
|
||||
# ------------------------------------------------------------ 明细
|
||||
def _append_detail(self, wb, state: dict, days: list, provider: DataProvider) -> list:
|
||||
ws = wb.Worksheets(DETAIL)
|
||||
ws = _sheet(wb, DETAIL)
|
||||
pay_cols = self._pay_columns(ws)
|
||||
row = state["detail_row"]
|
||||
out = []
|
||||
@@ -454,7 +613,11 @@ class LedgerMaintainer:
|
||||
_copy_number_formats(ws, start_row - 1, start_row, n, 2, PAY_LAST_COL)
|
||||
# C=会员编号、F=手机号保持文本;B/AD=发生时间/入会时间模板里也是文本(BC/BD 用 =B*1)
|
||||
_as_text_columns(ws, start_row, n, (2, 3, 6, 30))
|
||||
ws.Range(ws.Cells(start_row, 2), ws.Cells(start_row + n - 1, PAY_LAST_COL)).Value = values
|
||||
def _write_block(start_row=start_row, n=n, values=values):
|
||||
ws.Range(ws.Cells(start_row, 2),
|
||||
ws.Cells(start_row + n - 1, PAY_LAST_COL)).Value = values
|
||||
|
||||
_com_call(_write_block)
|
||||
self._fill_formulas(ws, start_row, n, 1, 1) # A 列
|
||||
self._fill_formulas(ws, start_row, n,
|
||||
DETAIL_FORMULA_FIRST, DETAIL_FORMULA_LAST) # BC~BW
|
||||
@@ -474,7 +637,7 @@ class LedgerMaintainer:
|
||||
"""模板 AH~AZ 的支付方式列名 → 列号。"""
|
||||
out = {}
|
||||
for c in range(PAY_FIRST_COL, PAY_LAST_COL + 1):
|
||||
name = str(ws.Cells(2, c).Value or "").strip()
|
||||
name = str(_cell(ws, 2, c) or "").strip()
|
||||
if name:
|
||||
out[name] = c
|
||||
return out
|
||||
@@ -489,22 +652,26 @@ class LedgerMaintainer:
|
||||
不判就会把表头文字(如「交班时间1」)当公式写进数据行。
|
||||
"""
|
||||
for c in range(first_col, last_col + 1):
|
||||
src_cell = ws.Cells(start_row - 1, c)
|
||||
try:
|
||||
if not src_cell.HasFormula:
|
||||
continue
|
||||
has = bool(_com_call(lambda c=c: ws.Cells(start_row - 1, c).HasFormula))
|
||||
except Exception: # noqa: BLE001 WPS 个别版本没有该属性
|
||||
if not str(src_cell.Formula or "").startswith("="):
|
||||
continue
|
||||
src = src_cell.FormulaR1C1
|
||||
has = str(_com_call(lambda c=c: ws.Cells(start_row - 1, c).Formula)
|
||||
or "").startswith("=")
|
||||
if not has:
|
||||
continue
|
||||
src = _com_call(lambda c=c: ws.Cells(start_row - 1, c).FormulaR1C1)
|
||||
if not src:
|
||||
continue
|
||||
ws.Range(ws.Cells(start_row, c),
|
||||
ws.Cells(start_row + n - 1, c)).FormulaR1C1 = src
|
||||
|
||||
def _do(c=c, src=src):
|
||||
ws.Range(ws.Cells(start_row, c),
|
||||
ws.Cells(start_row + n - 1, c)).FormulaR1C1 = src
|
||||
|
||||
_com_call(_do)
|
||||
|
||||
# ------------------------------------------------------------ 新办卡
|
||||
def _append_newcard(self, wb, state: dict, days: list, detail: list) -> dict:
|
||||
ws = wb.Worksheets(NEWCARD)
|
||||
ws = _sheet(wb, NEWCARD)
|
||||
row = state["newcard_row"]
|
||||
count = 0
|
||||
|
||||
@@ -522,8 +689,11 @@ class LedgerMaintainer:
|
||||
values.append(tuple(cells))
|
||||
_copy_number_formats(ws, start_row - 1, start_row, len(values), 1, NEWCARD_COLS)
|
||||
_as_text_columns(ws, start_row, len(values), (2, 3, 6)) # B=入会时间(文本)、C/F=编号/手机
|
||||
ws.Range(ws.Cells(start_row, 1), ws.Cells(start_row + len(values) - 1,
|
||||
NEWCARD_COLS)).Value = values
|
||||
def _write_block(start_row=start_row, values=values):
|
||||
ws.Range(ws.Cells(start_row, 1),
|
||||
ws.Cells(start_row + len(values) - 1, NEWCARD_COLS)).Value = values
|
||||
|
||||
_com_call(_write_block)
|
||||
self._fill_formulas(ws, start_row, len(values), NEWCARD_COLS + 1, NEWCARD_COLS + 1)
|
||||
row += len(values)
|
||||
count += len(values)
|
||||
@@ -532,7 +702,7 @@ class LedgerMaintainer:
|
||||
|
||||
# ------------------------------------------------------------ 余额
|
||||
def _write_balance(self, wb, day: date, provider: DataProvider) -> dict:
|
||||
ws = wb.Worksheets(BALANCE)
|
||||
ws = _sheet(wb, BALANCE)
|
||||
end = self._latest_end(provider, day)
|
||||
start = provider.latest_shift(day - timedelta(days=1)) or \
|
||||
("%s 00:00:00" % (day - timedelta(days=1)))
|
||||
@@ -543,16 +713,16 @@ class LedgerMaintainer:
|
||||
pass
|
||||
n = table.count
|
||||
|
||||
ws_bal_last = int(ws.Cells(ws.Rows.Count, 2).End(XL_UP).Row)
|
||||
total_row = ws_bal_last if str(ws.Cells(ws_bal_last, 2).Value or "").strip() == "合计" else 0
|
||||
ws_bal_last = _last_row(ws, 2)
|
||||
total_row = ws_bal_last if str(_cell(ws, ws_bal_last, 2) or "").strip() == "合计" else 0
|
||||
data_last = (total_row - 1) if total_row else ws_bal_last
|
||||
old_n = max(0, data_last - BALANCE_FIRST + 1)
|
||||
delta = n - old_n
|
||||
|
||||
if delta > 0:
|
||||
ws.Rows("%d:%d" % (data_last + 1, data_last + delta)).Insert()
|
||||
_com_call(lambda: ws.Rows("%d:%d" % (data_last + 1, data_last + delta)).Insert())
|
||||
elif delta < 0:
|
||||
ws.Rows("%d:%d" % (BALANCE_FIRST + n, data_last)).Delete()
|
||||
_com_call(lambda: ws.Rows("%d:%d" % (BALANCE_FIRST + n, data_last)).Delete())
|
||||
|
||||
end_row = BALANCE_FIRST + n - 1
|
||||
values = []
|
||||
@@ -564,30 +734,38 @@ class LedgerMaintainer:
|
||||
if values:
|
||||
_copy_number_formats(ws, BALANCE_FIRST, BALANCE_FIRST, n, 2, 20)
|
||||
_as_text_columns(ws, BALANCE_FIRST, n, (2,)) # B=会员卡号(保住前导零)
|
||||
ws.Range(ws.Cells(BALANCE_FIRST, 2),
|
||||
ws.Cells(end_row, 1 + BALANCE_COLS)).Value = values
|
||||
|
||||
def _write_block(values=values, end_row=end_row):
|
||||
ws.Range(ws.Cells(BALANCE_FIRST, 2),
|
||||
ws.Cells(end_row, 1 + BALANCE_COLS)).Value = values
|
||||
|
||||
_com_call(_write_block)
|
||||
|
||||
# 公式列 L~T:以第一行数据的公式为模板整列填充(R1C1,保证逐行相对引用)
|
||||
for c in range(12, 21):
|
||||
src_cell = ws.Cells(BALANCE_FIRST, c)
|
||||
try:
|
||||
has = bool(src_cell.HasFormula)
|
||||
has = bool(_com_call(lambda c=c: ws.Cells(BALANCE_FIRST, c).HasFormula))
|
||||
except Exception: # noqa: BLE001
|
||||
has = str(src_cell.Formula or "").startswith("=")
|
||||
has = str(_com_call(lambda c=c: ws.Cells(BALANCE_FIRST, c).Formula)
|
||||
or "").startswith("=")
|
||||
if not has:
|
||||
continue
|
||||
ws.Range(ws.Cells(BALANCE_FIRST, c),
|
||||
ws.Cells(end_row, c)).FormulaR1C1 = src_cell.FormulaR1C1
|
||||
src = _com_call(lambda c=c: ws.Cells(BALANCE_FIRST, c).FormulaR1C1)
|
||||
|
||||
def _fill(c=c, src=src):
|
||||
ws.Range(ws.Cells(BALANCE_FIRST, c),
|
||||
ws.Cells(end_row, c)).FormulaR1C1 = src
|
||||
|
||||
_com_call(_fill)
|
||||
|
||||
# 合计行
|
||||
tr = end_row + 1
|
||||
totals = table.totals or {}
|
||||
ws.Cells(tr, 2).Value = "合计"
|
||||
ws.Cells(tr, 4).Value = totals.get("实收余额", 0.0)
|
||||
ws.Cells(tr, 5).Value = totals.get("折扣余额", 0.0)
|
||||
ws.Cells(tr, 6).Value = totals.get("卡内余额", 0.0)
|
||||
ws.Cells(2, 2).Value = " 开始:%s 结束:%s" % (table.window[0] if table.window else "",
|
||||
end)
|
||||
_put(ws, tr, 2, "合计")
|
||||
_put(ws, tr, 4, totals.get("实收余额", 0.0))
|
||||
_put(ws, tr, 5, totals.get("折扣余额", 0.0))
|
||||
_put(ws, tr, 6, totals.get("卡内余额", 0.0))
|
||||
_put(ws, 2, 2, " 开始:%s 结束:%s" % (table.window[0] if table.window else "", end))
|
||||
self.log("会员卡余额已覆盖:%d 人(r4~r%d,合计行 r%d,卡内合计 %.2f)"
|
||||
% (n, end_row, tr, totals.get("卡内余额", 0.0)))
|
||||
return {"count": n, "total": totals.get("卡内余额", 0.0), "end": end}
|
||||
@@ -598,15 +776,16 @@ class LedgerMaintainer:
|
||||
app.Calculation = XL_CALC_AUTO
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 重算要算 20 万行公式,期间 Excel 会忙到拒绝外部调用 —— 所以每次都走 _com_call
|
||||
for fn in ("CalculateFull", "CalculateFullRebuild", "Calculate"):
|
||||
try:
|
||||
getattr(app, fn)()
|
||||
_com_call(lambda fn=fn: getattr(app, fn)())
|
||||
return
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
for name in (SHIFT, BALANCE, DETAIL, NEWCARD, SUMMARY):
|
||||
try:
|
||||
wb.Worksheets(name).Calculate()
|
||||
_com_call(lambda name=name: _sheet(wb, name).Calculate())
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
@@ -618,10 +797,11 @@ class LedgerMaintainer:
|
||||
|
||||
# ------------------------------------------------------------ 核对
|
||||
def _check(self, wb, day: date, detail: list, cards: dict, bal: dict) -> list:
|
||||
ws = wb.Worksheets(SUMMARY)
|
||||
ws = _sheet(wb, SUMMARY)
|
||||
row_of = {}
|
||||
for r in range(5, int(ws.UsedRange.Rows.Count) + 1):
|
||||
d = _as_date(ws.Cells(r, 2).Value)
|
||||
used = int(_com_call(lambda: ws.UsedRange.Rows.Count))
|
||||
for r in range(5, used + 1):
|
||||
d = _as_date(_cell(ws, r, 2))
|
||||
if d is not None:
|
||||
row_of[d] = r
|
||||
results = []
|
||||
@@ -651,16 +831,16 @@ class LedgerMaintainer:
|
||||
"「%s」没有 %s 的行(需先切到当月),本次跳过明细核对" % (SUMMARY, label))
|
||||
elif today is not None:
|
||||
# 当天充值/实收:明细 H/I 合计 vs 汇总 M/N(SUMIFS 结果)
|
||||
add("当天充值", today["h"], _num(ws.Cells(r, 13).Value), note="汇总!M%d" % r)
|
||||
add("当天实收", today["i"], _num(ws.Cells(r, 14).Value), note="汇总!N%d" % r)
|
||||
add("当天充值", today["h"], _num(_cell(ws, r, 13)), note="汇总!M%d" % r)
|
||||
add("当天实收", today["i"], _num(_cell(ws, r, 14)), note="汇总!N%d" % r)
|
||||
# 累计会员 = 新办 + 前一天
|
||||
prev = ws.Cells(r - 1, 10).Value if r > 5 else ws.Cells(4, 10).Value
|
||||
prev = _cell(ws, r - 1, 10) if r > 5 else _cell(ws, 4, 10)
|
||||
expect = _num(prev) + today["new"]
|
||||
add("累计会员(=新办+前一天)", expect, _num(ws.Cells(r, 10).Value),
|
||||
note="J%d" % r)
|
||||
add("累计会员(=新办+前一天)", expect, _num(_cell(ws, r, 10)), note="J%d" % r)
|
||||
|
||||
# AS36(期末余额)vs AS37(余额表合计 MAX(F:F))
|
||||
as36, as37 = _num(ws.Range("AS36").Value), _num(ws.Range("AS37").Value)
|
||||
as36 = _num(_com_call(lambda: ws.Range("AS36").Value))
|
||||
as37 = _num(_com_call(lambda: ws.Range("AS37").Value))
|
||||
add("AS36 与 AS37", as36, as37, note="期末余额 vs 余额表合计")
|
||||
add("余额表合计", bal["total"], as37, note="本次导出 F 列合计 vs AS37")
|
||||
return results
|
||||
|
||||
@@ -7,6 +7,11 @@ from datetime import date
|
||||
from .ledger import DataProvider
|
||||
|
||||
|
||||
def _norm_ts(value) -> str:
|
||||
"""时间文本归一:`2026-11-09T07:00:15+08:00` / `2026-11-09 07:00:15` → 前 19 位比较。"""
|
||||
return str(value or "").strip().replace("T", " ")[:19]
|
||||
|
||||
|
||||
class SdkProvider(DataProvider):
|
||||
"""`latest_shift` / `detail` / `balance` 三个入口,结果按参数缓存。
|
||||
|
||||
@@ -35,5 +40,40 @@ class SdkProvider(DataProvider):
|
||||
|
||||
def balance(self, end: str):
|
||||
if end not in self._balance:
|
||||
self._balance[end] = self.sdk.collect.collect_member_balance(end, self.cfg)
|
||||
self._balance[end] = self.sdk.collect.collect_member_balance(
|
||||
end, self.cfg)
|
||||
return self._balance[end]
|
||||
|
||||
|
||||
class SnapshotProvider(SdkProvider):
|
||||
"""维护台账时用:余额/明细优先命中「导出快照」,没命中才回查 WCF。
|
||||
|
||||
导出那天的窗口数据一定在快照里(余额 20 万行、明细一整天的流水),所以
|
||||
「只维护台账」不用重新取数;台账落后多天、要补历史时,那几天的明细快照里没有,
|
||||
自然回退到查库(一次一条 SQL,很快),不会碰导出表。
|
||||
"""
|
||||
|
||||
def __init__(self, sdk, cfg, snapshot: dict | None = None, log=None):
|
||||
super().__init__(sdk, cfg)
|
||||
self.snapshot = snapshot or {}
|
||||
self.log = log or (lambda msg, level="INFO": None)
|
||||
self.hits = {"balance": False, "detail": 0}
|
||||
|
||||
def balance(self, end: str):
|
||||
table = self.snapshot.get("balance")
|
||||
if table is not None:
|
||||
got = getattr(table, "window", ()) or ("", "")
|
||||
if _norm_ts(got[-1]) == _norm_ts(end):
|
||||
self.hits["balance"] = True
|
||||
return table
|
||||
self.log("快照余额时间 %s ≠ 需要的 %s,改为重新取数" % (got[-1] or "空", end), "WARN")
|
||||
return super().balance(end)
|
||||
|
||||
def detail(self, start: str, end: str):
|
||||
table = self.snapshot.get("detail")
|
||||
if table is not None:
|
||||
got = getattr(table, "window", ()) or ("", "")
|
||||
if _norm_ts(got[0]) == _norm_ts(start) and _norm_ts(got[-1]) == _norm_ts(end):
|
||||
self.hits["detail"] += 1
|
||||
return table
|
||||
return super().detail(start, end)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出快照:把「导出」和「维护台账」拆成两步时中间的交接文件。
|
||||
|
||||
为什么要有:台账维护走 WPS COM,可能因为文件被占用、模板结构变动、WPS 抽风而失败;
|
||||
以前失败要整趟重跑——包括重新取 20 万行余额(二十多秒)和重写两份 Excel。
|
||||
现在**导出成功后**把两份结果表(SDK dataclass)整份存成快照,
|
||||
「只维护台账」直接读快照:不取数、不重写两份表,几十秒就能重试台账。
|
||||
|
||||
存放位置:`%LOCALAPPDATA%\\37duAutomation\\plugin_data\\xq0052\\snapshot_<营业日>.pkl.gz`
|
||||
(取不到 LOCALAPPDATA 时退回系统临时目录)。一个营业日一份,后一次导出覆盖前一次——
|
||||
重跑导出本来就等于重新取数,覆盖是对的。删掉它们不影响任何业务数据。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import os
|
||||
import pickle
|
||||
import tempfile
|
||||
from datetime import date, datetime
|
||||
|
||||
#: 快照结构版本;结构变化时 +1,老快照会被拒绝(提示重新导出)
|
||||
SNAPSHOT_VERSION = 1
|
||||
|
||||
|
||||
class SnapshotError(RuntimeError):
|
||||
"""没有可用的导出快照。"""
|
||||
|
||||
|
||||
def snapshot_dir() -> str:
|
||||
root = os.environ.get("LOCALAPPDATA") or ""
|
||||
if root:
|
||||
path = os.path.join(root, "37duAutomation", "plugin_data", "xq0052")
|
||||
else: # 极端情况(服务/精简环境)
|
||||
path = os.path.join(tempfile.gettempdir(), "37duAutomation_xq0052")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def snapshot_path(day: date) -> str:
|
||||
return os.path.join(snapshot_dir(), "snapshot_%s.pkl.gz" % day.strftime("%Y%m%d"))
|
||||
|
||||
|
||||
def save(day: date, *, window: dict, files: list, balance, detail,
|
||||
sdk: str = "", log=None) -> str:
|
||||
"""存一份导出快照(pickle + gzip)。返回快照路径。"""
|
||||
log = log or (lambda msg, level="INFO": None)
|
||||
payload = {
|
||||
"version": SNAPSHOT_VERSION,
|
||||
"day": day.strftime("%Y-%m-%d"),
|
||||
"saved_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"window": window or {},
|
||||
"files": list(files or []),
|
||||
"balance": balance,
|
||||
"detail": detail,
|
||||
"sdk": sdk,
|
||||
}
|
||||
path = snapshot_path(day)
|
||||
tmp = path + ".tmp"
|
||||
with gzip.open(tmp, "wb", compresslevel=4) as fh:
|
||||
pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
|
||||
os.replace(tmp, path)
|
||||
log("导出快照已保存:%s" % path)
|
||||
return path
|
||||
|
||||
|
||||
def load(day: date, log=None) -> dict:
|
||||
"""读某营业日的导出快照;没有/过期/损坏都抛 SnapshotError(带可读原因)。"""
|
||||
log = log or (lambda msg, level="INFO": None)
|
||||
path = snapshot_path(day)
|
||||
text = day.strftime("%Y-%m-%d")
|
||||
if not os.path.isfile(path):
|
||||
raise SnapshotError(
|
||||
"%s 没有导出快照(%s):先跑一次「只导出」或「导出+维护台账」,"
|
||||
"再用「只维护台账」重试" % (text, path))
|
||||
try:
|
||||
with gzip.open(path, "rb") as fh:
|
||||
payload = pickle.load(fh)
|
||||
except Exception as e: # noqa: BLE001 SDK 结构变化 / 文件损坏 / 半截文件
|
||||
raise SnapshotError(
|
||||
"导出快照读取失败(%s):%s;请重新跑「只导出」生成新快照" % (path, e)) from e
|
||||
if not isinstance(payload, dict) or payload.get("version") != SNAPSHOT_VERSION:
|
||||
raise SnapshotError(
|
||||
"导出快照格式已过期(%s):请重新跑「只导出」生成新快照" % path)
|
||||
if payload.get("day") != text:
|
||||
raise SnapshotError(
|
||||
"导出快照的营业日是 %s,不是 %s:请按营业日重新导出"
|
||||
% (payload.get("day"), text))
|
||||
log("复用导出快照:%s(%s 导出)" % (path, payload.get("saved_at")))
|
||||
return payload
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0052",
|
||||
"name": "湖畔储值卡每日导出统计",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"description": "按营业日导出金贵系统会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
@@ -42,17 +42,18 @@
|
||||
"type": "string",
|
||||
"title": "台账文件",
|
||||
"default": "D:\\资料\\财务\\湖畔储值卡每日导出统计",
|
||||
"description": "当月那份月度统计 Excel 的完整路径;也可填它所在的文件夹(运行时按营业日年月自动匹配当月那份,每月改名后不用改配置);留空=不维护台账;需关闭 Excel 后运行。台账会自动补齐交班时间、明细、新办卡,并覆盖余额"
|
||||
"description": "当月那份月度统计 Excel 的完整路径;也可填它所在的文件夹(运行时按营业日年月自动匹配当月那份,每月改名后不用改配置);留空=不维护台账;需在 WPS 里关掉这份台账(台账只用 WPS 表格维护,不调用 Office)。台账会自动补齐交班时间、明细、新办卡,并覆盖余额"
|
||||
},
|
||||
"ledger_mode": {
|
||||
"type": "string",
|
||||
"title": "台账维护",
|
||||
"default": "导表+维护台账",
|
||||
"title": "执行方式",
|
||||
"default": "导出+维护台账",
|
||||
"enum": [
|
||||
"导表+维护台账",
|
||||
"只导表"
|
||||
"导出+维护台账",
|
||||
"只导出",
|
||||
"只维护台账"
|
||||
],
|
||||
"description": "只导表=仅产出两份 Excel,不动台账"
|
||||
"description": "只导出=取数并出两份 Excel(留快照,不动台账);只维护台账=复用上一次导出的快照,不重新取数/导出,台账失败时用它重试"
|
||||
},
|
||||
"ledger_backup": {
|
||||
"type": "string",
|
||||
@@ -72,7 +73,7 @@
|
||||
"重算(推荐)",
|
||||
"不重算(快)"
|
||||
],
|
||||
"description": "模板公式是整列引用,20 万行全量重算可能几分钟;不重算则由 Excel 打开时自行计算(核对项会读到旧值)"
|
||||
"description": "模板公式是整列引用,20 万行全量重算可能几分钟;不重算则由 WPS 打开时自行计算(核对项会读到旧值)"
|
||||
},
|
||||
"ledger_month_reset": {
|
||||
"type": "string",
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -78,8 +78,8 @@
|
||||
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">台账维护</div>
|
||||
<div class="r-desc">只导表 = 不动台账,仅出两份 Excel</div>
|
||||
<div class="r-title">执行方式</div>
|
||||
<div class="r-desc">只导出 = 只出两份 Excel;只维护台账 = 复用上次导出,台账失败用它重试</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-select v-model="form.ledger_mode" class="sel-mode" :disabled="running">
|
||||
@@ -131,7 +131,7 @@
|
||||
<div class="tip">
|
||||
台账会自动补齐「交班时间 / 明细-原表 / 新办卡时间信息」、覆盖「会员卡余额」,并按「本月汇总数」核对。
|
||||
台账里残留上个月数据时,<b>切月</b>会先清空上月明细、把日期行滚到当月、期初取上月末;
|
||||
<b>运行前请关闭这个 Excel</b>。
|
||||
<b>运行前请关闭这个台账</b>(台账只用 <b>WPS 表格</b>维护,不会调用 Microsoft Office)。
|
||||
<br />
|
||||
台账填当月那一份 Excel 最直接;想每月改完名字不用再动配置,就改填它所在的<b>文件夹</b>
|
||||
(名字带「2026年11月」这类年月最稳),运行时会按营业日年月自动挑;
|
||||
@@ -180,7 +180,7 @@ import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 选项必须与后端 config / plugin.json.fields 的 enum 完全一致
|
||||
const MODES = ['导表+维护台账', '只导表']
|
||||
const MODES = ['导出+维护台账', '只导出', '只维护台账']
|
||||
const BACKUPS = ['先备份', '不备份']
|
||||
const RECALCS = ['重算(推荐)', '不重算(快)']
|
||||
const RESETS = ['自动切月(推荐)', '不切月(只补数)']
|
||||
@@ -190,7 +190,7 @@ const DEFAULTS = () => ({
|
||||
day: '',
|
||||
save_dir: 'D:\\资料\\财务\\湖畔储值卡统计',
|
||||
ledger_file: 'D:\\资料\\财务\\湖畔储值卡每日导出统计',
|
||||
ledger_mode: '导表+维护台账',
|
||||
ledger_mode: '导出+维护台账',
|
||||
ledger_backup: '先备份',
|
||||
ledger_recalc: '重算(推荐)',
|
||||
ledger_month_reset: '自动切月(推荐)',
|
||||
@@ -210,7 +210,7 @@ const {
|
||||
return false
|
||||
}
|
||||
if (ledgerOn.value && !String(form.ledger_file || '').trim()) {
|
||||
ElMessage.warning('台账维护已开启,请选择台账所在文件夹(或把台账维护改成「只导表」)')
|
||||
ElMessage.warning('要维护台账,请选择台账所在文件夹(或把执行方式改成「只导出」)')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -224,7 +224,8 @@ const {
|
||||
},
|
||||
})
|
||||
|
||||
const ledgerOn = computed(() => form.ledger_mode === '导表+维护台账')
|
||||
// 只导出不碰台账;「导出+维护台账」「只维护台账」都要台账
|
||||
const ledgerOn = computed(() => form.ledger_mode !== '只导出')
|
||||
|
||||
// 窗口提示:只描述口径,真正的时间点在执行日志里(需要查交班)
|
||||
const windowHint = computed(() => (form.day
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/* 全局样式(从 v0.3.x 构建产物还原;改动后请重跑 _build.ps1) */
|
||||
:root{--canvas: #F2F4F8;--surface: #FFFFFF;--field: #F5F6FA;--subtle: #F7F8FC;--line: #E8EAF1;--line-soft: #F0F2F7;--line-btn: #E3E6EF;--t1: #12141B;--t2: #3C4250;--t3: #6E7686;--t4: #A3AAB8;--t5: #C6CBD6;--brand: #4F5AE8;--brand-ink: #3D47D4;--brand-soft: #EEF0FE;--brand-track: #DDE1F8;--brand-hover: #4550E0;--good: #0E9F76;--good-ink: #0B8A66;--good-soft: #EBF7F2;--good-line: #D3EDE3;--warn: #D98218;--warn-ink: #B4700F;--warn-soft: #FDF3E4;--warn-line: rgba(217, 130, 24, .28);--danger: #E5484D;--danger-ink: #CC3B40;--danger-soft: #FDEDED;--danger-line: #F6D7D8;--r-row: 8px;--r-field: 9px;--r-btn: 10px;--r-sub: 12px;--r-card: 14px;--r-pill: 999px;--sh-card: 0 2px 8px rgba(18, 20, 31, .05);--sh-float: 0 8px 24px rgba(18, 20, 31, .1);--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;--space-1: 4px;--space-1-5: 6px;--space-2: 8px;--space-2-5: 10px;--space-3: 12px;--space-4: 16px;--space-5: 20px;--space-6: 28px;--dur: .15s;--ease: cubic-bezier(.22, 1, .36, 1)}
|
||||
:root{--el-color-primary: var(--brand);--el-color-primary-light-3: #7A83EE;--el-color-primary-light-5: #A6ACF4;--el-color-primary-light-7: #C9CDF9;--el-color-primary-light-8: #DDE0FB;--el-color-primary-light-9: var(--brand-soft);--el-color-primary-dark-2: var(--brand-ink);--el-color-success: var(--good);--el-color-success-light-9: var(--good-soft);--el-color-warning: var(--warn);--el-color-warning-light-9: var(--warn-soft);--el-color-danger: var(--danger);--el-color-danger-light-9: var(--danger-soft);--el-color-error: var(--danger);--el-text-color-primary: var(--t1);--el-text-color-regular: var(--t2);--el-text-color-secondary: var(--t3);--el-text-color-placeholder: var(--t4);--el-border-color: var(--line);--el-border-color-light: var(--line);--el-border-color-lighter: var(--line-soft);--el-border-color-extra-light: var(--line-soft);--el-fill-color-blank: var(--surface);--el-fill-color-light: var(--field);--el-bg-color: var(--surface);--el-border-radius-base: var(--r-field);--el-border-radius-small: var(--r-field);--el-font-family: var(--f-cn);--el-font-size-base: 12.5px;--el-box-shadow-light: var(--sh-card)}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;padding:0;background:var(--surface);color:var(--t1);font-family:var(--f-cn);font-size:12.5px;line-height:1.5;-webkit-font-smoothing:antialiased}
|
||||
#app{padding:0}
|
||||
.page{width:100%;display:flex;flex-direction:column;gap:var(--space-4);padding:2px 0 20px}
|
||||
.toolbar{display:flex;align-items:center;gap:var(--space-2);flex-wrap:wrap;min-height:32px}
|
||||
.toolbar .spacer{flex:1}
|
||||
.scheme-sel{width:200px}
|
||||
.saved{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 9px;border-radius:var(--r-pill);background:var(--good-soft);border:1px solid var(--good-line);color:var(--good-ink);font:500 11px/1 var(--f-cn);white-space:nowrap}
|
||||
.saved i{width:5px;height:5px;border-radius:50%;background:var(--good)}
|
||||
.saved.is-idle{background:var(--field);border-color:var(--line);color:var(--t4)}
|
||||
.saved.is-idle i{background:var(--t5)}
|
||||
.notice{display:flex;align-items:flex-start;gap:var(--space-2);padding:9px 12px;border-radius:var(--r-sub);border:1px solid var(--line);background:var(--subtle);font:400 12px/18px var(--f-cn);color:var(--t2)}
|
||||
.notice .n-ico{flex:0 0 auto;font-weight:700}
|
||||
.notice.is-warn{background:var(--warn-soft);border-color:var(--warn-line);color:var(--warn-ink)}
|
||||
.notice.is-error{background:var(--danger-soft);border-color:var(--danger-line);color:var(--danger-ink)}
|
||||
.notice.is-ok{background:var(--good-soft);border-color:var(--good-line);color:var(--good-ink)}
|
||||
.sec{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-sub);overflow:hidden}
|
||||
.sec-head{display:flex;align-items:center;gap:var(--space-2);padding:10px 14px;background:var(--subtle);border-bottom:1px solid var(--line)}
|
||||
.sec-badge{width:20px;height:20px;border-radius:6px;display:inline-grid;place-items:center;font:600 10.5px/1 var(--f-num);color:var(--brand-ink);background:var(--brand-soft);flex-shrink:0}
|
||||
.sec-name{font:600 13px/18px var(--f-cn);color:var(--t1);white-space:nowrap}
|
||||
.sec-line{flex:1;height:1px;background:var(--line-soft)}
|
||||
.sec-body{padding:14px 14px 6px}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:0 16px}
|
||||
.grid-switch{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}
|
||||
.grid-date{margin-top:4px}
|
||||
.grid .el-form-item{margin-bottom:12px}
|
||||
.grid .el-form-item__label{padding-bottom:6px!important;font-weight:500;color:var(--t2)}
|
||||
.grid .el-input,.grid .el-select,.grid .el-date-editor,.grid .el-input-number{width:100%!important}
|
||||
.tip{margin-top:var(--space-2);font:400 11.5px/1.65 var(--f-cn);color:var(--t3)}
|
||||
.tip b{color:var(--t2);font-weight:600}
|
||||
.plan{display:flex;align-items:baseline;gap:var(--space-2);font-size:11.5px;line-height:1.6;color:var(--t3)}
|
||||
.plan .p-tag{flex:0 0 auto;font-weight:600;color:var(--brand-ink)}
|
||||
.plan .p-text{min-width:0}
|
||||
.plan.is-empty .p-text{color:var(--warn)}
|
||||
.actions{display:flex;align-items:center;gap:var(--space-2);flex-wrap:wrap;padding-top:14px;border-top:1px solid var(--line-soft)}
|
||||
.actions .spacer{flex:1}
|
||||
.btn-run{min-width:150px;height:34px;border:none;border-radius:var(--r-btn);background:var(--brand);color:#fff;font:600 12.5px/18px var(--f-cn);letter-spacing:1px;box-shadow:var(--sh-brand);transition:background var(--dur),box-shadow var(--dur),transform .06s}
|
||||
.btn-run:hover{background:var(--brand-hover)}
|
||||
.btn-run:active{transform:translateY(1px);box-shadow:var(--sh-brand-sm)}
|
||||
.btn-run.is-loading{pointer-events:none}
|
||||
.badge{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 9px;border:1px solid transparent;border-radius:6px;font:500 11px/1 var(--f-cn);white-space:nowrap}
|
||||
.badge i{width:5px;height:5px;border-radius:50%;flex-shrink:0}
|
||||
.badge.ok{color:var(--good-ink);background:var(--good-soft);border-color:var(--good-line)}
|
||||
.badge.ok i{background:var(--good)}
|
||||
.badge.warn{color:var(--warn-ink);background:var(--warn-soft);border-color:var(--warn-line)}
|
||||
.badge.warn i{background:var(--warn)}
|
||||
.badge.bad{color:var(--danger-ink);background:var(--danger-soft);border-color:var(--danger-line)}
|
||||
.badge.bad i{background:var(--danger)}
|
||||
.badge.idle{color:var(--t3);background:var(--field);border-color:var(--line)}
|
||||
.badge.idle i{background:var(--t5)}
|
||||
.table-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-sub);overflow:hidden}
|
||||
.table-head{display:flex;align-items:center;justify-content:space-between;gap:var(--space-3);padding:12px 16px;background:var(--subtle);border-bottom:1px solid var(--line);font:600 13.5px/20px var(--f-cn);color:var(--t1)}
|
||||
.table{width:100%;border-collapse:collapse;table-layout:fixed}
|
||||
.table th{padding:10px 16px;text-align:center;font:500 11px/16px var(--f-cn);color:var(--t3);background:var(--surface);border-bottom:1px solid var(--line)}
|
||||
.table td{padding:10px 16px;text-align:center;border-bottom:1px solid var(--line-soft);font:400 12px/18px var(--f-cn);color:var(--t2)}
|
||||
.table tr:last-child td{border-bottom:0}
|
||||
.table tbody tr{transition:background var(--dur)}
|
||||
.table tbody tr:hover{background:var(--field)}
|
||||
.table td.is-name{text-align:left;font-weight:600;color:var(--t1)}
|
||||
.table th.is-name{text-align:left}
|
||||
.runline{display:flex;align-items:center;gap:var(--space-2);font-size:12px;color:var(--t3)}
|
||||
.runline .pct{font:600 12px/1 var(--f-num);color:var(--brand-ink);font-variant-numeric:tabular-nums}
|
||||
.pulse{width:7px;height:7px;border-radius:50%;background:var(--brand);animation:pulse 1.4s ease-out infinite}
|
||||
@keyframes pulse{0%{box-shadow:0 0 0 0 var(--brand-soft)}
|
||||
70%{box-shadow:0 0 0 7px transparent}
|
||||
to{box-shadow:0 0 0 0 transparent}
|
||||
}
|
||||
.step-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:var(--space-2-5)}
|
||||
.step-card{position:relative;display:flex;flex-direction:column;gap:3px;padding:11px 32px 11px 13px;background:var(--surface);border:1px solid var(--line);border-radius:var(--r-sub);cursor:pointer;transition:border-color var(--dur),background var(--dur),box-shadow var(--dur)}
|
||||
.step-card:hover{border-color:var(--brand-track);background:var(--subtle)}
|
||||
.step-card.on{border-color:var(--brand);background:var(--brand-soft);box-shadow:inset 0 0 0 1px var(--brand-soft)}
|
||||
.step-card .sc-title{font:600 13px/18px var(--f-cn);color:var(--t1)}
|
||||
.step-card.on .sc-title{color:var(--brand-ink)}
|
||||
.step-card .sc-desc{font:400 11.5px/1.6 var(--f-cn);color:var(--t3)}
|
||||
.step-card .sc-check{position:absolute;top:10px;right:10px;width:16px;height:16px;color:var(--brand)}
|
||||
.step-cards.is-disabled .step-card{opacity:.55;pointer-events:none}
|
||||
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
||||
.rows{display:flex;flex-direction:column;gap:var(--space-2);padding:var(--space-2);background:var(--subtle);border:1px solid var(--line);border-radius:var(--r-sub)}
|
||||
.row{display:flex;align-items:center;justify-content:space-between;gap:var(--space-4);padding:9px 12px;background:var(--surface);border:1px solid var(--line-soft);border-radius:var(--r-field)}
|
||||
.row .r-main{min-width:0}
|
||||
.row .r-title{font:500 12.5px/18px var(--f-cn);color:var(--t1)}
|
||||
.row .r-desc{margin-top:1px;font:400 11.5px/1.6 var(--f-cn);color:var(--t3)}
|
||||
.row .r-ctrl{flex:0 0 auto}
|
||||
.row.is-hidden{display:none}
|
||||
.help{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-sub);overflow:hidden}
|
||||
.help>summary{display:flex;align-items:center;justify-content:space-between;gap:var(--space-2);padding:10px 14px;background:var(--subtle);font:600 12.5px/18px var(--f-cn);color:var(--t2);cursor:pointer;list-style:none}
|
||||
.help>summary::-webkit-details-marker{display:none}
|
||||
.help[open]>summary{border-bottom:1px solid var(--line)}
|
||||
.help .h-arrow{color:var(--t4);transition:transform var(--dur);font-size:11px}
|
||||
.help[open] .h-arrow{transform:rotate(180deg)}
|
||||
.help-body{padding:12px 14px;font:400 12px/1.8 var(--f-cn);color:var(--t3)}
|
||||
.help-body b{color:var(--t2);font-weight:600}
|
||||
.help-body .hb-line+.hb-line{margin-top:6px}
|
||||
@@ -0,0 +1,356 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
// 用户强制停止 / 排队取消 / 排队超时 → 「已取消」,不显示成「执行失败」
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : (ev.status === 'cancelled' ? cancelled(ev.error) : failed(ev.error || '执行失败'))
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'cancelled') cancelled(r.error)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
// 用户主动停止 / 排队取消 / 排队超时:不算失败,给中性的「已取消」提示
|
||||
function cancelled(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('warn', '任务已取消:' + (err || '用户已停止'))
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
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-C6cU26PF.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0052/assets/index-CG5WLXss.css">
|
||||
<script type="module" crossorigin src="/pui/xq0052/assets/index-LUCCty2j.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0052/assets/index-BvjwJu6v.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
|
||||
Reference in New Issue
Block a user