restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
This commit is contained in:
@@ -28,13 +28,6 @@ SAVE_TOKEN = True # 登录成功后把 token 落到临时文件,便于后
|
||||
VERIFY_TOKEN = True # 登录成功后调用一次 userInfo 验证 token 是否可用
|
||||
# ===============================================
|
||||
|
||||
# 账号密码也可以写在同目录 account.json({"account": "...", "password": "..."})
|
||||
_ACC_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "account.json")
|
||||
if os.path.exists(_ACC_FILE):
|
||||
_acc = json.load(open(_ACC_FILE, encoding="utf-8"))
|
||||
ACCOUNT = ACCOUNT or _acc.get("account", "")
|
||||
PASSWORD = PASSWORD or _acc.get("password", "")
|
||||
|
||||
BASE = "https://user.lotsmall.cn"
|
||||
TIMEOUT = 15
|
||||
RSA_PUBLIC_KEY = (
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""sdk_compat_check 自检:用固定夹具跑完所有判定分支。
|
||||
|
||||
运行(仓库根)::
|
||||
|
||||
.venv\\Scripts\\python.exe tests\\sdk_compat_check\\_run_cases.py
|
||||
|
||||
仓库没有 pytest 组织(tests/ 是探针脚本集合),所以这里用可直接运行的自检脚本,
|
||||
任一用例不符即非 0 退出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = HERE.parents[1]
|
||||
TOOL = REPO / "tools" / "sdk_compat_check.py"
|
||||
PLUGINS = HERE / "plugins"
|
||||
SDK_OLD = HERE / "sdk_v1.0.0"
|
||||
SDK_NEW = HERE / "sdk_v1.1.0"
|
||||
SDK_MAJOR = HERE / "sdk_v2.0.0"
|
||||
|
||||
CASES = [
|
||||
# name, extra args, 期望分类, 期望退出码, 期望 error 码集合, 期望 summary 片段
|
||||
("p_ok", ["--only", "p_ok"], "COMPATIBLE", 0, set(), {"pass": 1}),
|
||||
("p_undeclared", ["--only", "p_undeclared"], "PLUGIN_BUMP", 1, {"UNDECLARED_SDK"}, {}),
|
||||
("p_missing", ["--only", "p_missing"], "ACCIDENTAL_BREAK", 1, {"MISSING_API"}, {}),
|
||||
("p_import_fail", ["--only", "p_import_fail"], "ACCIDENTAL_BREAK", 1, {"IMPORT_FAIL"}, {}),
|
||||
("p_old_major", ["--sdk", str(SDK_MAJOR), "--baseline-sdk", str(SDK_OLD),
|
||||
"--only", "p_old_major"], "PLUGIN_BUMP", 1, {"NEEDS_BUMP"}, {}),
|
||||
("p_legacy(API_REMOVED)", ["--baseline-sdk", str(SDK_OLD), "--only", "p_legacy"],
|
||||
"ACCIDENTAL_BREAK", 1, {"API_REMOVED", "MISSING_API"}, {}, {"API_SIGNATURE_CHANGED"}),
|
||||
("p_skip", ["--only", "p_skip"], "COMPATIBLE", 0, set(), {"skipped": 1, "checked": 0}),
|
||||
("p_selftest_fail", ["--only", "p_selftest_fail"], "ACCIDENTAL_BREAK", 1,
|
||||
{"SELFTEST_FAIL"}, {}),
|
||||
("p_dynamic", ["--only", "p_dynamic"], "COMPATIBLE", 0, set(), {}),
|
||||
("p_vendored", ["--only", "p_vendored"], "COMPATIBLE", 0, set(), {}, {"VENDORED_SDK"}),
|
||||
]
|
||||
|
||||
|
||||
def run_tool(extra: list) -> tuple:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = Path(td) / "report.json"
|
||||
cmd = [sys.executable, str(TOOL), "--plugins", str(PLUGINS),
|
||||
"--json", str(out), *extra]
|
||||
proc = subprocess.run(cmd, cwd=str(REPO), capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=600)
|
||||
rep = json.loads(out.read_text(encoding="utf-8")) if out.is_file() else None
|
||||
return proc.returncode, rep, (proc.stdout or "") + (proc.stderr or "")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failures = 0
|
||||
for case in CASES:
|
||||
name, extra, want_class, want_exit, want_codes, want_summary = case[:6]
|
||||
want_warns = case[6] if len(case) > 6 else set()
|
||||
args = list(extra)
|
||||
if "--sdk" not in args:
|
||||
args = ["--sdk", str(SDK_NEW)] + args
|
||||
code, rep, log = run_tool(args)
|
||||
problems = []
|
||||
if rep is None:
|
||||
problems.append("无 JSON 报告")
|
||||
else:
|
||||
if rep["classification"] != want_class:
|
||||
problems.append(f"分类 {rep['classification']} != {want_class}")
|
||||
if code != want_exit:
|
||||
problems.append(f"退出码 {code} != {want_exit}")
|
||||
got = {f["code"] for r in rep["plugins"] for f in r["findings"]
|
||||
if f["severity"] == "error"}
|
||||
got |= {f["code"] for f in rep["sdk_findings"] if f["severity"] == "error"}
|
||||
missing = want_codes - got
|
||||
if missing:
|
||||
problems.append(f"缺少 error 码 {sorted(missing)}(实际 {sorted(got)})")
|
||||
warns = {f["code"] for r in rep["plugins"] for f in r["findings"]
|
||||
if f["severity"] == "warning"}
|
||||
warns |= {f["code"] for f in rep["sdk_findings"] if f["severity"] == "warning"}
|
||||
miss_warn = want_warns - warns
|
||||
if miss_warn:
|
||||
problems.append(f"缺少 warning 码 {sorted(miss_warn)}(实际 {sorted(warns)})")
|
||||
for key, val in want_summary.items():
|
||||
if rep["summary"].get(key) != val:
|
||||
problems.append(f"summary.{key}={rep['summary'].get(key)} != {val}")
|
||||
if problems:
|
||||
failures += 1
|
||||
print(f"[FAIL] {name}: " + ";".join(problems))
|
||||
print(" " + log.strip().splitlines()[0][:200] if log.strip() else "")
|
||||
else:
|
||||
print(f"[ok] {name:<24}{want_class:<18}exit={code}")
|
||||
|
||||
# 非法 SDK:路径不存在 → 退出码 2
|
||||
code, rep, log = run_tool(["--sdk", str(HERE / "no_such_sdk"), "--only", "p_ok"])
|
||||
if code != 2:
|
||||
failures += 1
|
||||
print(f"[FAIL] sdk_invalid: 退出码 {code} != 2")
|
||||
else:
|
||||
print(f"[ok] {'sdk_invalid':<24}{'SDK_INVALID':<18}exit={code}")
|
||||
|
||||
print("—— 全部用例通过 ——" if not failures else f"—— {failures} 个用例失败 ——")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import importlib
|
||||
mod = importlib.import_module('demo_sdk')
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_dynamic",
|
||||
"name": "p_dynamic",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_dynamic",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
raise RuntimeError('boom on import')
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_import_fail",
|
||||
"name": "p_import_fail",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_import_fail",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from demo_sdk.legacy import export_legacy # noqa: F401
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_legacy",
|
||||
"name": "p_legacy",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_legacy",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from demo_sdk import removed_fn # noqa: F401
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_missing",
|
||||
"name": "p_missing",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_missing",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from demo_sdk.roster import export, RosterRow
|
||||
|
||||
ROWS = [RosterRow(name='a')]
|
||||
export(ROWS)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
raise SystemExit(0)
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_ok",
|
||||
"name": "p_ok",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_ok",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from demo_sdk import roster
|
||||
|
||||
roster.export()
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_old_major",
|
||||
"name": "p_old_major",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_old_major",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^0.9"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from demo_sdk import roster
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
raise SystemExit('selftest boom')
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_selftest_fail",
|
||||
"name": "p_selftest_fail",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_selftest_fail",
|
||||
"ui": false,
|
||||
"fields": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"demo_sdk": {
|
||||
"compat": "^1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
VALUE = 1
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_skip",
|
||||
"name": "p_skip",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_skip",
|
||||
"ui": false,
|
||||
"fields": {}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import demo_sdk
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_undeclared",
|
||||
"name": "p_undeclared",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_undeclared",
|
||||
"ui": false,
|
||||
"fields": {}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""fixture:插件里带了 demo_sdk 副本(应被 VENDORED_SDK 检出)。"""
|
||||
VALUE = 1
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""这是"从 SDK 复制进插件"的副本,仅用于触发 VENDORED_SDK。"""
|
||||
|
||||
|
||||
def export(rows=None):
|
||||
return list(rows or [])
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "p_vendored",
|
||||
"name": "p_vendored",
|
||||
"version": "1.0.0",
|
||||
"description": "fixture p_vendored:插件内复制了 SDK 副本",
|
||||
"ui": false,
|
||||
"fields": {}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "demo_sdk",
|
||||
"version": "1.0.0",
|
||||
"modules": {
|
||||
"demo_sdk": {
|
||||
"exports": [
|
||||
"roster"
|
||||
],
|
||||
"all": [
|
||||
"roster"
|
||||
],
|
||||
"signatures": {}
|
||||
},
|
||||
"demo_sdk.legacy": {
|
||||
"exports": [
|
||||
"export_legacy"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"export_legacy": "()"
|
||||
}
|
||||
},
|
||||
"demo_sdk.roster": {
|
||||
"exports": [
|
||||
"RosterRow",
|
||||
"export"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"export": "(rows=None, dry_run=False)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
__version__ = "1.0.0"
|
||||
from . import roster # noqa: F401
|
||||
|
||||
__all__ = ["roster"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
def export_legacy():
|
||||
return []
|
||||
@@ -0,0 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""演示模块:export() 是稳定 API。"""
|
||||
|
||||
|
||||
class RosterRow(dict):
|
||||
pass
|
||||
|
||||
|
||||
def export(rows=None, dry_run=False):
|
||||
# v1.0.0 签名(1.1.0 起去掉 dry_run)—— 用于 API_SIGNATURE_CHANGED 用例
|
||||
return list(rows or [])
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "demo_sdk",
|
||||
"name": "演示 SDK",
|
||||
"version": "1.0.0",
|
||||
"description": "sdk_compat_check 测试用最小 SDK",
|
||||
"provides": [
|
||||
"demo_sdk"
|
||||
],
|
||||
"deps": [],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "",
|
||||
"api": "api.json"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "demo_sdk",
|
||||
"version": "1.1.0",
|
||||
"modules": {
|
||||
"demo_sdk": {
|
||||
"exports": [
|
||||
"roster"
|
||||
],
|
||||
"all": [
|
||||
"roster"
|
||||
],
|
||||
"signatures": {}
|
||||
},
|
||||
"demo_sdk.roster": {
|
||||
"exports": [
|
||||
"RosterRow",
|
||||
"export"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"export": "(rows=None)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
__version__ = "1.1.0"
|
||||
from . import roster # noqa: F401
|
||||
|
||||
__all__ = ["roster"]
|
||||
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""演示模块:export() 是稳定 API。"""
|
||||
|
||||
|
||||
class RosterRow(dict):
|
||||
pass
|
||||
|
||||
|
||||
def export(rows=None):
|
||||
return list(rows or [])
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "demo_sdk",
|
||||
"name": "演示 SDK",
|
||||
"version": "1.1.0",
|
||||
"description": "sdk_compat_check 测试用最小 SDK",
|
||||
"provides": [
|
||||
"demo_sdk"
|
||||
],
|
||||
"deps": [],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "",
|
||||
"api": "api.json"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "demo_sdk",
|
||||
"version": "2.0.0",
|
||||
"modules": {
|
||||
"demo_sdk": {
|
||||
"exports": [
|
||||
"roster"
|
||||
],
|
||||
"all": [
|
||||
"roster"
|
||||
],
|
||||
"signatures": {}
|
||||
},
|
||||
"demo_sdk.roster": {
|
||||
"exports": [
|
||||
"RosterRow",
|
||||
"export"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"export": "(rows=None)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
__version__ = "2.0.0"
|
||||
from . import roster # noqa: F401
|
||||
|
||||
__all__ = ["roster"]
|
||||
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""演示模块:export() 是稳定 API。"""
|
||||
|
||||
|
||||
class RosterRow(dict):
|
||||
pass
|
||||
|
||||
|
||||
def export(rows=None):
|
||||
return list(rows or [])
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "demo_sdk",
|
||||
"name": "演示 SDK",
|
||||
"version": "2.0.0",
|
||||
"description": "sdk_compat_check 测试用最小 SDK",
|
||||
"provides": [
|
||||
"demo_sdk"
|
||||
],
|
||||
"deps": [],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "",
|
||||
"api": "api.json"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""临时校验:xq0079 人工登录通道能否打开登录页并预填账号密码(8 秒后自动超时,用完即删)。"""
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"xq0079", os.path.join(PLUGIN_DIR, "__init__.py"),
|
||||
submodule_search_locations=[PLUGIN_DIR])
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules["xq0079"] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
from xq0079 import config # noqa: E402
|
||||
from xq0079.data import tianque_browser # noqa: E402
|
||||
|
||||
config.set_log(lambda m, level="INFO": print(f"[{level}] {m}", flush=True))
|
||||
|
||||
print("登录选项:", config.LOGIN_MODE_CHOICES)
|
||||
result = tianque_browser.manual_login("13629779871", "Qq201201", wait_seconds=8)
|
||||
print("结果:", result.get("success"), result.get("message"))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""临时校验:人工登录是否使用按账号隔离的浏览器用户目录(8 秒后超时,用完即删)。"""
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"xq0079", os.path.join(PLUGIN_DIR, "__init__.py"),
|
||||
submodule_search_locations=[PLUGIN_DIR])
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules["xq0079"] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
from xq0079 import config # noqa: E402
|
||||
from xq0079.data import tianque_browser # noqa: E402
|
||||
|
||||
config.set_log(lambda m, level="INFO": print(f"[{level}] {m}", flush=True))
|
||||
config.set_debug(True)
|
||||
|
||||
print("profile 根目录:", config.BROWSER_PROFILE_ROOT)
|
||||
print("账号A 目录:", config.get_profile_dir("13629779871"))
|
||||
print("账号B 目录:", config.get_profile_dir("17318298162"))
|
||||
|
||||
result = tianque_browser.manual_login("13629779871", "Qq201201", wait_seconds=6)
|
||||
print("结果:", result.get("success"), result.get("message"))
|
||||
print("临时公共目录是否被使用:", os.path.join(os.environ.get("TEMP", ""), "DrissionPage", "userData"))
|
||||
@@ -0,0 +1,40 @@
|
||||
"""临时:从已抓到的 packets.jsonl 里提取导出链路报文(紧凑版,用完即删)。"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "capture", "20261106-093603")
|
||||
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_dump_export.txt")
|
||||
|
||||
WANT = ("exportNew", "download/polling", "download/downLoadList", "download/look",
|
||||
"download/read", "download/downLoad/")
|
||||
seen = {}
|
||||
order = []
|
||||
for raw in open(os.path.join(ROOT, "packets.jsonl"), encoding="utf-8"):
|
||||
rec = json.loads(raw)
|
||||
path = rec["path"]
|
||||
if not any(k in path for k in WANT):
|
||||
continue
|
||||
key = (rec["method"], path if "download" not in path else path.split("/read/")[0].split("/downLoad/")[0])
|
||||
if key in seen:
|
||||
continue
|
||||
seen[key] = rec
|
||||
order.append(key)
|
||||
|
||||
lines = []
|
||||
for key in order:
|
||||
rec = seen[key]
|
||||
lines.append("-" * 90)
|
||||
lines.append(f"{rec['method']} {rec['url']}")
|
||||
lines.append(f" POST: {(rec['postData'] or '')[:900]}")
|
||||
body = rec.get("body") or ""
|
||||
lines.append(f" RESP({rec['size']}B) ct={rec['contentType']} bin={rec['binaryFile']}")
|
||||
lines.append(f" {body[:900]}")
|
||||
|
||||
text = "\n".join(lines)
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
print(f"wrote {len(text)} chars, {len(order)} unique")
|
||||
@@ -0,0 +1,56 @@
|
||||
"""临时探针:拉前端 bundle,列出全部业务接口路径 + 报表相关路由(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
BASE = "https://mch-web.tianquetech.com"
|
||||
OUT = os.path.join(os.environ.get("TEMP", "."), "tianque_js")
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
|
||||
class Low(HTTPAdapter):
|
||||
def init_poolmanager(self, *a, **kw):
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
kw["ssl_context"] = ctx
|
||||
return super().init_poolmanager(*a, **kw)
|
||||
|
||||
|
||||
s = requests.Session()
|
||||
s.mount("https://", Low())
|
||||
s.headers.update({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36"})
|
||||
r = s.get(BASE + "/login", timeout=30)
|
||||
srcs = re.findall(r'<script[^>]+src="([^"]+)"', r.text)
|
||||
text = ""
|
||||
for src in srcs:
|
||||
url = src if src.startswith("http") else BASE + ("" if src.startswith("/") else "/") + src
|
||||
text += s.get(url, timeout=30).text
|
||||
|
||||
cache = os.path.join(OUT, "all.js")
|
||||
open(cache, "w", encoding="utf-8", errors="replace").write(text)
|
||||
|
||||
apis = sorted(set(re.findall(r'"(/?management/easypay/api/[A-Za-z0-9_/\-]+)"', text)))
|
||||
print(f"### 接口共 {len(apis)}")
|
||||
for p in apis:
|
||||
print(" " + p)
|
||||
|
||||
KW = ("report", "bill", "settle", "download", "export", "tranInfo", "statis", "sum", "statement", "check")
|
||||
print("\n### 报表/对账/导出相关")
|
||||
for p in apis:
|
||||
if any(k.lower() in p.lower() for k in KW):
|
||||
print(" " + p)
|
||||
|
||||
routes = sorted(set(re.findall(r'path:"(/[A-Za-z0-9_/\-]{2,40})"', text)))
|
||||
print(f"\n### 路由共 {len(routes)}")
|
||||
for p in routes:
|
||||
if any(k in p.lower() for k in ("report", "bill", "settle", "tran", "download", "statis", "check", "account")):
|
||||
print(" " + p)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""临时探针:只看报表/对账/导出相关接口与路由(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
cache = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "all.js")
|
||||
text = open(cache, encoding="utf-8", errors="replace").read()
|
||||
|
||||
apis = sorted(set(re.findall(r'"(/?management/easypay/api/[A-Za-z0-9_/\-]+)"', text)))
|
||||
KW = ("report", "bill", "settle", "download", "export", "tranInfo", "statis", "sum", "statement", "check", "voucher", "order")
|
||||
print("### 报表/对账/导出相关接口")
|
||||
for p in apis:
|
||||
if any(k.lower() in p.lower() for k in KW):
|
||||
print(" " + p)
|
||||
|
||||
routes = sorted(set(re.findall(r'path:"(/[A-Za-z0-9_/\-]{2,60})"', text)))
|
||||
print(f"\n### 相关路由(共 {len(routes)} 条路由)")
|
||||
for p in routes:
|
||||
if any(k in p.lower() for k in ("report", "bill", "settle", "tran", "download", "statis", "check", "voucher", "order")):
|
||||
print(" " + p)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""临时验证:故意提交错误验证码,看服务端错误码,用于区分「验证码错」和「密码错」(用完即删)。"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import tianque_login_test as m
|
||||
|
||||
URL_NEW = "/management/easypay/api/user/transForm/login"
|
||||
|
||||
s = m.new_session()
|
||||
key, img = m.fetch_captcha(s)
|
||||
print("imageKey =", key)
|
||||
|
||||
for url, label in ((URL_NEW, "transForm/login"), (m.URL_LOGIN, "bankLogin/loginByAccount")):
|
||||
resp = m.post_json(s, url, {
|
||||
"loginAcc": m.ACCOUNT,
|
||||
"loginPwd": m.enc_password(m.PASSWORD),
|
||||
"imageCode": "0000",
|
||||
"imageKey": key,
|
||||
})
|
||||
print(f"[{label}] 错误验证码 -> {json.dumps(resp, ensure_ascii=False)[:300]}")
|
||||
key, img = m.fetch_captcha(s)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""临时验证:对比「扁平 body」与「{header,data} 信封 body」两种提交方式(用完即删)。"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import tianque_login_test as m
|
||||
|
||||
URL_NEW = "/management/easypay/api/user/transForm/login"
|
||||
URL_OLD = "/management/easypay/api/bankLogin/loginByAccount"
|
||||
|
||||
|
||||
def submit(session, url, wrapped, code, key):
|
||||
inner = {
|
||||
"loginAcc": m.ACCOUNT.strip(),
|
||||
"loginPwd": m.enc_password(m.PASSWORD.strip()),
|
||||
"imageCode": code,
|
||||
"imageKey": key,
|
||||
}
|
||||
payload = {"header": {"sysType": "pc"}, "data": inner} if wrapped else inner
|
||||
return m.post_json(session, url, payload)
|
||||
|
||||
|
||||
for url, wrapped in ((URL_NEW, True), (URL_NEW, False), (URL_OLD, True)):
|
||||
s = m.new_session()
|
||||
s.headers["omp_sui_pc"] = "pc"
|
||||
key, img = m.fetch_captcha(s)
|
||||
code = m.ocr_image(img)
|
||||
ok = m.ocr_code_ok(code)
|
||||
resp = submit(s, url, wrapped, code, key)
|
||||
print(f"\n[{url}] wrapped={wrapped} OCR={code!r} 格式OK={ok}")
|
||||
print(json.dumps(resp, ensure_ascii=False)[:400])
|
||||
@@ -0,0 +1,60 @@
|
||||
"""临时探针:抓前端 JS bundle,定位登录密码加密实现与请求字段(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
BASE = "https://mch-web.tianquetech.com"
|
||||
OUT = os.path.join(os.environ.get("TEMP", "."), "tianque_js")
|
||||
|
||||
|
||||
class Low(HTTPAdapter):
|
||||
def init_poolmanager(self, *a, **kw):
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
kw["ssl_context"] = ctx
|
||||
return super().init_poolmanager(*a, **kw)
|
||||
|
||||
|
||||
s = requests.Session()
|
||||
s.mount("https://", Low())
|
||||
s.headers.update({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36"})
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
r = s.get(BASE + "/login", timeout=30)
|
||||
print("login page", r.status_code, len(r.text))
|
||||
open(os.path.join(OUT, "login.html"), "w", encoding="utf-8").write(r.text)
|
||||
|
||||
srcs = re.findall(r'<script[^>]+src="([^"]+)"', r.text)
|
||||
print("scripts:", len(srcs))
|
||||
hits = []
|
||||
for src in srcs:
|
||||
url = src if src.startswith("http") else BASE + ("" if src.startswith("/") else "/") + src
|
||||
try:
|
||||
resp = s.get(url, timeout=30)
|
||||
except Exception as exc:
|
||||
print("skip", url, exc)
|
||||
continue
|
||||
name = os.path.basename(url.split("?")[0])
|
||||
path = os.path.join(OUT, name)
|
||||
open(path, "w", encoding="utf-8", errors="replace").write(resp.text)
|
||||
print(f" {name} {resp.status_code} {len(resp.text)}")
|
||||
for kw in ("loginPwd", "loginByAccount", "abcdefgabcdefg12", "imageKey"):
|
||||
if kw in resp.text:
|
||||
hits.append((name, kw))
|
||||
|
||||
print("kw hits:", hits)
|
||||
for name, kw in hits:
|
||||
text = open(os.path.join(OUT, name), encoding="utf-8", errors="replace").read()
|
||||
for m in re.finditer(kw, text):
|
||||
seg = text[max(0, m.start() - 400): m.start() + 400]
|
||||
print("=" * 30, name, kw)
|
||||
print(seg.replace("\n", " "))
|
||||
@@ -0,0 +1,31 @@
|
||||
"""临时探针 2:分析已下载 bundle 中的加密实现与接口地址(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
print("len", len(text))
|
||||
|
||||
|
||||
def show(kw, before=600, after=1200, limit=3):
|
||||
print("\n" + "#" * 40, kw)
|
||||
n = 0
|
||||
for m in re.finditer(re.escape(kw), text):
|
||||
print("-" * 20, f"@{m.start()}")
|
||||
print(text[max(0, m.start() - before): m.start() + after].replace("\n", " "))
|
||||
n += 1
|
||||
if n >= limit:
|
||||
break
|
||||
if not n:
|
||||
print("(not found)")
|
||||
|
||||
|
||||
show("abcdefgabcdefg12")
|
||||
show("transForm/login", 800, 400)
|
||||
show("bankLogin", 300, 300, 2)
|
||||
show("mode:r.ECB", 600, 300, 2)
|
||||
show("ECB", 300, 300, 3)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""临时探针 3:列出 bundle 里所有接口路径 + transForm/login 提交上下文(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
|
||||
paths = sorted(set(re.findall(r'"(/management/easypay/api/[^"]+)"', text)))
|
||||
print("### 接口路径", len(paths))
|
||||
for p in paths:
|
||||
print(" ", p)
|
||||
|
||||
print("\n### bankLogin 相关")
|
||||
for p in paths:
|
||||
if "bankLogin" in p:
|
||||
print(" HIT", p)
|
||||
|
||||
print("\n### getImage 定义")
|
||||
for m in re.finditer(r'getImage', text):
|
||||
seg = text[max(0, m.start() - 200): m.start() + 400]
|
||||
if "url" in seg or "/api/" in seg:
|
||||
print("-" * 20, m.start())
|
||||
print(seg.replace("\n", " "))
|
||||
|
||||
print("\n### transForm/login 上下文")
|
||||
for m in re.finditer(r'transForm/login', text):
|
||||
print("-" * 20, m.start())
|
||||
print(text[max(0, m.start() - 1500): m.start() + 300].replace("\n", " "))
|
||||
@@ -0,0 +1,29 @@
|
||||
"""临时探针 4:登录表单字段名、请求头封装、transForm/login 失败分支(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
|
||||
|
||||
def show(kw, before=300, after=900, limit=4, label=None):
|
||||
print("\n" + "#" * 30, label or kw)
|
||||
n = 0
|
||||
for m in re.finditer(re.escape(kw), text):
|
||||
print("-" * 15, f"@{m.start()}")
|
||||
print(text[max(0, m.start() - before): m.start() + after].replace("\n", " "))
|
||||
n += 1
|
||||
if n >= limit:
|
||||
break
|
||||
if not n:
|
||||
print("(not found)")
|
||||
|
||||
|
||||
show('"imageCode"', 400, 900, 4, "imageCode 字段")
|
||||
show("channel", 300, 500, 3, "channel 请求头")
|
||||
show("sysType", 300, 400, 3, "sysType 请求头")
|
||||
show("errorType", 400, 600, 5, "errorType 处理")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""临时探针 5:请求头封装(channel / sysType 等)(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
|
||||
print("### channel 上下文")
|
||||
for m in re.finditer(r'channel', text):
|
||||
seg = text[max(0, m.start() - 250): m.start() + 250]
|
||||
if "header" in seg or "WELIFE" in seg or "sysType" in seg:
|
||||
print("-" * 15, m.start())
|
||||
print(seg.replace("\n", " "))
|
||||
|
||||
print("\n### sysType 上下文")
|
||||
for m in re.finditer(r'sysType', text):
|
||||
seg = text[max(0, m.start() - 250): m.start() + 250]
|
||||
if "header" in seg or "pc" in seg:
|
||||
print("-" * 15, m.start())
|
||||
print(seg.replace("\n", " "))
|
||||
@@ -0,0 +1,10 @@
|
||||
"""临时探针 6:打印请求封装函数全文,确认 POST body 信封结构(用完即删)。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
print(text[5419000:5427000])
|
||||
@@ -0,0 +1,14 @@
|
||||
"""临时探针 7:探针接口参数(用完即删)。"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
JS = os.path.join(os.environ.get("TEMP", "."), "tianque_js", "umi.4ba392fc.js")
|
||||
text = open(JS, encoding="utf-8", errors="replace").read()
|
||||
|
||||
for m in re.finditer(r'queryTranSumByDate', text):
|
||||
print("-" * 20, m.start())
|
||||
print(text[max(0, m.start() - 700): m.start() + 700].replace("\n", " "))
|
||||
@@ -0,0 +1,11 @@
|
||||
"""临时验证:用前端真实接口 transForm/login 提交一次(用完即删)。"""
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import tianque_login_test as m
|
||||
|
||||
m.MAX_ATTEMPTS = int(sys.argv[1]) if len(sys.argv) > 1 else 2
|
||||
m.URL_LOGIN = "/management/easypay/api/user/transForm/login"
|
||||
sys.exit(0 if m.main() else 1)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""临时验证:token 探针接口的 body 形态(flat / 信封)(用完即删)。"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import tianque_login_test as m
|
||||
|
||||
s = m.new_session()
|
||||
key, img = m.fetch_captcha(s)
|
||||
code = m.ocr_image(img)
|
||||
resp = m.do_login(s, m.ACCOUNT, m.PASSWORD, key, code)
|
||||
data = (resp.get("data") or {}).get("users") or []
|
||||
if not data:
|
||||
print("登录失败", json.dumps(resp, ensure_ascii=False)[:200])
|
||||
sys.exit(1)
|
||||
token = data[0]["token"]
|
||||
s.headers["token"] = token
|
||||
print("token =", token[:12], "...")
|
||||
|
||||
for label, payload in (
|
||||
("信封", m.envelope({"queryType": "D"})),
|
||||
("扁平", {"queryType": "D"}),
|
||||
("日期+信封", m.envelope({"queryType": "D", "startDate": "", "endDate": ""})),
|
||||
):
|
||||
r = m.post_json(s, m.URL_PROBE, payload)
|
||||
print(f"[{label}] {json.dumps(r, ensure_ascii=False)[:200]}")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""临时联调:按壳子方式加载 xq0079 并跑 run(login_mode=人工登录,缓存 token 有效时应直接复用)。"""
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
|
||||
class FakeCtx:
|
||||
def log(self, msg, level="INFO"):
|
||||
print(f"[{level}] {msg}", flush=True)
|
||||
|
||||
def progress(self, pct):
|
||||
pass
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"xq0079", os.path.join(PLUGIN_DIR, "__init__.py"),
|
||||
submodule_search_locations=[PLUGIN_DIR])
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules["xq0079"] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
plugin = mod.PLUGINS.find("xq0079")
|
||||
fields = {
|
||||
"tq_account1": "13629779871",
|
||||
"tq_password1": "Qq201201",
|
||||
"tq_account2": "",
|
||||
"tq_password2": "",
|
||||
"login_mode": "人工登录",
|
||||
"date_from": "",
|
||||
"date_to": "",
|
||||
"save_dir": os.path.join(tempfile.gettempdir(), "xq0079_test"),
|
||||
"debug_mode": False,
|
||||
}
|
||||
result = plugin.run(fields, FakeCtx())
|
||||
print("\nsummary:", result.get("summary"))
|
||||
for note in result.get("notes") or []:
|
||||
print("note:", note)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""临时冒烟:小范围跑一次报表监听(1 个路由、短超时),验证监听链路(用完即删)。"""
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import tianque_report_capture as R
|
||||
|
||||
R.MODE = "auto"
|
||||
R.REPORT_ROUTES = [("交易趋势", "/report/trend")]
|
||||
R.PAGE_WAIT = 8
|
||||
R.PAGE_LISTEN = 12
|
||||
R.IDLE_SECONDS = 6
|
||||
R.MAX_SECONDS = 60
|
||||
sys.exit(0 if R.main() else 1)
|
||||
@@ -0,0 +1,48 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""临时校验:目标变更记录表只认当天业务日期。"""
|
||||
import importlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import date, timedelta
|
||||
|
||||
_REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.join(_REPO, "desktop", "electron-shell", "python"))
|
||||
sys.path.insert(0, os.path.join(_REPO, "plugins", "XQ0001-0100"))
|
||||
cfg = importlib.import_module("XQ0002 雇主险增减操作.config")
|
||||
|
||||
today = date.today()
|
||||
yesterday = today - timedelta(days=1)
|
||||
root = tempfile.mkdtemp()
|
||||
folder = os.path.join(root, "三十七度")
|
||||
os.makedirs(folder)
|
||||
|
||||
def touch(name):
|
||||
p = os.path.join(folder, name)
|
||||
with open(p, "wb") as f:
|
||||
f.write(b"x")
|
||||
return p
|
||||
|
||||
old = touch(f"三十七度-雇主险变更记录-{yesterday.strftime('%Y.%m.%d')}.xlsx")
|
||||
old2 = touch("三十七度-雇主险变更记录-7.23.xlsx")
|
||||
try:
|
||||
cfg.find_target_file(folder)
|
||||
print("FAIL: 只有历史文件时未报错")
|
||||
except FileNotFoundError as e:
|
||||
print("PASS: 只有历史文件时报错 ->", str(e)[:90])
|
||||
|
||||
today_file = touch(f"三十七度-雇主险变更记录-{today.strftime('%Y.%m.%d')}.xlsx")
|
||||
picked = cfg.find_target_file(folder)
|
||||
print("PASS" if picked == today_file else "FAIL", ": 命中当天文件 ->", os.path.basename(picked))
|
||||
|
||||
cfg.set_base_dir(root)
|
||||
cat = cfg.get_category("三十七度")
|
||||
print("PASS" if cfg.category_target_file(cat) == today_file else "FAIL", ": category_target_file 同口径")
|
||||
|
||||
pad = touch(f"三十七度-雇主险变更记录-{today.year}.{today.month}.{today.day}.xlsx")
|
||||
print("PASS" if cfg.find_target_file(folder).endswith(pad.split(os.sep)[-1]) else "FAIL",
|
||||
": 不补零当天文件也可识别")
|
||||
|
||||
os.remove(pad)
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- 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())
|
||||
@@ -0,0 +1,172 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 对拍:legacy 直连(pyodbc)vs SDK WCF 通道,验证会员卡余额/明细口径一致。
|
||||
|
||||
余额:legacy 多语句批(#临时表)跑在 jgmember ↔ 新单条 CTE 跑在 golden(四段式)
|
||||
明细:同一条 DETAIL_SQL,两条通道各跑一次,逐列比对
|
||||
支付方式:同上
|
||||
|
||||
用法(项目根,.venv 已装 pyodbc):
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\compare_member.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(BASE, "..", ".."))
|
||||
SDK_ROOT = os.path.join(ROOT, "libs", "hotel_report")
|
||||
sys.path.insert(0, SDK_ROOT)
|
||||
sys.path.insert(0, os.path.join(SDK_ROOT, "legacy"))
|
||||
|
||||
# legacy 直连通道(只读)
|
||||
os.environ.setdefault(
|
||||
"GS_CONN",
|
||||
"DRIVER={SQL Server};SERVER=172.22.43.254,1433;UID=sa;PWD=Goldensoft5829;DATABASE=golden")
|
||||
os.environ["GS_SKIP_CLIENT_CHECK"] = "1"
|
||||
|
||||
from hotel_report import HotelConfig, latest_shift_time # noqa: E402
|
||||
import balance_cte_probe as probe # noqa: E402
|
||||
import db # noqa: E402
|
||||
import export_member # noqa: E402
|
||||
|
||||
|
||||
def norm(v):
|
||||
"""两条通道的值归一化:数值→float(4),时间→'YYYY-MM-DD HH:MM:SS',其余→str。"""
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
if isinstance(v, (int, float)):
|
||||
return round(float(v), 4)
|
||||
if isinstance(v, str):
|
||||
s = v.strip()
|
||||
if s == "":
|
||||
return None
|
||||
if len(s) >= 19 and s[4] == "-" and s[10] in "T ":
|
||||
return s[:10] + " " + s[11:19]
|
||||
try:
|
||||
return round(float(s), 4) # WCF 通道的数值列是字符串
|
||||
except ValueError:
|
||||
return s
|
||||
try:
|
||||
return round(float(v), 4)
|
||||
except (TypeError, ValueError):
|
||||
return str(v)
|
||||
|
||||
|
||||
def compare_balance(cfg, end):
|
||||
print("\n===== 余额对拍")
|
||||
t0 = time.time()
|
||||
old = export_member.fetch_balance(end)
|
||||
print(f" legacy 直连: {len(old)} 行 / {time.time() - t0:.1f}s")
|
||||
t0 = time.time()
|
||||
new = probe.raw_query(";" + probe.BALANCE_CTE.format(endtime=end, top=""), cfg)
|
||||
print(f" WCF CTE : {len(new)} 行 / {time.time() - t0:.1f}s")
|
||||
|
||||
def agg_old(rows):
|
||||
out = {}
|
||||
for d in rows:
|
||||
k = str(d["memberid"]).strip()
|
||||
a = out.setdefault(k, [0, 0.0, 0.0, 0.0, 0.0])
|
||||
a[0] += 1
|
||||
for i, key in ((1, "leavemoney"), (2, "griftleave"), (3, "factleave"), (4, "partition")):
|
||||
a[i] += float(d[key] or 0)
|
||||
return out
|
||||
|
||||
def agg_new(rows):
|
||||
out = {}
|
||||
for d in rows:
|
||||
k = str(d["Memberid"]).strip()
|
||||
a = out.setdefault(k, [0, 0.0, 0.0, 0.0, 0.0])
|
||||
a[0] += 1
|
||||
for i, key in ((1, "leavemoney"), (2, "griftleave"), (3, "factleave"),
|
||||
(4, "PartitionLeaveMoney")):
|
||||
a[i] += float(d[key] or 0)
|
||||
return out
|
||||
|
||||
a, b = agg_old(old), agg_new(new)
|
||||
diff = []
|
||||
for k in set(a) | set(b):
|
||||
x = a.get(k, [0, 0.0, 0.0, 0.0, 0.0])
|
||||
y = b.get(k, [0, 0.0, 0.0, 0.0, 0.0])
|
||||
if x[0] != y[0] or any(abs(x[i] - y[i]) > 0.011 for i in (1, 2, 3, 4)):
|
||||
diff.append((k, x, y))
|
||||
print(f" 会员数 legacy={len(a)} wcf={len(b)};差异 {len(diff)} 个会员")
|
||||
for k, x, y in diff[:10]:
|
||||
print(f" {k}: legacy={x} wcf={y}")
|
||||
tot_old, tot_new = sum(v[1] for v in a.values()), sum(v[1] for v in b.values())
|
||||
print(f" 卡内余额合计 legacy={tot_old:,.2f} wcf={tot_new:,.2f} 差={tot_new - tot_old:+.2f}")
|
||||
return len(diff) == 0
|
||||
|
||||
|
||||
def compare_rows(label, old_rows, new_rows, key_cols):
|
||||
print(f"\n===== {label} 对拍")
|
||||
print(f" 行数 legacy={len(old_rows)} wcf={len(new_rows)}")
|
||||
if len(old_rows) != len(new_rows):
|
||||
print(" 行数不一致,跳过逐行比对")
|
||||
return False
|
||||
cols = list(new_rows[0].keys()) if new_rows else []
|
||||
none_cnt = {}
|
||||
diff = 0
|
||||
for i, (o, n) in enumerate(zip(old_rows, new_rows)):
|
||||
for j, col in enumerate(cols):
|
||||
vo, vn = norm(o[j]), norm(n[col])
|
||||
if vo == vn:
|
||||
continue
|
||||
if isinstance(vo, float) and isinstance(vn, float) and abs(vo - vn) < 0.011:
|
||||
continue
|
||||
diff += 1
|
||||
if diff <= 8:
|
||||
print(f" 行{i} 列[{j}]{col}: legacy={vo!r} wcf={vn!r}")
|
||||
none_cnt[col] = none_cnt.get(col, 0) + 1
|
||||
print(f" 列={len(cols)};差异单元格 {diff}")
|
||||
if none_cnt:
|
||||
print(" 差异列分布: " + ", ".join(f"{k}×{v}" for k, v in none_cnt.items()))
|
||||
return diff == 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
cfg = HotelConfig.resolve(timeout=300)
|
||||
today = datetime.now()
|
||||
cur = latest_shift_time(cfg, today)
|
||||
prev = latest_shift_time(cfg, today.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
- __import__("datetime").timedelta(days=1))
|
||||
end = cur["latest"] or today.strftime("%Y-%m-%d %H:%M:%S")
|
||||
start = prev["latest"] or (today - __import__("datetime").timedelta(days=1)).strftime(
|
||||
"%Y-%m-%d 00:00:00")
|
||||
print(f"WCF: {cfg.wcf_url}\n窗口: {start} ~ {end}")
|
||||
|
||||
ok1 = compare_balance(cfg, end)
|
||||
|
||||
detail_sql = export_member.DETAIL_SQL.format(starttime=start, endtime=end, feetype="全部")
|
||||
t0 = time.time()
|
||||
old = db.fetch_all(detail_sql)
|
||||
print(f"\n明细 legacy 直连: {len(old)} 行 / {time.time() - t0:.1f}s")
|
||||
t0 = time.time()
|
||||
new = probe.raw_query(detail_sql, cfg)
|
||||
print(f"明细 WCF : {len(new)} 行 / {time.time() - t0:.1f}s")
|
||||
ok2 = compare_rows("明细", old, new, ("memberid", "feeindate"))
|
||||
|
||||
pay_sql = ("select a.Billid, b.MethodName, sum(b.PayAmount) as amt "
|
||||
"from jgmember.dbo.dt_membercardcomein a "
|
||||
"left join v_snchangeclass b on b.BillId = a.Billid "
|
||||
"where a.feeindate >= ? and a.feeindate <= ? and a.feetype = '充值' "
|
||||
"group by a.Billid, b.MethodName")
|
||||
old_pay = db.fetch_all(pay_sql, start, end)
|
||||
new_pay = probe.raw_query(pay_sql.replace("?", f"'{start}'", 1).replace("?", f"'{end}'", 1), cfg)
|
||||
print(f"\n支付方式 legacy={len(old_pay)} wcf={len(new_pay)}")
|
||||
ok3 = compare_rows("支付方式", old_pay, new_pay, ("Billid", "MethodName"))
|
||||
|
||||
print(f"\n结论: 余额={'一致' if ok1 else '有差异'} 明细={'一致' if ok2 else '有差异'} "
|
||||
f"支付方式={'一致' if ok3 else '有差异'}")
|
||||
return 0 if (ok1 and ok2 and ok3) else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,155 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 端到端验收:SDK `hotel_report` 0.3.0 会员卡统计 vs legacy 直连,并对产出 xlsx 做结构校验。
|
||||
|
||||
覆盖:
|
||||
1. settle_window(前一日最晚总交班 ~ 当日最晚总交班)
|
||||
2. 余额:SDK collect vs legacy fetch_balance(按会员聚合逐项比对)
|
||||
3. 明细:SDK collect vs legacy fetch_detail(36 列逐格比对)
|
||||
4. export_member 产出两份 xlsx:行数 / 表头 / 合计行位置
|
||||
|
||||
用法(项目根,.venv 已装 pyodbc):
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\e2e_sdk_check.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(BASE, "..", ".."))
|
||||
SDK_ROOT = os.path.join(ROOT, "libs", "hotel_report")
|
||||
sys.path.insert(0, SDK_ROOT)
|
||||
sys.path.insert(0, os.path.join(SDK_ROOT, "legacy"))
|
||||
sys.path.insert(0, BASE)
|
||||
|
||||
os.environ.setdefault(
|
||||
"GS_CONN",
|
||||
"DRIVER={SQL Server};SERVER=172.22.43.254,1433;UID=sa;PWD=Goldensoft5829;DATABASE=golden")
|
||||
os.environ["GS_SKIP_CLIENT_CHECK"] = "1"
|
||||
|
||||
import hotel_report # noqa: E402
|
||||
import export_member # noqa: E402
|
||||
from compare_member import norm # noqa: E402
|
||||
|
||||
|
||||
def check_balance(cfg, w) -> bool:
|
||||
t0 = time.time()
|
||||
table = hotel_report.collect.collect_member_balance(w["end"], cfg)
|
||||
print(f" SDK 余额: {table.count} 人 / {time.time() - t0:.1f}s,卡内合计 {table.totals['卡内余额']:,.2f}")
|
||||
t0 = time.time()
|
||||
old = export_member.fetch_balance(w["end"])
|
||||
print(f" legacy余额: {len(old)} 人 / {time.time() - t0:.1f}s")
|
||||
|
||||
if table.count != len(old):
|
||||
print(f" ✗ 行数不一致 SDK={table.count} legacy={len(old)}")
|
||||
return False
|
||||
|
||||
old_agg: dict = {}
|
||||
for d in old:
|
||||
key = str(d["memberid"]).strip()
|
||||
item = old_agg.setdefault(key, [0, 0.0, 0.0, 0.0])
|
||||
item[0] += 1
|
||||
item[1] += float(d["leavemoney"] or 0)
|
||||
item[2] += float(d["griftleave"] or 0)
|
||||
item[3] += float(d["factleave"] or 0)
|
||||
new_agg: dict = {}
|
||||
for r in table.rows:
|
||||
item = new_agg.setdefault(r.member_id.strip(), [0, 0.0, 0.0, 0.0])
|
||||
item[0] += 1
|
||||
item[1] += float(r.leavemoney or 0)
|
||||
item[2] += float(r.griftleave or 0)
|
||||
item[3] += float(r.factleave or 0)
|
||||
|
||||
diff = [k for k in set(old_agg) | set(new_agg)
|
||||
if old_agg.get(k, [0, 0, 0, 0])[0] != new_agg.get(k, [0, 0, 0, 0])[0]
|
||||
or any(abs(old_agg.get(k, [0, 0, 0, 0])[i] - new_agg.get(k, [0, 0, 0, 0])[i]) > 0.011
|
||||
for i in (1, 2, 3))]
|
||||
print(f" 差异会员: {len(diff)}" + (f",示例 {diff[:3]}" if diff else ""))
|
||||
return not diff
|
||||
|
||||
|
||||
def check_detail(cfg, w) -> bool:
|
||||
t0 = time.time()
|
||||
table = hotel_report.collect.collect_member_detail(w["start"], w["end"], cfg)
|
||||
print(f" SDK 明细: {table.count} 行 × {len(table.headers)} 列 / {time.time() - t0:.1f}s")
|
||||
old = export_member.fetch_detail(w["start"], w["end"])
|
||||
print(f" legacy明细: {len(old)} 行 / 36 列")
|
||||
if table.count != len(old):
|
||||
print(f" ✗ 行数不一致 SDK={table.count} legacy={len(old)}")
|
||||
return False
|
||||
|
||||
diff = 0
|
||||
for i, (o, n) in enumerate(zip(old, table.rows)):
|
||||
for j in range(36):
|
||||
a, b = norm(o[j]), norm(n.values[j])
|
||||
if a == b:
|
||||
continue
|
||||
if isinstance(a, float) and isinstance(b, float) and abs(a - b) < 0.011:
|
||||
continue
|
||||
diff += 1
|
||||
if diff <= 5:
|
||||
print(f" 行{i} 列{j}: legacy={a!r} sdk={b!r}")
|
||||
print(f" 差异单元格: {diff}")
|
||||
return diff == 0
|
||||
|
||||
|
||||
def check_files(res) -> bool:
|
||||
"""write_only 产物没有 dimension,直接读 sheet XML 数行 / 表头非空单元格。"""
|
||||
import re
|
||||
import zipfile
|
||||
ok = True
|
||||
for path in res["files"]:
|
||||
name = os.path.basename(path)
|
||||
with zipfile.ZipFile(path) as z:
|
||||
xml = z.read("xl/worksheets/sheet1.xml").decode("utf-8")
|
||||
rows = xml.count("<row ")
|
||||
row_xml = re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)
|
||||
if "余额" in name:
|
||||
head = row_xml[2] # 第 3 行才是列名
|
||||
expect_rows = res["balance"]["count"] + 4 # 标题 + 区间 + 表头 + 数据 + 合计
|
||||
expect_cells = 11 # B~L
|
||||
else:
|
||||
head = row_xml[1] # 第 2 行是列名
|
||||
expect_rows = res["detail"]["count"] + 3 # 标题 + 表头 + 数据 + 合计
|
||||
expect_cells = len(res["detail"]["headers"])
|
||||
cells = head.count("<c ")
|
||||
good = rows == expect_rows and cells == expect_cells
|
||||
print(f" {name}: {rows} 行 / 表头 {cells} 个非空单元格"
|
||||
f"(期望 {expect_rows} 行 / {expect_cells}){'OK' if good else '✗'}")
|
||||
ok &= good
|
||||
return ok
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
cfg = hotel_report.HotelConfig.resolve(timeout=300)
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
w = hotel_report.settle_window(cfg, today)
|
||||
print(f"WCF: {cfg.wcf_url}")
|
||||
print(f"结算窗口: {w['start']} ~ {w['end']}(closed={w['closed']})")
|
||||
if not w["closed"]:
|
||||
print("✗ 当日尚未交班,无法验收")
|
||||
return 1
|
||||
|
||||
ok1 = check_balance(cfg, w)
|
||||
ok2 = check_detail(cfg, w)
|
||||
|
||||
ok3 = True
|
||||
with tempfile.TemporaryDirectory(prefix="xq0052_e2e_") as d:
|
||||
t0 = time.time()
|
||||
res = hotel_report.export_member(cfg, today, d)
|
||||
print(f"\n export_member 落盘: {time.time() - t0:.1f}s")
|
||||
ok3 = check_files(res)
|
||||
|
||||
print(f"\n结论: 余额={'一致' if ok1 else '有差异'} 明细={'一致' if ok2 else '有差异'} "
|
||||
f"文件={'正常' if ok3 else '异常'}")
|
||||
return 0 if (ok1 and ok2 and ok3) else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 台账维护端到端:在**模板副本**上跑一遍(不碰生产文件),验证四张 sheet 的写入。
|
||||
|
||||
流程与插件一致:
|
||||
交班时间逐日追加 → 明细按天追加(支付方式按列名对应)→ 新办卡追加(A 列交班时间)
|
||||
→ 余额整体覆盖 → 重算 → 汇总核对
|
||||
|
||||
用法(项目根):
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\ledger_e2e.py --no-recalc
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\ledger_e2e.py # 含重算
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(BASE, "..", ".."))
|
||||
sys.path.insert(0, os.path.join(ROOT, "libs", "hotel_report"))
|
||||
sys.path.insert(0, os.path.join(ROOT, "plugins", "XQ0001-0100",
|
||||
"XQ0052 湖畔储值卡每日导出统计"))
|
||||
|
||||
TEMPLATE = r"D:\资料\财务\湖畔储值卡每日导出统计\2026年11月会员卡统计-模版调整-新会员卡.xlsx"
|
||||
OUT_DIR = os.path.join(BASE, "out_test")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--day", default="", help="目标营业日,留空=今天")
|
||||
ap.add_argument("--no-recalc", action="store_true", help="跳过工作簿重算(快)")
|
||||
ap.add_argument("--template", default=TEMPLATE)
|
||||
ap.add_argument("--inplace", action="store_true",
|
||||
help="直接维护 --template 指向的台账(会先自动备份),不复制副本")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
import hotel_report
|
||||
from logic.ledger import LedgerMaintainer
|
||||
from logic.provider import SdkProvider
|
||||
|
||||
if args.inplace:
|
||||
target = args.template
|
||||
print(f"原地维护:{target}(会先自动备份)")
|
||||
else:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
target = os.path.join(OUT_DIR, "台账副本.xlsx")
|
||||
t0 = time.time()
|
||||
shutil.copy2(args.template, target)
|
||||
print(f"已复制模板副本({os.path.getsize(target) / 1048576:.1f} MB,{time.time() - t0:.1f}s)")
|
||||
|
||||
day = (datetime.strptime(args.day, "%Y-%m-%d").date() if args.day
|
||||
else datetime.now().date())
|
||||
cfg = hotel_report.HotelConfig.resolve(timeout=300)
|
||||
maint = LedgerMaintainer(target, log=lambda m, lv="INFO": print(f" [{lv}] {m}"),
|
||||
progress=lambda p: None, backup=args.inplace,
|
||||
recalc=not args.no_recalc)
|
||||
|
||||
t0 = time.time()
|
||||
res = maint.run(day, SdkProvider(hotel_report, cfg))
|
||||
cost = time.time() - t0
|
||||
|
||||
print(f"\n耗时 {cost / 60:.1f} 分钟")
|
||||
print(f"补的天:{[str(d) for d in res['days']]}")
|
||||
print(f"明细 +{res['detail_rows']} 行,新办卡 +{res['new_cards']} 行,"
|
||||
f"余额 {res['balance_rows']} 人(合计 {res['balance_total']:,.2f})")
|
||||
print("核对:")
|
||||
for c in res["checks"]:
|
||||
print(f" {'✓' if c['ok'] else '✗'} {c['name']}:应为 {c['expect']} / 实际 {c['actual']}"
|
||||
f"{(' ' + c['note']) if c['note'] else ''}")
|
||||
bad = [c for c in res["checks"] if not c["ok"]]
|
||||
print(f"\n结论:{'全部一致' if not bad else f'{len(bad)} 项不一致'}")
|
||||
return 0 if not bad else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 插件级端到端:按壳子的加载方式加载插件,用真实 WCF 跑一次 run()。
|
||||
|
||||
验证链路:插件 run() → SDK 挂载 → settle_window → export_member → 两份 Excel。
|
||||
|
||||
用法(项目根):
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\plugin_e2e.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(BASE, "..", ".."))
|
||||
PLUGIN_DIR = os.path.join(ROOT, "plugins", "XQ0001-0100", "XQ0052 湖畔储值卡每日导出统计")
|
||||
|
||||
sys.path.insert(0, os.path.join(ROOT, "desktop", "electron-shell", "python")) # webhost 包
|
||||
sys.path.insert(0, os.path.join(ROOT, "libs", "hotel_report")) # 开发态 SDK
|
||||
|
||||
|
||||
class _Ctx:
|
||||
def __init__(self):
|
||||
self.lines = []
|
||||
|
||||
def log(self, msg, level="INFO"):
|
||||
self.lines.append(msg)
|
||||
print(f" [{level}] {msg}")
|
||||
|
||||
def progress(self, pct):
|
||||
if int(pct) in (5, 50, 55, 100):
|
||||
print(f" [progress] {int(pct)}%")
|
||||
|
||||
|
||||
def load_plugin():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"xq0052_plugin", os.path.join(PLUGIN_DIR, "__init__.py"),
|
||||
submodule_search_locations=[PLUGIN_DIR])
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules["xq0052_plugin"] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
return mod.PLUGINS[-1]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
plugin = load_plugin()
|
||||
print(f"插件:{plugin.id} {plugin.name} v{plugin.version}")
|
||||
|
||||
out_dir = os.path.join(BASE, "out")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
ctx = _Ctx()
|
||||
res = plugin.run({"day": "", "save_dir": out_dir}, ctx)
|
||||
|
||||
print("\n" + res["summary"])
|
||||
print("\n产出:")
|
||||
ok = True
|
||||
for p in res.get("files") or []:
|
||||
size = os.path.getsize(p) / 1024 / 1024 if os.path.isfile(p) else 0
|
||||
print(f" {os.path.basename(p)} {size:.2f} MB {'OK' if size else '✗ 缺失'}")
|
||||
ok &= bool(size)
|
||||
print(f"\n链路:{'OK' if ok else '✗'}")
|
||||
return 0 if ok else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 模板结构探针:打印指定 sheet 的表头/首尾行/公式分布(只读,不改文件)。
|
||||
|
||||
用法:
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\template_probe.py 交班时间
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\template_probe.py 本月汇总数 --rows 1-6
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
TEMPLATE = Path(r"D:\资料\财务\湖畔储值卡每日导出统计\2026年11月会员卡统计-模版调整-新会员卡.xlsx")
|
||||
|
||||
|
||||
def dump(ws, rows: list, max_col: int) -> None:
|
||||
for r in rows:
|
||||
cells = []
|
||||
for c in range(1, max_col + 1):
|
||||
v = ws.cell(row=r, column=c).value
|
||||
if v is None:
|
||||
continue
|
||||
text = str(v).replace("\n", "\\n")
|
||||
cells.append(f"{get_column_letter(c)}{r}={text[:28]}")
|
||||
print(f" r{r}: " + " | ".join(cells) if cells else f" r{r}: (空)")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("sheet", help="sheet 名;* 表示全部")
|
||||
ap.add_argument("--rows", default="", help="行范围,如 1-8 或 36-43")
|
||||
ap.add_argument("--cols", type=int, default=30, help="最多打印列数")
|
||||
ap.add_argument("--tail", type=int, default=0, help="额外打印末尾 N 行")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
warnings.filterwarnings("ignore")
|
||||
wb = load_workbook(TEMPLATE, data_only=False)
|
||||
|
||||
names = wb.sheetnames if args.sheet == "*" else [n for n in wb.sheetnames if n == args.sheet]
|
||||
if not names:
|
||||
print(f"没有 sheet {args.sheet!r};全部:{wb.sheetnames}")
|
||||
return 1
|
||||
|
||||
for name in names:
|
||||
ws = wb[name]
|
||||
print(f"\n=== {name} dims={ws.dimensions} rows={ws.max_row} cols={ws.max_column}")
|
||||
if args.rows:
|
||||
a, _, b = args.rows.partition("-")
|
||||
rows = list(range(int(a), int(b or a) + 1))
|
||||
else:
|
||||
rows = list(range(1, min(6, ws.max_row) + 1))
|
||||
dump(ws, [r for r in rows if r <= ws.max_row], min(args.cols, ws.max_column))
|
||||
if args.tail:
|
||||
start = max(1, ws.max_row - args.tail + 1)
|
||||
print(f" --- 末尾 {args.tail} 行 ---")
|
||||
dump(ws, list(range(start, ws.max_row + 1)), min(args.cols, ws.max_column))
|
||||
|
||||
formulas = []
|
||||
for row in ws.iter_rows(min_row=1, max_row=min(ws.max_row, 60)):
|
||||
for cell in row:
|
||||
if isinstance(cell.value, str) and cell.value.startswith("="):
|
||||
formulas.append(f"{cell.coordinate}={cell.value[:40]}")
|
||||
if formulas:
|
||||
print(f" 公式(前 60 行,共 {len(formulas)} 个,示例 12 个):")
|
||||
print(" " + " | ".join(formulas[:12]))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,144 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0052 探针:验证 WCF 只读通道能否承载「会员卡统计(余额 + 明细)」。
|
||||
|
||||
结论决定 SDK hotel_report 的实现路径:
|
||||
· 四段式能读会员库视图 / 能调会员库标量函数 F_GetMemberMoney → 余额可改写成单条 CTE,纯 WCF 实现;
|
||||
· 否则余额只能退回 pyodbc 直连(执行机需 ODBC 驱动 + 库账号)。
|
||||
|
||||
用法(项目根,.venv):
|
||||
.venv\\Scripts\\python.exe tests\\xq0052_湖畔储值卡\\wcf_probe.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
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
|
||||
|
||||
|
||||
def step(no: str, title: str, sql: str, params=()) -> bool:
|
||||
print(f"\n--- [{no}] {title}")
|
||||
print(" SQL: " + " ".join(sql.split())[:220])
|
||||
t0 = time.time()
|
||||
try:
|
||||
rows = wcf.query(sql, cfg, params)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" FAIL ({time.time() - t0:.1f}s): {type(e).__name__}: {e}")
|
||||
return False
|
||||
cost = time.time() - t0
|
||||
print(f" OK {len(rows)} 行 / {cost:.1f}s")
|
||||
if rows:
|
||||
keys = list(rows[0].keys())
|
||||
print(" 列: " + ", ".join(keys[:12]) + (" ..." if len(keys) > 12 else ""))
|
||||
for r in rows[:3]:
|
||||
print(" 行: " + " | ".join(f"{k}={r[k]}" for k in keys[:8]))
|
||||
return True
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
global cfg
|
||||
cfg = HotelConfig.resolve()
|
||||
print(f"WCF: {cfg.wcf_url}")
|
||||
|
||||
# 0 连通性
|
||||
step("0", "连通性 getdate()", "select getdate() as now")
|
||||
|
||||
# 1 最晚交班(昨日/今日)→ 得到余额/明细的时间窗口
|
||||
start = end = None
|
||||
try:
|
||||
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
prev = latest_shift_time(cfg, today - timedelta(days=1))
|
||||
cur = latest_shift_time(cfg, today)
|
||||
print(f"\n--- [1] 最晚交班")
|
||||
print(f" 昨日 {prev['day']} → {prev['latest']}")
|
||||
print(f" 今日 {cur['day']} → {cur['latest']}")
|
||||
start = prev["latest"] or (today - timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
|
||||
end = cur["latest"]
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" FAIL: {type(e).__name__}: {e}")
|
||||
|
||||
if not end:
|
||||
print("\n今日无交班记录,退化为最近两天做通道探测")
|
||||
end = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
if not start:
|
||||
start = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
|
||||
print(f" 探测窗口: {start} ~ {end}")
|
||||
|
||||
# 2 会员库视图(两段式走链接服务器默认库)
|
||||
ok_view = step(
|
||||
"2", "四段式读会员库视图 jgmember.dbo.V_GetMemberOperateHistory",
|
||||
"select top 5 memberid, membername, feeindate, status, money "
|
||||
"from jgmember.dbo.V_GetMemberOperateHistory with (nolock) order by feeindate desc")
|
||||
|
||||
# 2b 链接服务器 + 库名两段(抓包里的写法)
|
||||
if not ok_view:
|
||||
step(
|
||||
"2b", "链接服务器全名 jgmember.jgmember.dbo.V_GetMemberOperateHistory",
|
||||
"select top 5 memberid, feeindate from jgmember.jgmember.dbo.V_GetMemberOperateHistory "
|
||||
"with (nolock) order by feeindate desc")
|
||||
|
||||
# 3 关键:跨库调用会员库标量函数 F_GetMemberMoney
|
||||
step(
|
||||
"3", "会员库标量函数 jgmember.dbo.F_GetMemberMoney('余额',...)",
|
||||
"select jgmember.dbo.F_GetMemberMoney('余额','',100,null,null,null) as v")
|
||||
|
||||
# 4 会员系统参数(决定本金/赠金列是否显示)
|
||||
step(
|
||||
"4", "会员系统参数 cmbIsCalcMemberPercent",
|
||||
"select ParaValue from jgmember.dbo.Dt_MemberSysPara with (nolock) "
|
||||
"where ParaName='cmbIsCalcMemberPercent'")
|
||||
|
||||
# 5 明细主查询(单语句,golden 上执行)
|
||||
detail_sql = (
|
||||
"select top 5 a.feeindate, a.memberid, a.membername, a.billid, a.mobilephone, "
|
||||
"a.leavecardmoney, a.money, a.truemoney, a.feetype, a.basemoney, a.giftmoney, "
|
||||
"a.cardtypename, "
|
||||
"dbo.F_GetMemberMoney('全部', sp.ParaValue, b.OldMoney, a.VRealPercentNum, "
|
||||
"a.PRealPercentNum, NULL) as oldmoney, "
|
||||
"dbo.F_GetMemberMoney('全部', sp.ParaValue, b.Shishou, a.VRealPercentNum, "
|
||||
"a.PRealPercentNum, NULL) as shishou, "
|
||||
"b.favourmoney, a.vpnname, a.opersite, a.persumename, a.employname as hj, "
|
||||
"a.waternum, -(a.griftmoney * a.money) as factconsume, a.totalconsume, "
|
||||
"a.memberremark, a.coach, a.enterdate, a.operatorname, b.jifen "
|
||||
"from jgmember.dbo.V_GetMemberOperateHistory a "
|
||||
"left join sn_bill b on a.billid = b.billid "
|
||||
"left join dbo.Dt_SysPara sp on sp.ParaName = 'cmbIsStartAdjustBill' "
|
||||
"where a.feeindate <= ? and a.feeindate >= ? "
|
||||
"and a.status <> '删除' and a.Status <> '作废' and a.remark <> '非卡结' "
|
||||
"order by a.memberid, a.feeindate")
|
||||
step("5", "明细主查询(窗口内 top5)", detail_sql, (end, start))
|
||||
|
||||
# 6 明细末尾动态支付方式列
|
||||
step(
|
||||
"6", "充值单收款方式(按 BillId 关联 v_snchangeclass)",
|
||||
"select top 5 a.Billid, b.MethodName, sum(b.PayAmount) as amt "
|
||||
"from jgmember.dbo.dt_membercardcomein a "
|
||||
"left join v_snchangeclass b on b.BillId = a.Billid "
|
||||
"where a.feeindate >= ? and a.feeindate <= ? and a.feetype = '充值' "
|
||||
"group by a.Billid, b.MethodName", (start, end))
|
||||
|
||||
# 7 余额改写方向验证:会员库函数在 golden 侧可用性 + 视图带 nolock 的大表扫描耗时
|
||||
step(
|
||||
"7", "余额所需基础数据:按 memberguid 聚合最新一笔",
|
||||
"select count(*) as n from jgmember.dbo.V_GetMemberOperateHistory a with (nolock) "
|
||||
"where a.FeeInDate <= ? and (a.Remark <> '非卡结' or a.Remark is null) "
|
||||
"and a.status <> '删除'", (end,))
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception: # noqa: BLE001
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user