XQ0034 v1.0.31:AI 表字段「电子签接收电话号码」已改名为「电子签接收员工本人电话」,插件版与 workflows 版同步,避免写旧字段 404。XQ0052 v0.4.3:台账写入改事务顺序(明细 -> 新办卡 -> 交班行 -> 余额 -> 一次保存),交班行作为补数进度提交点,中途失败整簿不落盘;返回值 days 改 isoformat 修复 exit=0 但结果被静默丢弃;导出落盘遇文件占用(WPS/Excel 打开)改重试 3 次并给中文提示;台账已含某营业日时改为核对明细覆盖度。
308 lines
12 KiB
Python
308 lines
12 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""离线自测:不联网、不碰生产数据。
|
||
|
||
校验三件事:
|
||
1. 营业日解析(空=今天 / 各种日期写法 / 非法输入要报错);
|
||
2. 结算窗口 + 一次导出两份表(用假数据模拟 WCF 返回);
|
||
3. 台账定位(文件夹 → 按年月自动匹配当月 Excel,分不清要报错)。
|
||
|
||
SDK 兼容预检(`tools/sdk_compat_check.py`)会在挂载 SDK 后跑本文件;也可手动:
|
||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0052 湖畔储值卡每日导出统计\\_selftest.py"
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
from datetime import date
|
||
|
||
BALANCE_ROWS = [
|
||
{"Memberid": "GD001", "CardTypeName": "储值卡", "leavemoney": "1500.5000",
|
||
"griftleave": "1200.0000", "factleave": "300.5000", "MemberGuid": "g1",
|
||
"Coach": "石桥铺会馆", "EnterDate": "2026-01-01T10:00:00+08:00",
|
||
"MobilePhone": "13800000000", "Status": "正常", "PartitionLeaveMoney": "0.0000",
|
||
"MemberName": "张三"},
|
||
]
|
||
|
||
DETAIL_ROWS = [
|
||
{"feeindate": "2026-11-05T10:00:00+08:00", "memberid": "GD001", "membername": "张三",
|
||
"billid": "CW202611050001-01", "mobilephone": "13800000000", "leavecardmoney": "2000.0000",
|
||
"money": "2000.0000", "truemoney": "2000.0000", "feetype": "充值", "basemoney": "0.0",
|
||
"giftmoney": "0.0", "cardtypename": "储值卡", "oldmoney": "0.0", "shishou": "2000.0",
|
||
"favourmoney": "0.0", "vpnname": None, "opersite": "财务部", "persumename": None,
|
||
"hj": "王五", "waternum": "W001", "factconsume": None, "totalconsume": "-1",
|
||
"memberremark": None, "coach": "石桥铺会馆", "enterdate": "2026-01-01T10:00:00+08:00",
|
||
"operatorname": "张三", "jifen": "0"},
|
||
]
|
||
|
||
PAY_ROWS = [{"Billid": "CW202611050001-01", "MethodName": "微信扫码支付", "amt": "2000.0000"}]
|
||
|
||
|
||
def _fake_query(sql, cfg=None, params=()):
|
||
text = sql.lstrip().lstrip(";").strip().lower()
|
||
if "max(changetime)" in text:
|
||
day = str(params[0])[:10] if params else "2026-11-05"
|
||
return [{"latest": "%sT07:00:16+08:00" % day}]
|
||
if "dt_membercardcomein" in text:
|
||
return PAY_ROWS
|
||
if text.startswith("select paravalue"):
|
||
return [{"ParaValue": None}]
|
||
if "latest as (" in text:
|
||
return BALANCE_ROWS
|
||
if "a.leavecardmoney" in text:
|
||
return DETAIL_ROWS
|
||
raise AssertionError("未预期的 SQL:%s" % sql.strip()[:60])
|
||
|
||
|
||
def _check_period(period) -> list:
|
||
problems = []
|
||
if period.parse_day("2026-11-05") != date(2026, 11, 5):
|
||
problems.append("parse_day('2026-11-05') 解析错误")
|
||
if period.parse_day("2026/11/05") != date(2026, 11, 5):
|
||
problems.append("parse_day 不支持 YYYY/MM/DD")
|
||
if period.parse_day("2026-11-05 18:30:00") != date(2026, 11, 5):
|
||
problems.append("parse_day 未丢弃时间部分")
|
||
if period.parse_day("") != period.today():
|
||
problems.append("营业日留空应取今天")
|
||
if period.file_stamp(date(2026, 11, 5)) != "20261105":
|
||
problems.append("file_stamp 错误")
|
||
try:
|
||
period.parse_day("上个月")
|
||
except ValueError:
|
||
pass
|
||
else:
|
||
problems.append("非法营业日应抛 ValueError")
|
||
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, _as_date, _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))}")
|
||
if abs(_time(datetime(2026, 11, 1, 12)) - 46327.5) > 1e-9:
|
||
problems.append("半天序列错误")
|
||
# 明细 A 列 =INT(LOOKUP(...)) 读回来常是日期序列数,核对覆盖度时要能认
|
||
if _as_date(46327) != date(2026, 11, 1) or _as_date(46327.0) != date(2026, 11, 1):
|
||
problems.append(f"日期序列反解错误:{_as_date(46327)}")
|
||
|
||
class _P(DataProvider):
|
||
def latest_shift(self, d):
|
||
return {date(2026, 11, 1): "2026-11-01 07:00:28",
|
||
date(2026, 11, 2): "2026-11-02 07:01:44"}.get(d)
|
||
|
||
def detail(self, start, end):
|
||
raise AssertionError("不应在 _plan 里取明细")
|
||
|
||
def balance(self, end):
|
||
raise AssertionError("不应在 _plan 里取余额")
|
||
|
||
maint = LedgerMaintainer("unused.xlsx")
|
||
state = {"shift_day": date(2026, 11, 1), "shift_row": 1289, "detail_row": 4422,
|
||
"newcard_row": 2676, "bal_last": 206430, "bal_total_row": 206431}
|
||
days = maint._plan(state, date(2026, 11, 2), _P())
|
||
if len(days) != 1:
|
||
problems.append(f"待补天数应为 1,实际 {len(days)}")
|
||
else:
|
||
d = days[0]
|
||
# 窗口 [11-01 交班, 11-02 交班] 的数据在台账里归到 11-01
|
||
expect = {"day": date(2026, 11, 2), "start": "2026-11-01 07:00:28",
|
||
"end": "2026-11-02 07:01:44", "label": date(2026, 11, 1)}
|
||
for k, v in expect.items():
|
||
if d.get(k) != v:
|
||
problems.append(f"窗口 {k} 应为 {v},实际 {d.get(k)}")
|
||
|
||
# 目标日还没交班 → 必须拒绝(不能出半天的表)
|
||
class _NoShift(_P):
|
||
def latest_shift(self, d):
|
||
return None
|
||
|
||
try:
|
||
maint._plan(state, date(2026, 11, 2), _NoShift())
|
||
except LedgerError:
|
||
pass
|
||
else:
|
||
problems.append("当日未交班应抛 LedgerError")
|
||
return problems
|
||
|
||
|
||
def _check_ledger_path() -> list:
|
||
"""台账定位(只动临时目录):文件夹自动匹配 / 多份报错 / 备份与导出表要排除。"""
|
||
import shutil
|
||
|
||
from logic import ledger_path
|
||
|
||
problems = []
|
||
root = tempfile.mkdtemp(prefix="xq0052_ledger_path_")
|
||
day = date(2026, 11, 5)
|
||
|
||
def touch(name):
|
||
with open(os.path.join(root, name), "wb"):
|
||
pass
|
||
|
||
try:
|
||
if ledger_path.resolve("", day) != "":
|
||
problems.append("台账没填时应返回空串")
|
||
|
||
# 只有一份 → 直接用(名字没年月也认)
|
||
touch("会员卡统计.xlsx")
|
||
touch("会员卡统计_备份_20261105_070000.xlsx") # 插件备份,必须排除
|
||
touch("~$会员卡统计.xlsx") # Excel 临时文件,必须排除
|
||
touch("会员卡余额_20261105.xlsx") # 同目录导出表,必须排除
|
||
touch("会员卡明细_20261105.xlsx")
|
||
got = ledger_path.resolve(root, day)
|
||
if os.path.basename(got) != "会员卡统计.xlsx":
|
||
problems.append(f"单份台账匹配错误:{got}")
|
||
|
||
# 完整文件路径(旧配置)→ 原样使用
|
||
if ledger_path.resolve(got, day) != got:
|
||
problems.append("填完整文件路径时应原样使用")
|
||
|
||
# 多份且都没当月年月 → 报错(不猜)
|
||
touch("2026年10月会员卡统计.xlsx")
|
||
try:
|
||
ledger_path.resolve(root, day)
|
||
except ledger_path.LedgerPathError:
|
||
pass
|
||
else:
|
||
problems.append("多份台账分不清时应抛 LedgerPathError")
|
||
|
||
# 有当月年月 → 用它
|
||
touch("2026年11月会员卡统计-模版调整-新会员卡.xlsx")
|
||
got = ledger_path.resolve(root, day)
|
||
if os.path.basename(got) != "2026年11月会员卡统计-模版调整-新会员卡.xlsx":
|
||
problems.append(f"当月台账匹配错误:{got}")
|
||
|
||
# 目录不存在 → 跳过(空串),不抛
|
||
if ledger_path.resolve(os.path.join(root, "nope"), day) != "":
|
||
problems.append("目录不存在时应返回空串")
|
||
finally:
|
||
shutil.rmtree(root, ignore_errors=True)
|
||
return problems
|
||
|
||
|
||
def main() -> int:
|
||
try:
|
||
from hotel_report import HotelConfig, export_member, settle_window
|
||
except ImportError as e:
|
||
print(f"SDK hotel_report 未挂载:{e}", file=sys.stderr)
|
||
return 2
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
import config
|
||
from logic import period
|
||
|
||
problems = (_check_period(period) + _check_mode(config)
|
||
+ _check_ledger() + _check_ledger_path())
|
||
if problems:
|
||
print("口径异常:\n- " + "\n- ".join(problems), file=sys.stderr)
|
||
return 1
|
||
|
||
cfg = HotelConfig(wcf_url="http://127.0.0.1:1/unused", timeout=1)
|
||
w = settle_window(cfg, date(2026, 11, 5), query=_fake_query)
|
||
if w["start"] != "2026-11-04 07:00:16" or w["end"] != "2026-11-05 07:00:16":
|
||
print(f"结算窗口错误:{w}", file=sys.stderr)
|
||
return 1
|
||
if not w["closed"]:
|
||
print(f"窗口应已闭合:{w}", file=sys.stderr)
|
||
return 1
|
||
|
||
out_dir = tempfile.mkdtemp(prefix="xq0052_selftest_")
|
||
res = export_member(cfg, date(2026, 11, 5), out_dir, window=w, query=_fake_query)
|
||
names = [os.path.basename(p) for p in res.get("files") or []]
|
||
if names != ["会员卡余额_20261105.xlsx", "会员卡明细_20261105.xlsx"]:
|
||
print(f"产出文件不符:{names}", file=sys.stderr)
|
||
return 1
|
||
for path in res["files"]:
|
||
if not os.path.isfile(path):
|
||
print(f"文件不存在:{path}", file=sys.stderr)
|
||
return 1
|
||
if res["balance"]["count"] != 1 or res["balance"]["totals"]["卡内余额"] != 1500.5:
|
||
print(f"余额结果异常:{res['balance']}", file=sys.stderr)
|
||
return 1
|
||
if res["detail"]["count"] != 1:
|
||
print(f"明细结果异常:{res['detail']}", file=sys.stderr)
|
||
return 1
|
||
|
||
print(f"xq0052 selftest OK(窗口 {w['start']} ~ {w['end']},余额 "
|
||
f"{res['balance']['count']} 人、明细 {res['detail']['count']} 行)")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|