feat: 采集任务可按即席查询分类选表,并按相对时间导出 CSV
This commit is contained in:
+1
-1
@@ -9,4 +9,4 @@ web/dist/
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
|
||||
Temp/
|
||||
|
||||
+71
-1
@@ -1,7 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import Response
|
||||
@@ -14,6 +15,7 @@ from app.config import env_database, hosted, installed, result_dir
|
||||
from app.install import InstallError, perform_install
|
||||
from app.db import get_session, session_scope
|
||||
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
|
||||
from app.nqi.adhoc import TIME_MODES, categories, tables, time_window
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.nqi.flows import drop, purge, remember, take
|
||||
from app.security import hash_password, issue_token, verify_password
|
||||
@@ -465,6 +467,38 @@ def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/admin/nqi/catalog")
|
||||
def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
cookies = _pool_cookies(session)
|
||||
|
||||
async def run() -> dict:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
await client.current_user()
|
||||
if code is None:
|
||||
return {"categories": await categories(client)}
|
||||
return {"tables": await tables(client, code)}
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
try:
|
||||
return asyncio.run(run())
|
||||
except NqiAuthError as exc:
|
||||
raise _bad("账号池凭证已失效") from exc
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
|
||||
|
||||
def _pool_cookies(session: Session) -> list:
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc()))
|
||||
cookies = list(account.cookies or []) if account is not None else []
|
||||
if not cookies:
|
||||
raise _bad("账号池里没有可用凭证")
|
||||
return cookies
|
||||
|
||||
|
||||
@router.get("/admin/sources")
|
||||
def list_sources(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
@@ -522,9 +556,45 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
|
||||
current = dict(source.config or {})
|
||||
if not incoming.get("password"):
|
||||
incoming["password"] = current.get("password") or ""
|
||||
if source.kind == "nqi" and "tables" in incoming:
|
||||
incoming = _nqi_tables(incoming)
|
||||
source.config = incoming
|
||||
|
||||
|
||||
def _nqi_tables(config: dict) -> dict:
|
||||
raw = config.get("tables")
|
||||
if not isinstance(raw, list) or not raw or len(raw) > 30:
|
||||
raise _bad("请选择要采集的表")
|
||||
cleaned = []
|
||||
for item in raw:
|
||||
if not isinstance(item, dict):
|
||||
raise _bad("请选择要采集的表")
|
||||
tablename = str(item.get("tablename") or "").strip()
|
||||
name = str(item.get("name") or tablename).strip()
|
||||
if not tablename or len(tablename) > 180 or len(name) > 120:
|
||||
raise _bad("请选择要采集的表")
|
||||
try:
|
||||
code = int(item.get("code") or 0)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("请选择要采集的表") from exc
|
||||
cleaned.append({"code": code, "category": str(item.get("category") or "")[:80], "tablename": tablename, "name": name})
|
||||
mode = str(config.get("timeMode") or "")
|
||||
if mode not in TIME_MODES:
|
||||
raise _bad("数据时间不正确")
|
||||
try:
|
||||
count = int(config.get("timeCount") or 1)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("时间数量不正确") from exc
|
||||
try:
|
||||
time_window(mode, count, date.today())
|
||||
except ValueError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
city = str(config.get("city") or "").strip()
|
||||
if len(city) > 32:
|
||||
raise _bad("城市名称过长")
|
||||
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city}
|
||||
|
||||
|
||||
def _public_task(task: ExportTask) -> dict:
|
||||
return {
|
||||
"id": task.id,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""即席查询的分类、表和按相对时间取数。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
from datetime import date, datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
from app.nqi.client import NqiClient, NqiError
|
||||
from app.nqi.constants import ORIGIN
|
||||
|
||||
ADHOC = f"{ORIGIN}/pro-adhoc"
|
||||
PAGE = f"{ADHOC}/adhocquery"
|
||||
PAGE_SIZE = 200
|
||||
MAX_PAGES = 2000
|
||||
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 categories(client: NqiClient) -> list[dict]:
|
||||
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 tables(client: NqiClient, code: int) -> list[dict]:
|
||||
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
|
||||
if not isinstance(payload, list):
|
||||
raise NqiError("没有取到这个分类下的表")
|
||||
result = []
|
||||
for row in payload:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
tablename = str(row.get("tablename") or "").strip()
|
||||
name = str(row.get("tablename_cn") or tablename).strip()
|
||||
if tablename:
|
||||
result.append({"tablename": tablename, "name": name})
|
||||
return result
|
||||
|
||||
|
||||
async def export_table(
|
||||
client: NqiClient,
|
||||
tablename: str,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
city: str,
|
||||
) -> tuple[str, bytes, int]:
|
||||
columns = await _columns(client, tablename)
|
||||
if not columns:
|
||||
raise NqiError("这张表没有可导出的字段")
|
||||
title = str(columns[0].get("tablename_cn") or tablename)
|
||||
selected = [_field(column) for column in columns]
|
||||
where = _where(columns[0], start, end, city)
|
||||
common = {
|
||||
"geographicdimension": columns[0].get("geographicdimension") or "",
|
||||
"timedimension": columns[0].get("timedimension") or "",
|
||||
"enodebField": columns[0].get("enodeb_field") or "",
|
||||
"cgiField": columns[0].get("cgi_field") or "",
|
||||
"timeField": columns[0].get("time_field") or "starttime",
|
||||
"cellField": columns[0].get("cell_field") or "",
|
||||
"cityField": columns[0].get("city_field") or "city",
|
||||
"result": json.dumps({"result": selected}, ensure_ascii=False),
|
||||
"where": json.dumps(where, ensure_ascii=False),
|
||||
}
|
||||
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
|
||||
total = int(counted.get("count") or 0) if isinstance(counted, dict) else 0
|
||||
index_count = str(counted.get("indexcount") or "0") if isinstance(counted, dict) else "0"
|
||||
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 title, _csv(columns, rows), len(rows)
|
||||
|
||||
|
||||
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 _where(column: dict, start: datetime, end: datetime, city: str) -> list[dict]:
|
||||
time_field = str(column.get("time_field") or "starttime")
|
||||
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
|
||||
|
||||
|
||||
def _csv(columns: list[dict], rows: list[dict]) -> bytes:
|
||||
buffer = io.StringIO()
|
||||
writer = csv.writer(buffer)
|
||||
writer.writerow([str(column.get("columnname_cn") or column.get("columnname") or "") for column in columns])
|
||||
keys = [str(column.get("columnname") or "") for column in columns]
|
||||
for row in rows:
|
||||
writer.writerow(["" if row.get(key) is None else row.get(key) for key in keys])
|
||||
return buffer.getvalue().encode("utf-8-sig")
|
||||
|
||||
|
||||
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
|
||||
@@ -3,16 +3,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.config import data_dir, inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.adhoc import export_table, time_window
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
@@ -165,6 +167,13 @@ def execute_collection(source_id: int) -> None:
|
||||
elif kind == "nqi":
|
||||
if not cookies:
|
||||
raise ValueError("账号池里没有可用凭证")
|
||||
if config.get("tables"):
|
||||
_save_nqi_tables(cookies, config, source_id)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = ""
|
||||
return
|
||||
name, content = _fetch_nqi_sync(cookies, config)
|
||||
else:
|
||||
raise ValueError("未知的采集来源")
|
||||
@@ -183,6 +192,40 @@ def execute_collection(source_id: int) -> None:
|
||||
source.last_error = str(exc) or "采集失败"
|
||||
|
||||
|
||||
def _save_nqi_tables(cookies: list, config: dict, source_id: int) -> None:
|
||||
import asyncio
|
||||
|
||||
tables = list(config.get("tables") or [])
|
||||
mode = str(config.get("timeMode") or "")
|
||||
count = int(config.get("timeCount") or 1)
|
||||
city = str(config.get("city") or "")
|
||||
start, end = time_window(mode, count, date.today())
|
||||
|
||||
async def run() -> list[tuple[str, bytes]]:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
try:
|
||||
await client.current_user()
|
||||
except NqiAuthError as exc:
|
||||
raise ValueError("账号池凭证已失效") from exc
|
||||
saved: list[tuple[str, bytes]] = []
|
||||
for table in tables:
|
||||
title, content, _rows = await export_table(client, str(table.get("tablename") or ""), start, end, city)
|
||||
saved.append((str(table.get("name") or title), content))
|
||||
return saved
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
files = asyncio.run(run())
|
||||
folder = data_dir() / "collect" / str(source_id)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
stamp = start.strftime("%Y%m%d")
|
||||
for title, content in files:
|
||||
safe = re.sub(r'[\\/:*?"<>|\s]+', "_", title).strip("._")[:80] or "table"
|
||||
(folder / f"{safe}-{stamp}.csv").write_bytes(content)
|
||||
|
||||
|
||||
def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
import asyncio
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from datetime import date
|
||||
|
||||
from app.nqi.adhoc import time_window
|
||||
|
||||
|
||||
def test_relative_windows_from_a_monday():
|
||||
today = date(2026, 11, 9)
|
||||
assert _span("prev_month", 1, today) == ("2026-10-01", "2026-10-31")
|
||||
assert _span("prev_week", 1, today) == ("2026-11-02", "2026-11-08")
|
||||
assert _span("prev_day", 1, today) == ("2026-11-08", "2026-11-08")
|
||||
assert _span("prev_days", 3, today) == ("2026-11-06", "2026-11-08")
|
||||
assert _span("prev_weeks", 2, today) == ("2026-10-26", "2026-11-08")
|
||||
assert _span("prev_months", 2, today) == ("2026-09-01", "2026-10-31")
|
||||
|
||||
|
||||
def _span(mode: str, count: int, today: date) -> tuple[str, str]:
|
||||
start, end = time_window(mode, count, today)
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NButton, NInput, NInputNumber, NModal, NSelect, NSwitch, useDialog } from "naive-ui";
|
||||
import Shell from "../../shell/Shell.vue";
|
||||
import { api } from "../../shared/http";
|
||||
@@ -12,7 +12,13 @@ interface Source {
|
||||
periodDays: number;
|
||||
enabled: boolean;
|
||||
lastError: string;
|
||||
config: Record<string, string | number | boolean>;
|
||||
config: Record<string, unknown>;
|
||||
}
|
||||
interface QueryTable {
|
||||
code: number;
|
||||
category: string;
|
||||
tablename: string;
|
||||
name: string;
|
||||
}
|
||||
const sources = ref<Source[]>([]);
|
||||
const show = ref(false);
|
||||
@@ -27,9 +33,30 @@ const protocol = ref("sftp");
|
||||
const username = ref("");
|
||||
const password = ref("");
|
||||
const path = ref("");
|
||||
const url = ref("");
|
||||
const categories = ref<{ code: number; name: string }[]>([]);
|
||||
const categoryCode = ref<number | null>(null);
|
||||
const categoryTables = ref<{ tablename: string; name: string }[]>([]);
|
||||
const chosen = ref<QueryTable[]>([]);
|
||||
const timeMode = ref("prev_month");
|
||||
const timeCount = ref(1);
|
||||
const city = ref("");
|
||||
const catalogLoading = ref(false);
|
||||
const tablesLoading = ref(false);
|
||||
const dialog = useDialog();
|
||||
const toast = useToast();
|
||||
const timeOptions = [
|
||||
{ label: "上一个月", value: "prev_month" },
|
||||
{ label: "上一周", value: "prev_week" },
|
||||
{ label: "前一天", value: "prev_day" },
|
||||
{ label: "前几周", value: "prev_weeks" },
|
||||
{ label: "前几月", value: "prev_months" },
|
||||
{ label: "前多少天", value: "prev_days" },
|
||||
];
|
||||
const needsCount = computed(() => ["prev_weeks", "prev_months", "prev_days"].includes(timeMode.value));
|
||||
const countLabel = computed(() => (timeMode.value === "prev_weeks" ? "周数" : timeMode.value === "prev_months" ? "月数" : "天数"));
|
||||
const categoryOptions = computed(() => categories.value.map((item) => ({ label: item.name, value: item.code })));
|
||||
const tableOptions = computed(() => categoryTables.value.map((item) => ({ label: item.name, value: item.tablename })));
|
||||
const pickedNames = computed(() => chosen.value.filter((item) => item.code === categoryCode.value).map((item) => item.tablename));
|
||||
|
||||
function reset(source?: Source) {
|
||||
editing.value = source || null;
|
||||
@@ -43,8 +70,72 @@ function reset(source?: Source) {
|
||||
username.value = String(source?.config.username || "");
|
||||
password.value = "";
|
||||
path.value = String(source?.config.path || "");
|
||||
url.value = String(source?.config.url || "");
|
||||
const stored = Array.isArray(source?.config.tables) ? source.config.tables as QueryTable[] : [];
|
||||
chosen.value = stored.filter((item) => item && item.tablename).map((item) => ({
|
||||
code: Number(item.code) || 0,
|
||||
category: String(item.category || ""),
|
||||
tablename: String(item.tablename),
|
||||
name: String(item.name || item.tablename),
|
||||
}));
|
||||
timeMode.value = String(source?.config.timeMode || "prev_month");
|
||||
timeCount.value = Number(source?.config.timeCount || 1);
|
||||
city.value = String(source?.config.city || "");
|
||||
categoryCode.value = chosen.value[0]?.code || categories.value[0]?.code || null;
|
||||
categoryTables.value = [];
|
||||
show.value = true;
|
||||
if (kind.value === "nqi") {
|
||||
void loadCategories();
|
||||
}
|
||||
}
|
||||
|
||||
async function changeKind(value: string) {
|
||||
kind.value = value;
|
||||
if (value === "nqi") await loadCategories();
|
||||
}
|
||||
|
||||
async function loadCategories() {
|
||||
catalogLoading.value = true;
|
||||
try {
|
||||
const result = await api<{ categories: { code: number; name: string }[] }>("/api/admin/nqi/catalog");
|
||||
categories.value = result.categories;
|
||||
if (categoryCode.value == null && categories.value.length) categoryCode.value = categories.value[0].code;
|
||||
if (categoryCode.value != null) await loadTables(categoryCode.value);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "查询分类没有获取到");
|
||||
} finally {
|
||||
catalogLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTables(code: number) {
|
||||
categoryCode.value = code;
|
||||
tablesLoading.value = true;
|
||||
try {
|
||||
const result = await api<{ tables: { tablename: string; name: string }[] }>(`/api/admin/nqi/catalog?code=${code}`);
|
||||
categoryTables.value = result.tables;
|
||||
} catch (error) {
|
||||
categoryTables.value = [];
|
||||
toast.error(error instanceof Error ? error.message : "数据表没有获取到");
|
||||
} finally {
|
||||
tablesLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function setPicked(names: string[]) {
|
||||
const code = categoryCode.value;
|
||||
const category = categories.value.find((item) => item.code === code)?.name || "";
|
||||
const current = categoryTables.value
|
||||
.filter((item) => names.includes(item.tablename))
|
||||
.map((item) => ({ code: code || 0, category, tablename: item.tablename, name: item.name }));
|
||||
chosen.value = [...chosen.value.filter((item) => item.code !== code), ...current];
|
||||
}
|
||||
|
||||
function selectCategory() {
|
||||
setPicked(categoryTables.value.map((item) => item.tablename));
|
||||
}
|
||||
|
||||
function removeTable(tablename: string) {
|
||||
chosen.value = chosen.value.filter((item) => item.tablename !== tablename);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
@@ -53,8 +144,12 @@ async function load() {
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (kind.value === "nqi" && !chosen.value.length) {
|
||||
toast.error("请选择要采集的表");
|
||||
return false;
|
||||
}
|
||||
const config = kind.value === "nqi"
|
||||
? { url: url.value }
|
||||
? { tables: chosen.value, timeMode: timeMode.value, timeCount: timeCount.value, city: city.value }
|
||||
: { protocol: protocol.value, host: host.value, port: port.value, username: username.value, password: password.value, path: path.value };
|
||||
const body = { name: name.value, kind: kind.value, periodDays: periodDays.value, enabled: enabled.value, config };
|
||||
try {
|
||||
@@ -140,7 +235,7 @@ onMounted(load);
|
||||
</div>
|
||||
</section>
|
||||
<n-modal v-model:show="show" class="app-dialog app-dialog-wide" preset="dialog" :show-icon="false" title="采集" positive-text="保存" negative-text="取消" @positive-click="save">
|
||||
<div class="form-row"><label>来源</label><n-select v-model:value="kind" :options="[{ label: 'FTP/SFTP', value: 'ftp' }, { label: 'NQI', value: 'nqi' }]" /></div>
|
||||
<div class="form-row"><label>来源</label><n-select :value="kind" :options="[{ label: 'FTP/SFTP', value: 'ftp' }, { label: 'NQI', value: 'nqi' }]" @update:value="changeKind" /></div>
|
||||
<div class="form-row"><label>名称</label><n-input v-model:value="name" /></div>
|
||||
<p class="form-section">连接</p>
|
||||
<template v-if="kind === 'ftp'">
|
||||
@@ -152,7 +247,23 @@ onMounted(load);
|
||||
<div class="form-row"><label>路径</label><n-input v-model:value="path" /></div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="form-row"><label>地址</label><n-input v-model:value="url" /></div>
|
||||
<div class="form-row"><label>查询分类</label><n-select :value="categoryCode" :options="categoryOptions" :loading="catalogLoading" @update:value="loadTables" /></div>
|
||||
<div class="form-row">
|
||||
<label>数据表</label>
|
||||
<div>
|
||||
<n-select multiple filterable :value="pickedNames" :options="tableOptions" :loading="tablesLoading" @update:value="setPicked" />
|
||||
<n-button size="small" quaternary :disabled="!categoryTables.length" @click="selectCategory">分类全选</n-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="chosen.length" class="form-row">
|
||||
<label>已选</label>
|
||||
<div class="picked-tables">
|
||||
<button v-for="item in chosen" :key="item.tablename" type="button" @click="removeTable(item.tablename)">{{ item.name }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row"><label>数据时间</label><n-select v-model:value="timeMode" :options="timeOptions" /></div>
|
||||
<div v-if="needsCount" class="form-row"><label>{{ countLabel }}</label><n-input-number v-model:value="timeCount" :min="1" :max="366" :show-button="false" /></div>
|
||||
<div class="form-row"><label>城市</label><n-input v-model:value="city" placeholder="不填则不按城市过滤" /></div>
|
||||
</template>
|
||||
<p class="form-section">周期</p>
|
||||
<div class="form-row"><label>周期(天)</label><n-input-number v-model:value="periodDays" :min="1" :max="31" :show-button="false" /></div>
|
||||
@@ -160,3 +271,19 @@ onMounted(load);
|
||||
</n-modal>
|
||||
</Shell>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.picked-tables {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.picked-tables button {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
padding: 2px 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user