feat(xq0052): 台账改用 WPS 维护并新增导出快照,支持只导出/只维护台账(0.4.0)
- 新增 logic/snapshot.py:导出后落快照,台账失败可复用上次导出数据重试,不用重新取数 - 台账只走 WPS 表格(不调 Office),字段提示同步改为关闭 WPS - 新增 通联扫码统计 支付数据追加 / 流程 两个测试;前端重建(ui 产物 + usePluginUI/style 拆分)
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user