- 执行方式新增「只推送台账」:不取数、不改表,定位当天台账后直接推钉钉; 其余执行方式不再自动推送,维护表与推送可分成两个定时任务 - 钉钉推送改企业内部应用工作通知(actionCard + 下载台账按钮),台账先传文件服务器拿直链 - 台账定位支持跨月换表:营业日月份的表不在时按文件名年月取最新一份,同月多份仍报错不猜 - 新增 logic/push.py,界面/配置/README/_selftest 同步
438 lines
22 KiB
Python
438 lines
22 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0052 湖畔储值卡每日导出统计 —— 消费 SDK `hotel_report` 的会员卡统计插件。
|
||
|
||
取数/渲染全部由 SDK 提供(宿主按 `plugin.json.requires.sdks` 挂载 `hotel_report`),插件只负责:
|
||
读表单 → 解析营业日 → 让 SDK 现算「前一日最晚交班 ~ 当日最晚交班」→ 导出余额 + 明细 → 维护台账。
|
||
|
||
执行方式分四步可选(`config.LEDGER_MODE_*`):
|
||
· 导出+维护台账:一次跑完导出与台账(不推送);
|
||
· 只导出:只取数落表 + 存导出快照,不碰台账(也不需要 WPS);
|
||
· 只维护台账:复用上次导出的快照,只跑台账 —— 台账那步失败时重试用它,不用重新取数导出;
|
||
· 只推送台账:不取数、不动表,定位当天那份台账直接推钉钉(推送单独定时用)。
|
||
台账维护走 **WPS 表格 COM(Ket.Application)**,装了 Office 也不会去调用 Microsoft Excel。
|
||
|
||
业务背景:储值卡(会员卡)按**营业日**结算,营业日由交班切开,不是自然日零点的。
|
||
所以窗口必须用两天的**最晚总交班时间**(`dt_changeclass` 里 `ChangeClassId like 'Z%'` 的最大值):
|
||
· 余额:只用上界 —— 截至当日交班时的余额快照;
|
||
· 明细:`[前一日最晚交班, 当日最晚交班]` 内的充值/消费/调整流水。
|
||
当日还没交班时窗口不闭合,直接报错退出,不产半天的表。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import time
|
||
|
||
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
|
||
|
||
|
||
def _sdk_versions() -> dict:
|
||
"""宿主挂载后写入的 SDK_VERSIONS(id → version)。"""
|
||
try:
|
||
return json.loads(os.environ.get("SDK_VERSIONS") or "{}")
|
||
except ValueError:
|
||
return {}
|
||
|
||
|
||
#: 导出表落盘重试:目标 xlsx 正被 WPS/Excel 打开时 openpyxl 会 PermissionError
|
||
_EXPORT_RETRIES = 3
|
||
_EXPORT_RETRY_DELAY = 2.0
|
||
|
||
|
||
def _save_xlsx(path: str, writer, ctx, what: str):
|
||
"""写一份导出表;被别的程序占用(财务开着那份 xlsx)时等一下重试,仍失败给中文提示。
|
||
|
||
原来的表现:直接抛 `PermissionError: [Errno 13] Permission denied: '...会员卡余额_xxx.xlsx'`
|
||
加一串 openpyxl 清理临时文件的 `Exception ignored`,财务完全看不出是"表被打开着"。
|
||
"""
|
||
name = os.path.basename(path)
|
||
last = None
|
||
for attempt in range(1, _EXPORT_RETRIES + 1):
|
||
try:
|
||
return writer()
|
||
except PermissionError as e:
|
||
last = e
|
||
if attempt < _EXPORT_RETRIES:
|
||
wait = _EXPORT_RETRY_DELAY * attempt
|
||
ctx.log("%s写不进去:「%s」正被别的程序占用(多半是 WPS/Excel 开着它),"
|
||
"%g 秒后重试(%d/%d)"
|
||
% (what, name, wait, attempt, _EXPORT_RETRIES), "WARN")
|
||
time.sleep(wait)
|
||
raise RuntimeError(
|
||
"写不了%s「%s」:文件被其它程序独占(请关掉 WPS/Excel 里打开着的这份表,"
|
||
"或结束残留的 et.exe / wps.exe 进程,再重跑一次)。原始错误:%s"
|
||
% (what, path, last)) from last
|
||
|
||
|
||
class HupanStoredCardPlugin(ScenePlugin):
|
||
"""湖畔储值卡每日导出统计(需求 XQ0052)。"""
|
||
|
||
id = "xq0052"
|
||
name = "湖畔储值卡每日导出统计"
|
||
version = "0.6.9"
|
||
description = ("按营业日导出会员卡统计(余额 + 明细),并维护会员卡统计台账 Excel:"
|
||
"交班时间逐日追加、余额覆盖、明细/新办卡追加、汇总核对;"
|
||
"台账维护与钉钉推送拆成两个执行方式,可分开定时")
|
||
platform = ""
|
||
uses_month = False
|
||
capabilities = ["xq0052"]
|
||
permissions = {"platforms": []}
|
||
# 与 plugin.json.fields 一致(底座按 fields 渲染表单)
|
||
fields = {
|
||
"day": {
|
||
"type": "string", "format": "date", "title": "营业日", "default": "",
|
||
"description": "YYYY-MM-DD;留空=今天。窗口自动取「前一日最晚交班 ~ 该日最晚交班」",
|
||
},
|
||
"save_dir": {
|
||
"type": "string", "title": "导出文件保存到", "default": config.DEFAULT_SAVE_DIR,
|
||
"description": "余额与明细两份导出表保存到这里",
|
||
},
|
||
"ledger_file": {
|
||
"type": "string", "title": "台账文件",
|
||
"default": config.DEFAULT_LEDGER_DIR,
|
||
"description": "当月那份月度统计 Excel 的完整路径;也可填它所在的文件夹"
|
||
"(运行时按营业日年月自动匹配当月那份);留空=不维护台账;"
|
||
"需在 WPS 里关掉这份台账(只用 WPS 维护,不调用 Office)",
|
||
},
|
||
"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, config.LEDGER_MODE_PUSH_ONLY],
|
||
"description": "导出+维护台账=取数、出表并维护台账(不推送);只导出=只出两份 Excel;"
|
||
"只维护台账=复用上次导出只维护台账;只推送台账=不取数不动表,"
|
||
"直接把当天那份台账推到钉钉(推送单独定时用)",
|
||
},
|
||
"ledger_backup": {
|
||
"type": "string", "title": "台账备份", "default": config.BACKUP_ON,
|
||
"enum": [config.BACKUP_ON, config.BACKUP_OFF],
|
||
"description": "先备份=同目录生成「<台账名>_备份_YYYYMMDD.xlsx」后再改",
|
||
},
|
||
"ledger_recalc": {
|
||
"type": "string", "title": "台账重算", "default": config.RECALC_ON,
|
||
"enum": [config.RECALC_ON, config.RECALC_OFF],
|
||
"description": "不重算则由 WPS 打开文件时自行计算(核对项会读到旧值)",
|
||
},
|
||
"ledger_month_reset": {
|
||
"type": "string", "title": "切月初始化", "default": config.RESET_ON,
|
||
"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": "留空=使用默认地址(技术排障用,一般不用填)",
|
||
},
|
||
}
|
||
|
||
# ------------------------------------------------------------------ 主流程
|
||
def run(self, fields: dict, ctx) -> dict:
|
||
fields = fields or {}
|
||
config.set_log(ctx.log)
|
||
|
||
try:
|
||
import hotel_report
|
||
except ImportError as e: # SDK 未挂载/未授权
|
||
raise RuntimeError(
|
||
"SDK hotel_report 未挂载:请确认插件 requires.sdks 已声明、"
|
||
f"执行机已同步并安装该 SDK({e})"
|
||
) from e
|
||
|
||
sdk_ver = str(getattr(hotel_report, "__version__", ""))
|
||
mounted = _sdk_versions().get("hotel_report", "")
|
||
ctx.log(f"SDK hotel_report {sdk_ver}(宿主挂载版本:{mounted or '未上报'})")
|
||
|
||
try:
|
||
day = period.parse_day(fields.get("day"))
|
||
except ValueError as e:
|
||
raise RuntimeError(f"营业日不正确:{e}") from e
|
||
|
||
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)
|
||
|
||
# 「只推送台账」:不取数、不动表,定位当天那份台账直接推送(推送单独定时用)
|
||
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:
|
||
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"]))
|
||
|
||
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('"')
|
||
ledger = None
|
||
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, 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")
|
||
or config.RESET_ON) == config.RESET_ON,
|
||
ctx=ctx)
|
||
elif not ledger_dir:
|
||
ctx.log("未配置台账文件夹,跳过台账维护(只出两份导出表)", "WARN")
|
||
|
||
summary = (
|
||
"湖畔储值卡统计完成(营业日 %s,%s)\n"
|
||
"· 结算窗口:%s ~ %s\n"
|
||
"· 会员卡余额:%s 人,卡内余额合计 %s\n"
|
||
"· 会员卡明细:%s 行\n"
|
||
"· 导出目录:%s"
|
||
) % (
|
||
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):,}",
|
||
save_dir,
|
||
)
|
||
if ledger:
|
||
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,
|
||
"path": files[0] if files else "",
|
||
"sdk": sdk_ver,
|
||
"mode": mode,
|
||
"window": window,
|
||
"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,
|
||
}
|
||
|
||
# ------------------------------------------------------------------ 导出
|
||
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"]))
|
||
btarget = os.path.join(save_dir, "会员卡余额_%s.xlsx" % stamp)
|
||
bpath = _save_xlsx(btarget, lambda: hotel_report.render.write_member_balance_xlsx(
|
||
balance, btarget), ctx, "会员卡余额表")
|
||
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"]))
|
||
dtarget = os.path.join(save_dir, "会员卡明细_%s.xlsx" % stamp)
|
||
dpath = _save_xlsx(dtarget, lambda: hotel_report.render.write_member_detail_xlsx(
|
||
detail, dtarget), ctx, "会员卡明细表")
|
||
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, snapshot: dict,
|
||
backup: bool, recalc: bool, month_reset: bool, ctx) -> dict:
|
||
from .logic.ledger import LedgerError, LedgerMaintainer
|
||
from .logic.provider import SnapshotProvider
|
||
|
||
if not os.path.isfile(path):
|
||
ctx.log("台账文件不存在,跳过维护:%s" % path, "WARN")
|
||
return {"skipped": "台账文件不存在", "path": path}
|
||
ctx.log("--- 维护台账:%s" % path)
|
||
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:
|
||
res = maint.run(day, provider)
|
||
except LedgerError as 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
|
||
# 兜底:整趟返回值要经壳子 `json.dumps` 回传前端,任何不可序列化的对象(date、COM 对象…)
|
||
# 都会在壳子侧抛错并被静默吞掉 → 前端只看到「执行进程异常退出(exit=0)且未返回结果」,
|
||
# 而台账其实已经保存成功(v0.4.1 的坑)。这里先自检一遍,坏字段转文本,别让结果凭空消失。
|
||
try:
|
||
json.dumps(res)
|
||
except (TypeError, ValueError) as e:
|
||
ctx.log("台账结果含无法回传的字段(%s),已按文本处理" % e, "WARN")
|
||
res = json.loads(json.dumps(res, default=str))
|
||
return res
|
||
|
||
|
||
#: 台账阶段失败时的下一步提示(导出成果已经落盘,不用重导)
|
||
_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:
|
||
if ledger.get("skipped"):
|
||
return "\n· 台账:跳过(%s)" % ledger["skipped"]
|
||
text = ""
|
||
reset = ledger.get("reset")
|
||
if reset:
|
||
text += ("\n· 切月初始化:%s → %s(清明细 %d 行、清新办卡 %d 行,期初 %s)"
|
||
% ("、".join(reset.get("from") or []) or "空", reset.get("to"),
|
||
int(reset.get("detail_cleared") or 0),
|
||
int(reset.get("newcard_cleared") or 0),
|
||
"、".join("%s=%s" % (k, v) for k, v in (reset.get("init") or {}).items())))
|
||
checks = ledger.get("checks") or []
|
||
bad = [c for c in checks if not c.get("ok")]
|
||
text += ("\n· 台账:补 %d 天、明细 +%s 行、新办卡 +%s 行、余额 %s 人(合计 %s)"
|
||
% (len(ledger.get("days") or []),
|
||
f"{int(ledger.get('detail_rows') or 0):,}",
|
||
f"{int(ledger.get('new_cards') or 0):,}",
|
||
f"{int(ledger.get('balance_rows') or 0):,}",
|
||
f"{float(ledger.get('balance_total') or 0):,.2f}"))
|
||
if checks:
|
||
text += "\n· 核对:%d 项,%d 项不一致" % (len(checks), len(bad))
|
||
for c in bad:
|
||
text += "\n ✗ %s:应为 %s / 实际 %s%s" % (
|
||
c["name"], c["expect"], c["actual"], ("(%s)" % c["note"]) if c.get("note") else "")
|
||
if ledger.get("backup"):
|
||
text += "\n· 备份:%s" % ledger["backup"]
|
||
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())
|