316 lines
14 KiB
Python
316 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""报表接口:列表查询与导出。
|
||
|
||
来源:前端 ``src/api/setting.ts`` 的声明式接口表(38 组 list/export 成对),
|
||
已用真实登录态验证过若干组(见 README 的验证记录)。**只做机制**:
|
||
分页、响应形态兼容、下载落盘、文件名还原;查哪些报表、怎么用数据、落哪个目录,
|
||
全部留给插件。
|
||
|
||
两种响应形态(实测,必须都兼容)::
|
||
|
||
{data: {list: [...], total: 120}} # 分页型,如 unionPay / groupPay
|
||
{data: [...]} # 直返数组型,如 posPay / debitCard
|
||
|
||
导出接口返回二进制 Excel(``application/vnd.ms-excel``),
|
||
文件名在 ``Content-Disposition`` 里且是 URL 编码的中文。
|
||
|
||
典型用法::
|
||
|
||
from crm_sdk import CrmClient, auth, reports
|
||
|
||
client = CrmClient(auth.build_session())
|
||
rows = reports.list_all(client, "unionPay", reportDate="2026-11-25")
|
||
path = reports.export(client, "unionPay", reportDate="2026-11-25",
|
||
save_dir=r"D:\\报表")
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from typing import Any, Dict, List, Optional, Tuple
|
||
|
||
from .config import CRM_BASE_URL
|
||
from .client import CrmClient
|
||
from .errors import ApiError, ConfigError, CrmError, SessionExpiredError
|
||
|
||
#: 报表接口前缀
|
||
_PREFIX = "/membership/report"
|
||
|
||
|
||
def _spec(title: str, slug: str, *, list_path: str = "", export_path: str = "",
|
||
list_suffix: str = "list", export_suffix: str = "export",
|
||
list_method: str = "get",
|
||
extra_exports: Optional[Dict[str, str]] = None) -> dict:
|
||
"""构造一条报表描述(路径都补全成绝对路径)。"""
|
||
base = f"{_PREFIX}/{slug}"
|
||
return {
|
||
"title": title,
|
||
"list": list_path or f"{base}/{list_suffix}",
|
||
"export": export_path or f"{base}/{export_suffix}",
|
||
# 个别报表的 list 只接受 POST(GET 直接 400 Request method 'GET' is not supported)
|
||
"list_method": list_method.lower(),
|
||
"extra_exports": extra_exports or {},
|
||
}
|
||
|
||
|
||
#: 报表注册表:key 即插件里用的名字
|
||
REPORTS: Dict[str, dict] = {
|
||
# ---- 支付/账单类 ----
|
||
"groupPay": _spec("团购支付", "groupPay"),
|
||
"posPay": _spec("POS支付", "posPay"),
|
||
"cashPay": _spec("现金支付", "cashPay"),
|
||
"thirdPayShop": _spec("第三方支付(门店)", "thirdPayShop"),
|
||
"thirdPayHeadquarters": _spec("第三方支付(总部)", "thirdPayHeadquarters"),
|
||
"unionPay": _spec("支付数据", "unionPay"),
|
||
"groupData": _spec("团购数据", "groupData"),
|
||
"unionPayRefund": _spec("退单统计", "unionPayRefund"),
|
||
"employeeUnionPay": _spec("员工内部卡消费", "employeeUnionPay"),
|
||
"orderSubjectAddition": _spec("订单附加属性统计", "orderSubjectAddition"),
|
||
|
||
# ---- 储值卡类 ----
|
||
"debitCard": _spec("储值卡充值", "debitCard"),
|
||
"debitCardConsume": _spec("储值卡消费", "debitCardConsume"),
|
||
"debitCardBalance": _spec("储值卡余额", "debitCardBalance"),
|
||
"depositData": _spec("储值卡线上充值", "depositData"),
|
||
"abnormalDeposit": _spec("储值卡异常充值", "abnormalDeposit"),
|
||
"debitCardAbnormal": _spec("储值卡异常消费", "debitCardAbnormal"),
|
||
"discountCardAbnormal": _spec("打折卡异常消费", "discountCardAbnormal"),
|
||
"discountCardRecord": _spec("打折卡升级记录", "discountCardRecord"),
|
||
"consumeOrderDeposit": _spec("储值规则统计", "consumeOrderDeposit"),
|
||
# 储值记录 / 储值台账 / 储值余额 三个是 debitCard 下的特殊路径
|
||
"debitCardDeposit": _spec("储值记录", "debitCard",
|
||
list_path=f"{_PREFIX}/debitCard/depositList",
|
||
export_path=f"{_PREFIX}/debitCard/depositExport"),
|
||
"debitCardAccountBook": _spec(
|
||
"储值台账", "debitCard",
|
||
list_path=f"{_PREFIX}/debitCard/balanceAccountBookList",
|
||
export_path=f"{_PREFIX}/debitCard/balanceAccountBookExport"),
|
||
"debitCardMemberBalance": _spec(
|
||
"储值余额", "debitCard",
|
||
list_path=f"{_PREFIX}/debitCard/memberBalanceList",
|
||
export_path=f"{_PREFIX}/debitCard/memberBalanceExport"),
|
||
|
||
# ---- 员工/业绩类 ----
|
||
"comprehensivePerformance": _spec("技师综合业绩", "comprehensivePerformance"),
|
||
"employeeWork": _spec("技师上钟数据", "employeeWork"),
|
||
"employeeWorkRank": _spec("技师上钟数据排名", "employeeWorkRank"),
|
||
"employeeSpecialWork": _spec("技师点钟数据", "employeeSpecialWork"),
|
||
"consumeSubjectCount": _spec("消费项目统计", "consumeSubjectCount",
|
||
extra_exports={"details": f"{_PREFIX}/consumeSubjectCount/exportDetails"}),
|
||
|
||
# ---- 霸王餐 ----
|
||
"overlordOrderDeposit": _spec("霸王餐充值明细", "overlordOrderDeposit"),
|
||
"overlordOrderConsume": _spec("霸王餐消费明细", "overlordOrderConsume"),
|
||
"overlordOrderBalance": _spec("霸王餐余额查询", "overlordOrderBalance"),
|
||
|
||
# ---- 小程序 / 留宿 ----
|
||
"miniProgramOrder": _spec("小程序订单", "miniProgramOrder"),
|
||
"miniProgramPay": _spec("小程序收入", "miniProgramPay"),
|
||
"overnightSettlement": _spec("留宿结算", "overnightSettlement"),
|
||
|
||
# ---- 第三方平台 ----
|
||
"taobaoTicket": _spec("淘宝订单数据", "taobaoTicket"),
|
||
"weimengValidate": _spec("微盟核销统计", "weimeng",
|
||
list_path=f"{_PREFIX}/weimeng/listValidate",
|
||
export_path=f"{_PREFIX}/weimeng/exportValidate"),
|
||
"weimengValidateSum": _spec("微盟核销汇总", "weimeng",
|
||
list_path=f"{_PREFIX}/weimeng/listValidateSum",
|
||
export_path=f"{_PREFIX}/weimeng/exportValidateSum"),
|
||
"weimengFundsSum": _spec("微盟资金汇总", "weimeng",
|
||
list_path=f"{_PREFIX}/weimeng/listFundsSum",
|
||
export_path=f"{_PREFIX}/weimeng/exportFundsSum"),
|
||
|
||
# ---- 会员券(不在 report 前缀下,且 list 只接受 POST)----
|
||
"memberCoupon": _spec("会员优惠券", "memberCoupon",
|
||
list_path="/membership/memberCoupon/report/list",
|
||
export_path="/membership/memberCoupon/report/export",
|
||
list_method="post"),
|
||
}
|
||
|
||
|
||
def names() -> List[str]:
|
||
"""全部报表 key(可直接传给 :func:`list_all` / :func:`export`)。"""
|
||
return sorted(REPORTS)
|
||
|
||
|
||
def titles() -> Dict[str, str]:
|
||
"""key → 中文标题。"""
|
||
return {k: v["title"] for k, v in REPORTS.items()}
|
||
|
||
|
||
def _spec_of(name: str) -> dict:
|
||
spec = REPORTS.get(name)
|
||
if spec is None:
|
||
raise ConfigError(
|
||
f"未知报表 {name!r};可用:{', '.join(names())}"
|
||
)
|
||
return spec
|
||
|
||
|
||
def _url(path: str) -> str:
|
||
"""相对路径 → 绝对 URL(配置里的 ``CRM_BASE_URL`` 可指向测试环境)。"""
|
||
return CRM_BASE_URL + path
|
||
|
||
|
||
# ==================== 列表 ====================
|
||
def _as_int(value) -> Optional[int]:
|
||
"""把后端返回的计数(可能是数字也可能是字符串)转成 int;不可解析返回 None。"""
|
||
if isinstance(value, bool) or value is None:
|
||
return None
|
||
if isinstance(value, int):
|
||
return value
|
||
if isinstance(value, float):
|
||
return int(value)
|
||
text = str(value).strip()
|
||
return int(text) if text.isdigit() else None
|
||
|
||
|
||
def _fetch_page(client, name: str, page_no: int, page_size: int,
|
||
**params) -> Tuple[List[dict], Optional[int], bool]:
|
||
"""取一页,返回 ``(rows, total, has_more)``;``total`` 仅分页型有。"""
|
||
spec = _spec_of(name)
|
||
query: Dict[str, Any] = dict(params)
|
||
query.setdefault("pageNum", page_no)
|
||
query.setdefault("pageSize", page_size)
|
||
url = _url(spec["list"])
|
||
label = f"报表 {name} 列表"
|
||
if spec["list_method"] == "post":
|
||
data = client.request_json("POST", url, data=query, label=label)
|
||
else:
|
||
data = client.request_json("GET", url, params=query, label=label)
|
||
client.check_code(data, label)
|
||
payload = data.get("data")
|
||
|
||
if isinstance(payload, dict):
|
||
rows = list(payload.get("list") or [])
|
||
total = _as_int(payload.get("total"))
|
||
has_more = (total is not None and page_no * page_size < total) \
|
||
or (total is None and len(rows) >= page_size)
|
||
return rows, total, has_more
|
||
|
||
if isinstance(payload, list):
|
||
# 直返数组型:服务端不分页,一次就是全量
|
||
return list(payload), len(payload), False
|
||
|
||
raise ApiError(f"报表 {name} 返回结构不支持:{str(payload)[:200]}",
|
||
payload=data)
|
||
|
||
|
||
def list_page(client, name: str, page_no: int = 1, page_size: int = 200,
|
||
*, extra: str = "", **params) -> Tuple[List[dict], bool]:
|
||
"""取一页数据,返回 ``(rows, has_more)``。
|
||
|
||
同时兼容两种响应形态:
|
||
|
||
* ``{list, total}``:按 ``total`` 判断是否还有下一页;
|
||
* 裸数组:服务端一次返回全量,``has_more`` 恒为 False。
|
||
|
||
请求方法按报表配置走(绝大多数 GET,``memberCoupon`` 是 POST)。
|
||
"""
|
||
rows, _total, has_more = _fetch_page(client, name, page_no, page_size, **params)
|
||
return rows, has_more
|
||
|
||
|
||
def query(client, name: str, *, page_size: int = 20, **params) -> dict:
|
||
"""「先查询」:用导出将用的同一批参数查一页,拿总量与样本。
|
||
|
||
Returns:
|
||
``{"total": int|None, "rows": [...], "has_more": bool}``
|
||
|
||
为什么需要它:
|
||
* 有的报表**不传条件会导出全表**(实测 ``debitCardMemberBalance``
|
||
无参数导出 70,200 行),先查一眼总量再决定导不导;
|
||
* 查询能第一时间暴露权限问题(如 ``memberCoupon`` 对无权限账号 403),
|
||
比下载到一半失败更早;
|
||
* 参数拼错时查询就报错,不用等到文件下来才发现为空。
|
||
"""
|
||
rows, total, has_more = _fetch_page(client, name, 1, page_size, **params)
|
||
return {"total": total, "rows": rows, "has_more": has_more}
|
||
|
||
|
||
def list_all(client, name: str, *, page_size: int = 200, max_pages: int = 200,
|
||
sleep: float = 0.2, **params) -> List[dict]:
|
||
"""按页取全量(直返数组型只会请求一次)。"""
|
||
return client.paginate(
|
||
lambda page_no, size: list_page(client, name, page_no, size, **params),
|
||
page_size=page_size, max_pages=max_pages, sleep=sleep)
|
||
|
||
|
||
# ==================== 导出 ====================
|
||
def export(client, name: str, *, save_dir: str = "", filename: str = "",
|
||
timeout: Optional[float] = None, extra: str = "",
|
||
query_first: bool = False, max_rows: Optional[int] = None,
|
||
**params) -> str:
|
||
"""导出报表到本地,返回绝对路径。
|
||
|
||
Args:
|
||
name: :data:`REPORTS` 的 key
|
||
save_dir: 落盘目录(默认当前目录)
|
||
filename: 指定文件名;不传则用服务端 ``Content-Disposition`` 里的原名
|
||
extra: 需要走子导出时用(如 ``consumeSubjectCount`` 的 ``details``)
|
||
query_first: True 时先用**同一批参数**查一页(走 list 接口),确认条件有效、
|
||
拿到总量后再导;无参数导出全表的情况会被这一步拦住
|
||
max_rows: 配合 ``query_first``:总量超过该值时拒绝导出并抛 ``ConfigError``,
|
||
防止误触全表导出
|
||
**params: 查询参数(``reportDate`` / ``brandId`` / ``shopId`` 等,原样透传)
|
||
|
||
Raises:
|
||
ApiError: 服务端返回 JSON 错误信封(如日期范围超限)
|
||
SessionExpiredError: 登录态失效
|
||
CrmError: 非 Excel 响应或落盘失败
|
||
ConfigError: ``query_first`` 查出超量 / 无数据
|
||
"""
|
||
spec = _spec_of(name)
|
||
path = spec["extra_exports"].get(extra) if extra else spec["export"]
|
||
if not path:
|
||
raise ConfigError(f"报表 {name} 没有名为 {extra!r} 的子导出")
|
||
|
||
if query_first:
|
||
probe = query(client, name, **params)
|
||
total = probe.get("total")
|
||
client.log(f"[INFO] 先查询 {name}:total={total} 首行字段={len(probe.get('rows') or [])}")
|
||
if total == 0:
|
||
raise ConfigError(f"报表 {name} 在当前条件下没有数据,不导出")
|
||
if max_rows is not None and total is not None and total > max_rows:
|
||
raise ConfigError(
|
||
f"报表 {name} 命中 {total} 行,超过 max_rows={max_rows};"
|
||
"请收窄条件(日期/门店)后再导")
|
||
|
||
url = _url(path)
|
||
resp = client.session.get(url, params=params, timeout=timeout or 180,
|
||
headers=client._headers(None))
|
||
if resp.status_code in (401, 403):
|
||
raise SessionExpiredError(f"报表 {name} 导出未认证(HTTP {resp.status_code})")
|
||
if resp.status_code != 200:
|
||
raise CrmError(f"报表 {name} 导出失败:HTTP {resp.status_code}")
|
||
|
||
ctype = (resp.headers.get("content-type") or "").lower()
|
||
if "json" in ctype: # 服务端把错误当 200 返回
|
||
try:
|
||
envelope = resp.json()
|
||
except ValueError:
|
||
envelope = {}
|
||
client.check_code(envelope, f"报表 {name} 导出")
|
||
raise ApiError(f"报表 {name} 导出返回 JSON 而非文件:{resp.text[:200]}",
|
||
payload=envelope)
|
||
|
||
content = resp.content or b""
|
||
if not content:
|
||
raise CrmError(f"报表 {name} 导出内容为空")
|
||
|
||
fname = (filename
|
||
or CrmClient._filename_from_disposition(resp.headers.get("content-disposition") or "")
|
||
or f"{name}.xlsx")
|
||
# 去掉文件名里 Windows 不接受的字符
|
||
fname = "".join(ch for ch in fname if ch not in '\\/:*?"<>|').strip() or f"{name}.xlsx"
|
||
target_dir = save_dir or os.getcwd()
|
||
os.makedirs(target_dir, exist_ok=True)
|
||
out = os.path.abspath(os.path.join(target_dir, fname))
|
||
with open(out, "wb") as fp:
|
||
fp.write(content)
|
||
client.log(f"[INFO] 报表 {name} 已导出:{out}({len(content)} 字节)")
|
||
return out
|
||
|
||
|
||
__all__ = ["REPORTS", "export", "list_all", "list_page", "names", "query", "titles"]
|