# -*- coding: utf-8 -*- """XQ0052 探针二:把「会员卡余额」的多语句批改写成单条 CTE,验证 WCF 通道可执行。 原批(legacy/export_member.py::BALANCE_SQL)4 个 #临时表: #MemberTrans → #MemberFeeDates → #PartitionSums → #LatestPartitions CTE 改写保持口径不变,只把 SELECT INTO 换成 WITH,变量换成 para 单行。 本脚本自带原始 SOAP 调用,能把服务端 fault 原文打出来(SDK 的 wcf.query 只报 HTTP 500)。 """ from __future__ import annotations import os import sys import time import urllib.error import urllib.request import xml.etree.ElementTree as ET BASE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(BASE, "..", "..", "libs", "hotel_report")) from hotel_report import HotelConfig, latest_shift_time, wcf # noqa: E402 ROOT = os.path.join(BASE, "..", "..", "libs", "hotel_report") def raw_query(sql: str, cfg: HotelConfig): """与 wcf.query 同协议,但保留 HTTP 错误体里的 faultstring。""" payload = wcf.ENVELOPE.format(sql=wcf._xml_escape(wcf.fill(sql, ()))).encode("utf-8") req = urllib.request.Request( cfg.wcf_url, data=payload, method="POST", headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": f'"{wcf.ACTION}"'}) try: with urllib.request.urlopen(req, timeout=cfg.timeout) as resp: return wcf.parse_dataset(resp.read()) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace") reason = "" try: root = ET.fromstring(body) for el in root.iter(): if el.tag.endswith("faultstring"): reason = el.text or "" except ET.ParseError: reason = body raise RuntimeError(f"HTTP {e.code}: {reason.strip()[:800]}") from None BALANCE_CTE = """ with para as ( select (select ParaValue from jgmember.dbo.Dt_MemberSysPara with (nolock) where ParaName = 'cmbIsStartAdjustBill') as adj, (select ParaValue from jgmember.dbo.Dt_MemberSysPara with (nolock) where ParaName = 'cmbIsCalcMemberPercent') as pct ), mt as ( select a.Memberid, a.cardtypename, a.Money, a.GiftMoney, a.BaseMoney, a.VRealPercentNum, a.PRealPercentNum, a.PercentNum, a.GriftMoney, a.MemberGuid, a.coach, a.EnterDate, a.MobilePhone, a.Status, a.FeeInDate, a.Billid, a.MemberName, 0 as AllPayByPartition from jgmember.dbo.V_GetMemberOperateHistory a with (nolock) where a.FeeInDate <= '{endtime}' and a.status <> '删除' and (a.Remark <> '非卡结' or a.Remark is null) ), fee_dates as ( select distinct mt.MemberGuid, mt.FeeInDate from mt ), part as ( select pm.MemberGuid, d.FeeInDate, sum(isnull(p.ChangeMoney, 0)) as s from fee_dates d join jgmember.dbo.P_PartitionMember pm with (nolock) on pm.MemberGuid = d.MemberGuid left join jgmember.dbo.P_PartitionMoneyHistory p with (nolock) on p.PartitionMemberId = pm.PartitionMemberId and p.OperateDate <= d.FeeInDate and p.OperateDate <= '{endtime}' group by pm.MemberGuid, d.FeeInDate ), latest as ( select p.MemberGuid, p.s as LatestPartitionSum from part p join (select MemberGuid, max(FeeInDate) as md from part group by MemberGuid) m on m.MemberGuid = p.MemberGuid and m.md = p.FeeInDate ) select {top} m.Memberid, m.cardtypename as CardTypeName, convert(decimal(18,2), sum( jgmember.dbo.F_GetMemberMoney('余额', para.adj, isnull(case when m.AllPayByPartition = 1 then 0 else m.Money end, 0), m.VRealPercentNum, m.PRealPercentNum, null) )) as leavemoney, convert(decimal(18,2), sum( jgmember.dbo.F_GetMemberMoney('余额', para.adj, case when para.pct = '是' then m.GiftMoney else m.Money end, m.VRealPercentNum, m.PRealPercentNum, (1 - case when para.pct = '是' then isnull(m.PercentNum,1) else m.GriftMoney end)) )) as griftleave, convert(decimal(18,2), sum( jgmember.dbo.F_GetMemberMoney('余额', para.adj, case when para.pct = '是' then m.BaseMoney else m.Money end, m.VRealPercentNum, m.PRealPercentNum, (case when para.pct = '是' then isnull(m.PercentNum,1) else m.GriftMoney end)) )) as factleave, m.MemberGuid, m.coach as Coach, m.EnterDate, m.MobilePhone, m.Status, convert(decimal(18,2), isnull(lp.LatestPartitionSum, 0)) as PartitionLeaveMoney, m.MemberName from mt m cross join para left join latest lp on lp.MemberGuid = m.MemberGuid group by m.Memberid, m.cardtypename, m.MemberGuid, m.coach, m.EnterDate, m.MobilePhone, m.Status, lp.LatestPartitionSum, m.MemberName, para.adj, para.pct order by m.Memberid """ def main() -> int: if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") cfg = HotelConfig.resolve(timeout=300) from datetime import datetime today = datetime.now() cur = latest_shift_time(cfg, today) end = cur["latest"] or today.strftime("%Y-%m-%d %H:%M:%S") print(f"WCF: {cfg.wcf_url}\n余额截至: {end}") for label, top in (("top 50 (;with)", "top 50"), ("全量 (;with)", "")): sql = ";" + BALANCE_CTE.format(endtime=end, top=top).lstrip() t0 = time.time() try: rows = raw_query(sql, cfg) except Exception as e: # noqa: BLE001 print(f"\n[{label}] FAIL: {type(e).__name__}: {e}") return 1 print(f"\n[{label}] OK {len(rows)} 行 / {time.time() - t0:.1f}s") if rows: r = rows[0] print(" 列: " + ", ".join(r.keys())) print(" 首行: " + " | ".join(f"{k}={v}" for k, v in list(r.items())[:8])) print(f" 卡内余额合计: {sum(float(x['leavemoney'] or 0) for x in rows):,.2f}") if not top: break return 0 if __name__ == "__main__": sys.exit(main())