# -*- 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 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: """宿主挂载后写入的 SDK_VERSIONS(id → version)。""" try: return json.loads(os.environ.get("SDK_VERSIONS") or "{}") except ValueError: return {} class HupanStoredCardPlugin(ScenePlugin): """湖畔储值卡每日导出统计(需求 XQ0052)。""" id = "xq0052" name = "湖畔储值卡每日导出统计" version = "0.4.0" 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], "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": "自动切月=月份不符时清明细/新办卡、汇总日期行滚到当月、期初取上月末", }, "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) # ---------- 一、导出两份 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") ctx.progress(100) 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)" return { "summary": summary, "files": files, "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, 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: return 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 #: 台账阶段失败时的下一步提示(导出成果已经落盘,不用重导) _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 PLUGINS.append(HupanStoredCardPlugin())