Files
DecomEval/backend/app/nqi/adhoc.py
T

394 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""即席查询的分类、表和按相对时间取数。"""
from __future__ import annotations
import json
from datetime import date, datetime, timedelta
from urllib.parse import urlencode
import httpx
from app.nqi.client import NqiAuthError, NqiClient, NqiError, _landed_on_login
from app.nqi.constants import ORIGIN
ADHOC = f"{ORIGIN}/pro-adhoc"
PAGE = f"{ADHOC}/adhocquery"
ENTRY = f"{ADHOC}/index"
PAGE_SIZE = 200
MAX_PAGES = 2000
IN_BATCH = 500
TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"}
def time_window(mode: str, count: int, today: date) -> tuple[datetime, datetime]:
if mode not in TIME_MODES:
raise ValueError("数据时间不正确")
amount = 1 if mode in {"prev_month", "prev_week", "prev_day"} else count
if amount < 1 or amount > 366:
raise ValueError("时间数量需要在 1 到 366 之间")
if mode in {"prev_month", "prev_months"}:
start_month = _shift_month(today.replace(day=1), -amount)
end = today.replace(day=1) - timedelta(days=1)
start = start_month
elif mode in {"prev_week", "prev_weeks"}:
this_monday = today - timedelta(days=today.weekday())
end = this_monday - timedelta(days=1)
start = this_monday - timedelta(weeks=amount)
else:
end = today - timedelta(days=1)
start = today - timedelta(days=amount)
return _start(start), _end(end)
def _shift_month(first: date, offset: int) -> date:
month_index = first.year * 12 + (first.month - 1) + offset
year, month = divmod(month_index, 12)
return date(year, month + 1, 1)
def _start(day: date) -> datetime:
return datetime(day.year, day.month, day.day)
def _end(day: date) -> datetime:
return datetime(day.year, day.month, day.day, 23, 59, 59)
async def ensure_session(client: NqiClient) -> None:
"""单点入口是 /pro-adhoc/index。票据有效时,这里会换成即席查询自己的会话。"""
response = await client._request(
"GET",
ENTRY,
headers={
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": f"{ORIGIN}/pro-portal/",
"Upgrade-Insecure-Requests": "1",
},
check_auth=False,
)
if response.status_code >= 400 or _landed_on_login(response):
raise NqiAuthError("登录已失效,请重新登录")
async def categories(client: NqiClient) -> list[dict]:
await ensure_session(client)
payload = await _post_json(client, f"{ADHOC}/index/searchTableType", {})
rows = payload.get("CFG_ADHOC_CODE") if isinstance(payload, dict) else None
if not isinstance(rows, list):
raise NqiError("没有取到查询分类")
result = []
for row in rows:
if not isinstance(row, dict):
continue
code = row.get("code")
name = str(row.get("name_cn") or "").strip()
if code is None or not name:
continue
result.append({"code": int(code), "name": name})
result.sort(key=lambda item: item["code"])
return result
async def catalog_tree(client: NqiClient) -> list[dict]:
await ensure_session(client)
payload = await _post_json(client, f"{ADHOC}/index/searchTableType", {})
rows = payload.get("CFG_ADHOC_CODE") if isinstance(payload, dict) else None
if not isinstance(rows, list):
raise NqiError("没有取到查询分类")
groups = []
for row in rows:
if not isinstance(row, dict) or row.get("code") is None:
continue
name = str(row.get("name_cn") or "").strip()
if not name:
continue
code = int(row["code"])
menu = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
groups.append({"code": code, "name": name, "tables": _table_rows(menu)})
groups.sort(key=lambda item: item["code"])
return groups
def _table_rows(payload: object) -> list[dict]:
if not isinstance(payload, list):
return []
result = []
for row in payload:
if not isinstance(row, dict):
continue
tablename = str(row.get("tablename") or "").strip()
title = str(row.get("tablename_cn") or tablename).strip()
if tablename:
result.append({"tablename": tablename, "name": title})
return result
async def tables(client: NqiClient, code: int) -> list[dict]:
await ensure_session(client)
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
result = _table_rows(payload)
if not isinstance(payload, list):
raise NqiError("没有取到这个分类下的表")
return result
async def export_table(
client: NqiClient,
tablename: str,
start: datetime,
end: datetime,
city: str,
) -> tuple[str, list[dict], list[dict]]:
await ensure_session(client)
columns = await _columns(client, tablename)
if not columns:
raise NqiError("这张表没有可导出的字段")
title = str(columns[0].get("tablename_cn") or tablename)
where = _where(columns[0], start, end, city, timed=_has_time_column(columns))
return title, columns, await _fetch_all(client, columns[0], columns, where)
async def select_rows(
client: NqiClient,
tablename: str,
start: datetime,
end: datetime,
city: str,
field: str,
values: list[str],
wanted: tuple[str, ...] = (),
) -> list[dict]:
"""按 field 的取值清单查 [start, end] 的行,和页面一样把清单逗号拼进 in 条件,每批 IN_BATCH 个。wanted 给出时只取这些列。"""
await ensure_session(client)
columns = await _columns(client, tablename)
if not columns:
raise NqiError("这张表没有可查的字段")
head = columns[0]
chosen = [column for column in columns if column.get("columnname") in wanted] if wanted else columns
names = [value for value in dict.fromkeys(str(item).strip() for item in values) if value and "," not in value]
timed = _has_time_column(columns)
rows: list[dict] = []
for offset in range(0, len(names), IN_BATCH):
where = _where(head, start, end, city, timed=timed)
at = len(where) - (1 if city.strip() else 0)
where.insert(
at,
{"datatype": "character", "feild": field, "feildName": "", "symbol": "in", "val": ",".join(names[offset : offset + IN_BATCH]), "whereCon": "and", "query": True},
)
rows.extend(await _fetch_all(client, head, chosen, where))
return rows
async def _fetch_all(client: NqiClient, head: dict, columns: list[dict], where: list[dict]) -> list[dict]:
common = {
"geographicdimension": head.get("geographicdimension") or "",
"timedimension": head.get("timedimension") or "",
"enodebField": head.get("enodeb_field") or "",
"cgiField": head.get("cgi_field") or "",
"timeField": head.get("time_field") or "starttime",
"cellField": head.get("cell_field") or "",
"cityField": head.get("city_field") or "city",
"result": _result_json(head, columns),
"where": json.dumps(where, ensure_ascii=False),
}
total, index_count = await _count(client, common)
rows: list[dict] = []
start_at = 0
pages = 0
while start_at < total:
pages += 1
if pages > MAX_PAGES:
raise NqiError("数据行数超出单次导出上限")
page = await _post_json(
client,
f"{PAGE}/getTable",
{
**common,
**_column_form(columns),
"draw": pages,
"start": start_at,
"length": PAGE_SIZE,
"indexcount": index_count,
"total": total,
"order[0][column]": 0,
"order[0][dir]": "desc",
"search[value]": "",
"search[regex]": "false",
},
)
data = page.get("data") if isinstance(page, dict) else None
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
rows.extend(batch)
if len(batch) < PAGE_SIZE:
break
start_at += PAGE_SIZE
return rows
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。页面第一次计数总是带 indexcount=0,缺了会报错。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", {**common, "indexcount": "0"})
if not isinstance(counted, dict) or "count" not in counted:
message = counted.get("message") if isinstance(counted, dict) else ""
raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}")
return int(counted.get("count") or 0), str(counted.get("indexcount") or "0")
def _result_json(head: dict, columns: list[dict]) -> str:
"""页面在字段列表后还带 tableParams 和 columnname,缺了服务端返回 {"stat":"0","message":"null"}。"""
payload = {
"result": [_field(column) for column in columns],
"tableParams": {
"supporteddimension": head.get("supporteddimension"),
"supportedtimedimension": head.get("supportedtimedimension") or "",
},
"columnname": "",
}
return json.dumps(payload, ensure_ascii=False)
def _field(column: dict) -> dict:
return {
"feildtype": column.get("fieldtype") or "",
"table": column.get("tablename") or "",
"tableName": column.get("tablename_cn") or "",
"datatype": column.get("datatype") or "",
"columntype": str(column.get("columntype") if column.get("columntype") is not None else ""),
"feildName": column.get("columnname_cn") or "",
"feild": column.get("columnname") or "",
"poly": "无",
"anyWay": "无",
"chart": "无",
"chartpoly": "无",
}
def _has_time_column(columns: list[dict]) -> bool:
"""工参这类表的配置写了 time_field,表里却没有这一列;页面这时不带时间条件,带了服务端不执行。"""
time_field = str(columns[0].get("time_field") or "starttime") if columns else ""
return any(column.get("columnname") == time_field for column in columns)
def _where(column: dict, start: datetime, end: datetime, city: str, *, timed: bool = True) -> list[dict]:
time_field = str(column.get("time_field") or "starttime")
conditions = []
if timed:
conditions += [
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
]
city_name = city.strip()
if city_name:
conditions.append(
{
"datatype": "character",
"feild": str(column.get("city_field") or "city"),
"feildName": "",
"symbol": "in",
"val": city_name,
"whereCon": "and",
"query": True,
}
)
return conditions
def _stamp(value: datetime) -> str:
return value.strftime("%Y-%m-%d %H:%M:%S")
def _column_form(columns: list[dict]) -> dict:
form: dict[str, str] = {}
for index, column in enumerate(columns):
prefix = f"columns[{index}]"
form[f"{prefix}[data]"] = str(column.get("columnname") or "")
form[f"{prefix}[name]"] = ""
form[f"{prefix}[searchable]"] = "true"
form[f"{prefix}[orderable]"] = "true"
form[f"{prefix}[search][value]"] = ""
form[f"{prefix}[search][regex]"] = "false"
return form
async def search_by_field(client: NqiClient, keyword: str) -> list[dict]:
"""按字段中文名、英文名或字段分类,找出包含它的表。"""
text = keyword.strip()
if not text or len(text) > 80 or any(ord(char) < 32 for char in text):
raise ValueError("请输入字段名称")
await ensure_session(client)
payload = await _post_json(
client,
f"{PAGE}/search",
{"key": text, "field": ["columnname_cn", "columnname", "fieldtype"]},
)
rows = payload.get("CFG_ADHOC_CONF_SEARCH") if isinstance(payload, dict) else None
if not isinstance(rows, list):
raise NqiError("没有查到相关的表")
grouped: dict[str, dict] = {}
order: list[str] = []
for row in rows:
if not isinstance(row, dict):
continue
tablename = str(row.get("tablename") or "").strip()
field_name = str(row.get("columnname_cn") or row.get("columnname") or "").strip()
if not tablename or not field_name:
continue
item = grouped.get(tablename)
if item is None:
title = str(row.get("tablename_cn") or tablename).strip() or tablename
item = {"tablename": tablename, "name": title, "fields": []}
grouped[tablename] = item
order.append(tablename)
column = str(row.get("columnname") or "").strip()
if any(existing["column"] == column and existing["name"] == field_name for existing in item["fields"]):
continue
item["fields"].append({"name": field_name, "column": column, "type": str(row.get("datatype") or "").strip()})
return [grouped[name] for name in order]
async def table_fields(client: NqiClient, tablename: str) -> list[dict]:
await ensure_session(client)
rows = await _columns(client, tablename)
fields = []
for row in rows:
name = str(row.get("columnname_cn") or row.get("columnname") or "").strip()
if not name:
continue
fields.append({"name": name, "type": str(row.get("datatype") or "").strip()})
return fields
async def _columns(client: NqiClient, tablename: str) -> list[dict]:
payload = await _post_json(client, f"{PAGE}/getSelectTable", {"tablename": tablename})
rows = payload.get("CFG_ADHOC_CONF_TABLE") if isinstance(payload, dict) else None
if not isinstance(rows, list):
raise NqiError("没有取到表字段")
shown = [row for row in rows if isinstance(row, dict) and str(row.get("isshow")) == "1" and row.get("columnname")]
usable = shown or [row for row in rows if isinstance(row, dict) and row.get("columnname")]
usable.sort(key=lambda row: int(row.get("sort") or 0))
return usable
async def _post_json(client: NqiClient, url: str, form: dict) -> dict | list:
response = await client._request(
"POST",
url,
content=urlencode(form, doseq=True).encode("utf-8"),
headers={
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Origin": ORIGIN,
"Referer": PAGE,
"X-Requested-With": "XMLHttpRequest",
},
timeout=httpx.Timeout(120.0, connect=15.0),
)
if response.status_code >= 400:
raise NqiError("查询没有返回数据")
try:
payload = response.json()
except json.JSONDecodeError as exc:
raise NqiError("查询返回的内容无法识别") from exc
if not isinstance(payload, (dict, list)):
raise NqiError("查询返回的内容无法识别")
return payload