feat: 采集按分组选表和固定时刻运行,号池可检查凭证,管理页不再退出

This commit is contained in:
2026-11-09 17:55:31 +08:00
parent 152cf92df9
commit 78ad5cea6b
19 changed files with 554 additions and 247 deletions
+2 -2
View File
@@ -29,10 +29,10 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
## Capabilities and Constraints ## Capabilities and Constraints
- 用户功能:提交任务,取得结果文件。多个任务可以并行,也可以排队。 - 用户功能:提交任务,取得结果文件。多个任务可以并行,也可以排队。
- 管理功能:首页运行面板查看大数据账号池指标(总数、新增、有效、失效、未退出)。选择登录方式,管理用户,管理大数据账号池,设置凭证刷新间隔和并行数量,手动添加账号。大数据账号池里的账号只有用户级别,不能设为管理员。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。用户管理可为用户角色改密;管理员账号只能由本人修改。 - 管理功能:首页运行面板查看号池指标(总数、新增、有效、失效、未退出)。选择登录方式,管理用户,管理号池,设置凭证刷新间隔和并行数量,手动添加账号。号池里的账号只有用户级别,不能设为管理员。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。用户管理可为用户角色改密;管理员账号只能由本人修改。
- 登录先看账号名。账号名与本系统管理员一致时,只校验本系统密码,不处理图形验证码,也不交给大数据平台。密码不正确就停在这里。 - 登录先看账号名。账号名与本系统管理员一致时,只校验本系统密码,不处理图形验证码,也不交给大数据平台。密码不正确就停在这里。
- 其余账号只启用一种登录方式。大数据平台登录时,登录页直接显示图形验证码,登录失败后更换验证码;登录成功后该账号进入账号池。自有账号由管理员添加,不能自行注册,登录不显示验证码,也不发送手机验证码。 - 其余账号只启用一种登录方式。大数据平台登录时,登录页直接显示图形验证码,登录失败后更换验证码;登录成功后该账号进入账号池。自有账号由管理员添加,不能自行注册,登录不显示验证码,也不发送手机验证码。
- 托管到 Metrix 时,用户入口只用本系统账号。登录方式为自有账号时,用户用本系统用户账号登录,管理员可以维护这些账号。登录方式为大数据平台时,普通用户仍走验证码和短信,账号进入账号池,不写入 Metrix。管理入口只认 Metrix 应用管理员,从应用托管进入,用户登录页没有管理员登录。管理页可以返回应用托管。退出用户账号回到本系统登录页。 - 托管到 Metrix 时,用户入口只用本系统账号。登录方式为自有账号时,用户用本系统用户账号登录,管理员可以维护这些账号。登录方式为大数据平台时,普通用户仍走验证码和短信,账号进入账号池,不写入 Metrix。管理入口只认 Metrix 应用管理员,从应用托管进入,用户登录页没有管理员登录。管理页跟随 Metrix 登录,不提供退出,也不提供返回应用托管。退出用户账号回到本系统登录页。
- Metrix 应用包内含接口与排队进程使用的容器镜像,并声明持久数据目录。数据库连接由应用自己的环境变量配置。接口与排队进程可同时启动,应用会等待数据库并自动完成安装,不显示安装页。 - Metrix 应用包内含接口与排队进程使用的容器镜像,并声明持久数据目录。数据库连接由应用自己的环境变量配置。接口与排队进程可同时启动,应用会等待数据库并自动完成安装,不显示安装页。
- 操作结果用 toast 提示。最短显示 2.5 秒;超过 6 个字后,每多一个字加 0.3 秒;最长 8 秒。每条可以单独关闭。 - 操作结果用 toast 提示。最短显示 2.5 秒;超过 6 个字后,每多一个字加 0.3 秒;最长 8 秒。每条可以单独关闭。
- 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。 - 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。
+1 -1
View File
@@ -69,6 +69,6 @@ backend\.venv\Scripts\python.exe scripts\package_metrix.py --npm-registry https:
- 用户入口 `/apps/decomeval/` 使用本系统自己的账号。登录方式为自有账号时,管理员在管理页维护这些用户;登录方式为大数据平台时,登录页使用验证码和短信,成功后进入账号池。 - 用户入口 `/apps/decomeval/` 使用本系统自己的账号。登录方式为自有账号时,管理员在管理页维护这些用户;登录方式为大数据平台时,登录页使用验证码和短信,成功后进入账号池。
- 管理入口只认 Metrix 的应用管理员,从应用托管的「管理」进入 `/apps/decomeval/admin/`。用户登录页没有管理员登录。 - 管理入口只认 Metrix 的应用管理员,从应用托管的「管理」进入 `/apps/decomeval/admin/`。用户登录页没有管理员登录。
- 管理页侧栏是「返回应用托管」。用户页不显示返回平台。退出用户账号回到本系统登录页。 - 管理页跟随 Metrix 登录,侧栏不提供退出,也不提供返回应用托管。用户页不显示返回平台。退出用户账号回到本系统登录页。
应用清单里用户账号来源是 `app`,管理账号来源是 `metrix`。大数据平台用户不需要 Metrix 账号。 应用清单里用户账号来源是 `app`,管理账号来源是 `metrix`。大数据平台用户不需要 Metrix 账号。
@@ -0,0 +1,20 @@
"""号池记录账号加入时间,刷新时间继续用 saved_at。"""
from alembic import op
import sqlalchemy as sa
revision = "0005_account_created_at"
down_revision = "0004_worker_concurrency"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("nqi_account", sa.Column("created_at", sa.DateTime(timezone=True), nullable=True))
op.execute("UPDATE nqi_account SET created_at = saved_at WHERE created_at IS NULL")
with op.batch_alter_table("nqi_account") as batch:
batch.alter_column("created_at", existing_type=sa.DateTime(timezone=True), nullable=False)
def downgrade() -> None:
op.drop_column("nqi_account", "created_at")
+68 -20
View File
@@ -15,11 +15,12 @@ from app.config import env_database, hosted, installed, result_dir
from app.install import InstallError, perform_install from app.install import InstallError, perform_install
from app.db import get_session, session_scope from app.db import get_session, session_scope
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
from app.nqi.adhoc import TIME_MODES, categories, tables, time_window from app.collect.schedule import next_run_at, parse_schedule
from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, tables, time_window
from app.nqi.client import NqiAuthError, NqiClient, NqiError from app.nqi.client import NqiAuthError, NqiClient, NqiError
from app.nqi.flows import drop, purge, remember, take from app.nqi.flows import drop, purge, remember, take
from app.security import hash_password, issue_token, verify_password from app.security import hash_password, issue_token, verify_password
from app.tasks.runner import check_concurrency, check_period, check_refresh, enqueue_export from app.tasks.runner import check_concurrency, check_refresh, enqueue_export
router = APIRouter(prefix="/api") router = APIRouter(prefix="/api")
# 在响应发出前提交,客户端紧接着发出的请求才能读到刚写入的内容。 # 在响应发出前提交,客户端紧接着发出的请求才能读到刚写入的内容。
@@ -443,19 +444,67 @@ def admin_dashboard(actor: Actor = Depends(current_actor), session: Session = db
def list_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: def list_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor) require_admin(actor)
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all() rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
return {"accounts": [_public_account(row) for row in rows]}
@router.post("/admin/pool/check")
def check_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
for row in rows:
_check_account(row)
return {"accounts": [_public_account(row) for row in rows]}
@router.post("/admin/pool/{account_id}/check")
def check_pool_account(account_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
account = session.get(NqiAccount, account_id)
if account is None:
raise _bad("账号不存在", 404)
_check_account(account)
return {"account": _public_account(account)}
def _public_account(row: NqiAccount) -> dict:
return { return {
"accounts": [
{
"id": row.id, "id": row.id,
"loginId": row.login_id, "loginId": row.login_id,
"userName": row.user_name, "userName": row.user_name,
"cityName": row.city_name, "cityName": row.city_name,
"sessionOpen": row.session_open,
"credentialValid": row.credential_valid, "credentialValid": row.credential_valid,
"savedAt": row.saved_at.isoformat() if row.saved_at else "",
"createdAt": row.created_at.isoformat() if row.created_at else "",
} }
for row in rows
]
} def _check_account(account: NqiAccount) -> None:
cookies = list(account.cookies or [])
if not cookies:
account.credential_valid = False
account.saved_at = utcnow()
return
async def run() -> tuple[bool, list]:
client = NqiClient()
try:
client.import_cookies(cookies)
await client.current_user()
await client.renew_ticket()
return True, client.export_cookies()
except NqiAuthError:
return False, cookies
finally:
await client.aclose()
try:
valid, refreshed = asyncio.run(run())
except NqiError as exc:
raise _bad(str(exc)) from exc
account.credential_valid = valid
account.saved_at = utcnow()
if valid:
account.cookies = refreshed
@router.delete("/admin/pool/{account_id}") @router.delete("/admin/pool/{account_id}")
@@ -469,7 +518,7 @@ def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session:
@router.get("/admin/nqi/catalog") @router.get("/admin/nqi/catalog")
def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: def nqi_catalog(code: int | None = None, tree: bool = False, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor) require_admin(actor)
cookies = _pool_cookies(session) cookies = _pool_cookies(session)
@@ -479,6 +528,8 @@ def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor),
client.import_cookies(cookies) client.import_cookies(cookies)
await client.current_user() await client.current_user()
try: try:
if tree:
return {"groups": await catalog_tree(client)}
if code is None: if code is None:
return {"categories": await categories(client)} return {"categories": await categories(client)}
return {"tables": await tables(client, code)} return {"tables": await tables(client, code)}
@@ -513,7 +564,7 @@ def list_sources(actor: Actor = Depends(current_actor), session: Session = db_se
@router.post("/admin/sources") @router.post("/admin/sources")
def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor) require_admin(actor)
source = CollectionSource(name="采集", kind="ftp", period_days=1, config={}, enabled=True, next_run_at=utcnow()) source = CollectionSource(name="采集", kind="nqi", period_days=1, config={}, enabled=True)
_apply_source(source, body) _apply_source(source, body)
session.add(source) session.add(source)
session.flush() session.flush()
@@ -545,14 +596,9 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
source.name = str(body.get("name") or "").strip() or source.name source.name = str(body.get("name") or "").strip() or source.name
if "kind" in body: if "kind" in body:
kind = str(body.get("kind") or "") kind = str(body.get("kind") or "")
if kind not in {"ftp", "nqi"}: if kind != "nqi":
raise _bad("采集来源不正确") raise _bad("只采集 NQI")
source.kind = kind source.kind = kind
if "periodDays" in body:
try:
source.period_days = check_period(int(body.get("periodDays")))
except (TypeError, ValueError) as exc:
raise _bad(str(exc)) from exc
if "enabled" in body: if "enabled" in body:
source.enabled = bool(body.get("enabled")) source.enabled = bool(body.get("enabled"))
if "config" in body and isinstance(body.get("config"), dict): if "config" in body and isinstance(body.get("config"), dict):
@@ -560,8 +606,9 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
current = dict(source.config or {}) current = dict(source.config or {})
if not incoming.get("password"): if not incoming.get("password"):
incoming["password"] = current.get("password") or "" incoming["password"] = current.get("password") or ""
if source.kind == "nqi" and "tables" in incoming: if source.kind == "nqi":
incoming = _nqi_tables(incoming) incoming = _nqi_tables(incoming)
source.next_run_at = next_run_at(incoming["schedule"], utcnow())
source.config = incoming source.config = incoming
@@ -591,12 +638,13 @@ def _nqi_tables(config: dict) -> dict:
raise _bad("时间数量不正确") from exc raise _bad("时间数量不正确") from exc
try: try:
time_window(mode, count, date.today()) time_window(mode, count, date.today())
schedule = parse_schedule(config.get("schedule"))
except ValueError as exc: except ValueError as exc:
raise _bad(str(exc)) from exc raise _bad(str(exc)) from exc
city = str(config.get("city") or "").strip() city = str(config.get("city") or "").strip()
if len(city) > 32: if len(city) > 32:
raise _bad("城市名称过长") raise _bad("城市名称过长")
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city} return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city, "schedule": schedule}
def _public_task(task: ExportTask) -> dict: def _public_task(task: ExportTask) -> dict:
@@ -633,7 +681,7 @@ def _pool_dashboard(rows: list[NqiAccount]) -> dict:
added_today = 0 added_today = 0
added_week = 0 added_week = 0
for row in rows: for row in rows:
saved = _as_utc(row.saved_at) saved = _as_utc(row.created_at)
if saved is not None: if saved is not None:
day = saved.date() day = saved.date()
key = day.isoformat() key = day.isoformat()
+1 -35
View File
@@ -1,46 +1,12 @@
"""从 FTP/SFTP 或已登录的大数据平台取回表格。""" """从已登录的大数据平台取回表格。"""
from __future__ import annotations from __future__ import annotations
import io
from ftplib import FTP
from urllib.parse import urlparse from urllib.parse import urlparse
import paramiko
from app.nqi.client import NqiClient from app.nqi.client import NqiClient
def fetch_ftp(config: dict) -> tuple[str, bytes]:
protocol = str(config.get("protocol") or "sftp")
host = str(config.get("host") or "")
path = str(config.get("path") or "")
username = str(config.get("username") or "")
password = str(config.get("password") or "")
port = int(config.get("port") or (21 if protocol == "ftp" else 22))
if not host or not path:
raise ValueError("请填写主机和路径")
if protocol == "ftp":
ftp = FTP()
ftp.connect(host, port, timeout=30)
ftp.login(username, password)
buffer = io.BytesIO()
ftp.retrbinary(f"RETR {path}", buffer.write)
ftp.quit()
return path.rsplit("/", 1)[-1], buffer.getvalue()
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
if sftp is None:
transport.close()
raise ValueError("无法连接 SFTP")
buffer = io.BytesIO()
sftp.getfo(path, buffer)
sftp.close()
transport.close()
return path.rsplit("/", 1)[-1], buffer.getvalue()
async def fetch_nqi(client: NqiClient, config: dict) -> tuple[str, bytes]: async def fetch_nqi(client: NqiClient, config: dict) -> tuple[str, bytes]:
address = str(config.get("url") or "").strip() address = str(config.get("url") or "").strip()
if not address: if not address:
+67
View File
@@ -0,0 +1,67 @@
"""采集按每周某天或每月某日的时刻运行。时间按北京时间计算。"""
from __future__ import annotations
import calendar
import re
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
ZONE = ZoneInfo("Asia/Shanghai")
TIME_RE = re.compile(r"^(\d{2}):(\d{2})$")
def parse_schedule(raw: object) -> dict:
if not isinstance(raw, dict):
raise ValueError("请设置采集周期")
mode = raw.get("mode")
if mode not in {"weekly", "monthly"}:
raise ValueError("请设置采集周期")
hour, minute = _clock(raw.get("time"))
if mode == "weekly":
weekday = _int(raw.get("weekday"), "请选择星期")
if weekday < 1 or weekday > 7:
raise ValueError("请选择星期")
return {"mode": mode, "weekday": weekday, "time": f"{hour:02d}:{minute:02d}"}
month_day = _int(raw.get("monthDay"), "请选择日期")
if month_day < 1 or month_day > 31:
raise ValueError("请选择日期")
return {"mode": mode, "monthDay": month_day, "time": f"{hour:02d}:{minute:02d}"}
def next_run_at(schedule: dict, now: datetime) -> datetime:
local = now.astimezone(ZONE)
hour, minute = _clock(schedule["time"])
if schedule["mode"] == "weekly":
target = local.replace(hour=hour, minute=minute, second=0, microsecond=0)
target += timedelta(days=(schedule["weekday"] - 1 - local.weekday()) % 7)
if target <= local:
target += timedelta(days=7)
else:
target = _monthly(local.year, local.month, schedule["monthDay"], hour, minute)
if target <= local:
year, month = (local.year + 1, 1) if local.month == 12 else (local.year, local.month + 1)
target = _monthly(year, month, schedule["monthDay"], hour, minute)
return target.astimezone(timezone.utc)
def _monthly(year: int, month: int, day: int, hour: int, minute: int) -> datetime:
last = calendar.monthrange(year, month)[1]
return datetime(year, month, min(day, last), hour, minute, tzinfo=ZONE)
def _clock(value: object) -> tuple[int, int]:
match = TIME_RE.fullmatch(str(value or ""))
if not match:
raise ValueError("请填写采集时间")
hour, minute = int(match.group(1)), int(match.group(2))
if hour > 23 or minute > 59:
raise ValueError("请填写采集时间")
return hour, minute
def _int(value: object, message: str) -> int:
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValueError(message) from exc
+1
View File
@@ -51,6 +51,7 @@ class NqiAccount(Base):
role: Mapped[str] = mapped_column(String(16), default="user") role: Mapped[str] = mapped_column(String(16), default="user")
session_open: Mapped[bool] = mapped_column(Boolean, default=True) session_open: Mapped[bool] = mapped_column(Boolean, default=True)
credential_valid: Mapped[bool] = mapped_column(Boolean, default=True) credential_valid: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
+32 -5
View File
@@ -85,19 +85,46 @@ async def categories(client: NqiClient) -> list[dict]:
return result return result
async def tables(client: NqiClient, code: int) -> list[dict]: async def catalog_tree(client: NqiClient) -> list[dict]:
await ensure_session(client) await ensure_session(client)
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code}) 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): if not isinstance(payload, list):
raise NqiError("没有取到这个分类下的表") return []
result = [] result = []
for row in payload: for row in payload:
if not isinstance(row, dict): if not isinstance(row, dict):
continue continue
tablename = str(row.get("tablename") or "").strip() tablename = str(row.get("tablename") or "").strip()
name = str(row.get("tablename_cn") or tablename).strip() title = str(row.get("tablename_cn") or tablename).strip()
if tablename: if tablename:
result.append({"tablename": tablename, "name": name}) 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 return result
+17 -4
View File
@@ -10,7 +10,8 @@ from datetime import date, datetime, timedelta, timezone
from sqlalchemy import select from sqlalchemy import select
from app.collect.io import parse_upload, write_table from app.collect.io import parse_upload, write_table
from app.collect.remote import fetch_ftp, fetch_nqi from app.collect.remote import fetch_nqi
from app.collect.schedule import next_run_at
from app.config import data_dir, 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.db import session_scope
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
@@ -162,9 +163,7 @@ def execute_collection(source_id: int) -> None:
else: else:
cookies = [] cookies = []
try: try:
if kind == "ftp": if kind == "nqi":
name, content = fetch_ftp(config)
elif kind == "nqi":
if not cookies: if not cookies:
raise ValueError("账号池里没有可用凭证") raise ValueError("账号池里没有可用凭证")
if config.get("tables"): if config.get("tables"):
@@ -278,10 +277,24 @@ def scan_sources() -> None:
with session_scope() as session: with session_scope() as session:
sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all() sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all()
for source in sources: for source in sources:
if source.kind != "nqi":
source.enabled = False
source.last_error = "不再从 FTP 采集"
continue
schedule = (source.config or {}).get("schedule")
if not isinstance(schedule, dict) or not schedule.get("mode"):
if source.next_run_at is not None and source.next_run_at > now: if source.next_run_at is not None and source.next_run_at > now:
continue continue
source.next_run_at = now + timedelta(days=source.period_days) source.next_run_at = now + timedelta(days=source.period_days)
due_ids.append(source.id) due_ids.append(source.id)
continue
if source.next_run_at is None:
source.next_run_at = next_run_at(schedule, now)
continue
if source.next_run_at > now:
continue
source.next_run_at = next_run_at(schedule, now)
due_ids.append(source.id)
for source_id in due_ids: for source_id in due_ids:
enqueue_collection(source_id) enqueue_collection(source_id)
-1
View File
@@ -9,5 +9,4 @@ cryptography
python-multipart python-multipart
openpyxl openpyxl
xlwt xlwt
paramiko
pytest pytest
+2 -2
View File
@@ -229,8 +229,8 @@ def test_admin_dashboard_and_user_password(client: TestClient):
assert empty.json()["pool"]["total"] == 0 assert empty.json()["pool"]["total"] == 0
now = utcnow() now = utcnow()
with session_scope() as session: with session_scope() as session:
session.add(NqiAccount(login_id="a1", city_name="广州", credential_valid=True, session_open=True, saved_at=now)) session.add(NqiAccount(login_id="a1", city_name="广州", credential_valid=True, session_open=True, created_at=now, saved_at=now))
session.add(NqiAccount(login_id="a2", city_name="深圳", credential_valid=False, session_open=False, saved_at=now - timedelta(days=2))) session.add(NqiAccount(login_id="a2", city_name="深圳", credential_valid=False, session_open=False, created_at=now - timedelta(days=2), saved_at=now - timedelta(days=2)))
stats = client.get("/api/admin/dashboard", headers=headers).json()["pool"] stats = client.get("/api/admin/dashboard", headers=headers).json()["pool"]
assert stats["total"] == 2 assert stats["total"] == 2
assert stats["valid"] == 1 assert stats["valid"] == 1
+20
View File
@@ -0,0 +1,20 @@
from datetime import datetime
from zoneinfo import ZoneInfo
from app.collect.schedule import next_run_at
ZONE = ZoneInfo("Asia/Shanghai")
def test_weekly_and_monthly_next_run():
now = datetime(2026, 11, 9, 10, 0, tzinfo=ZONE)
weekly_later = next_run_at({"mode": "weekly", "weekday": 1, "time": "18:00"}, now)
assert weekly_later.astimezone(ZONE).strftime("%Y-%m-%d %H:%M") == "2026-11-09 18:00"
weekly_next = next_run_at({"mode": "weekly", "weekday": 1, "time": "08:00"}, now)
assert weekly_next.astimezone(ZONE).strftime("%Y-%m-%d %H:%M") == "2026-11-16 08:00"
monthly_soon = next_run_at({"mode": "monthly", "monthDay": 15, "time": "09:30"}, now)
assert monthly_soon.astimezone(ZONE).strftime("%Y-%m-%d %H:%M") == "2026-11-15 09:30"
monthly_passed = next_run_at({"mode": "monthly", "monthDay": 9, "time": "08:00"}, now)
assert monthly_passed.astimezone(ZONE).strftime("%Y-%m-%d %H:%M") == "2026-12-09 08:00"
month_end = next_run_at({"mode": "monthly", "monthDay": 31, "time": "08:00"}, datetime(2026, 2, 1, 0, 0, tzinfo=ZONE))
assert month_end.astimezone(ZONE).strftime("%Y-%m-%d %H:%M") == "2026-02-28 08:00"
+89 -11
View File
@@ -1,22 +1,75 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from "vue"; import { computed, onMounted, ref } from "vue";
import { NButton, NModal, useDialog } from "naive-ui"; import { NButton, NIcon, NInput, NModal, NTooltip, useDialog } from "naive-ui";
import { CheckmarkCircleOutline, TrashOutline } from "@vicons/ionicons5";
import Shell from "../../shell/Shell.vue"; import Shell from "../../shell/Shell.vue";
import LoginView from "../auth/LoginView.vue"; import LoginView from "../auth/LoginView.vue";
import { api } from "../../shared/http"; import { api } from "../../shared/http";
import { useToast } from "../../shared/toast"; import { useToast } from "../../shared/toast";
interface Account { id: number; loginId: string; userName: string; cityName: string; sessionOpen: boolean; credentialValid: boolean } interface Account {
id: number;
loginId: string;
userName: string;
cityName: string;
credentialValid: boolean;
savedAt: string;
createdAt: string;
}
const accounts = ref<Account[]>([]); const accounts = ref<Account[]>([]);
const keyword = ref("");
const show = ref(false); const show = ref(false);
const checkingAll = ref(false);
const checkingId = ref<number | null>(null);
const dialog = useDialog(); const dialog = useDialog();
const toast = useToast(); const toast = useToast();
const visible = computed(() => {
const text = keyword.value.trim().toLowerCase();
if (!text) return accounts.value;
return accounts.value.filter((account) =>
[account.loginId, account.userName, account.cityName].some((value) => value.toLowerCase().includes(text))
);
});
function clock(value: string) {
const date = new Date(value);
if (!value || Number.isNaN(date.getTime())) return "—";
const pad = (part: number) => String(part).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
async function load() { async function load() {
const result = await api<{ accounts: Account[] }>("/api/admin/pool"); const result = await api<{ accounts: Account[] }>("/api/admin/pool");
accounts.value = result.accounts; accounts.value = result.accounts;
} }
async function check(account: Account) {
checkingId.value = account.id;
try {
const result = await api<{ account: Account }>(`/api/admin/pool/${account.id}/check`, { method: "POST" });
accounts.value = accounts.value.map((item) => item.id === result.account.id ? result.account : item);
toast.success(result.account.credentialValid ? "凭证有效" : "凭证已失效");
} catch (error) {
toast.error(error instanceof Error ? error.message : "检查失败");
} finally {
checkingId.value = null;
}
}
async function checkAll() {
checkingAll.value = true;
try {
const result = await api<{ accounts: Account[] }>("/api/admin/pool/check", { method: "POST" });
accounts.value = result.accounts;
const invalid = result.accounts.filter((item) => !item.credentialValid).length;
toast.success(invalid ? `${invalid} 个凭证已失效` : "全部凭证有效");
} catch (error) {
toast.error(error instanceof Error ? error.message : "检查失败");
} finally {
checkingAll.value = false;
}
}
async function remove(id: number) { async function remove(id: number) {
try { try {
await api(`/api/admin/pool/${id}`, { method: "DELETE" }); await api(`/api/admin/pool/${id}`, { method: "DELETE" });
@@ -30,7 +83,7 @@ async function remove(id: number) {
function confirmRemove(account: Account) { function confirmRemove(account: Account) {
dialog.warning({ dialog.warning({
title: "删除账号", title: "删除账号",
content: `从大数据账号池删除 ${account.loginId}?`, content: `从号池删除 ${account.loginId}?`,
positiveText: "删除", positiveText: "删除",
negativeText: "取消", negativeText: "取消",
positiveButtonProps: { type: "error" }, positiveButtonProps: { type: "error" },
@@ -45,11 +98,15 @@ onMounted(load);
<Shell> <Shell>
<section class="page admin-page"> <section class="page admin-page">
<header class="page-head"> <header class="page-head">
<h2>大数据账号池</h2> <h2>号池</h2>
<div class="page-head-actions">
<n-input v-model:value="keyword" clearable placeholder="搜索账号、姓名或地市" />
<n-button :loading="checkingAll" @click="checkAll">检查</n-button>
<n-button type="primary" @click="show = true">添加账号</n-button> <n-button type="primary" @click="show = true">添加账号</n-button>
</div>
</header> </header>
<div class="admin-scroll"> <div class="admin-scroll">
<div v-if="accounts.length" class="surface table-card"> <div v-if="visible.length" class="surface table-card">
<table class="admin-table"> <table class="admin-table">
<thead> <thead>
<tr> <tr>
@@ -57,24 +114,45 @@ onMounted(load);
<th>姓名</th> <th>姓名</th>
<th>地市</th> <th>地市</th>
<th>凭证</th> <th>凭证</th>
<th>登录</th> <th>刷新凭证时间</th>
<th>加入时间</th>
<th class="col-actions">操作</th> <th class="col-actions">操作</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="account in accounts" :key="account.id"> <tr v-for="account in visible" :key="account.id">
<td>{{ account.loginId }}</td> <td>{{ account.loginId }}</td>
<td>{{ account.userName }}</td> <td>{{ account.userName }}</td>
<td>{{ account.cityName }}</td> <td>{{ account.cityName }}</td>
<td :class="account.credentialValid ? 'status-ok' : 'status-bad'">{{ account.credentialValid ? "有效" : "失效" }}</td> <td :class="account.credentialValid ? 'status-ok' : 'status-bad'">{{ account.credentialValid ? "有效" : "失效" }}</td>
<td :class="account.sessionOpen ? 'status-run' : 'status-wait'">{{ account.sessionOpen ? "未退出" : "已退出" }}</td> <td>{{ clock(account.savedAt) }}</td>
<td class="col-actions"><n-button size="small" quaternary @click="confirmRemove(account)">删除</n-button></td> <td>{{ clock(account.createdAt) }}</td>
<td class="col-actions">
<div class="row-actions">
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary circle aria-label="检查" :loading="checkingId === account.id" :disabled="checkingAll" @click="check(account)">
<template #icon><n-icon :component="CheckmarkCircleOutline" /></template>
</n-button>
</template>
检查
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary circle aria-label="删除" @click="confirmRemove(account)">
<template #icon><n-icon :component="TrashOutline" /></template>
</n-button>
</template>
删除
</n-tooltip>
</div>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div> </div>
<div v-else class="surface empty-card"> <div v-else class="surface empty-card">
<p class="admin-status">没有账号</p> <p class="admin-status">{{ keyword.trim() ? "没有匹配的账号" : "没有账号" }}</p>
</div> </div>
</div> </div>
</section> </section>
+1 -1
View File
@@ -91,7 +91,7 @@ onMounted(load);
</n-radio-group> </n-radio-group>
</div> </div>
<div class="form-row"> <div class="form-row">
<label for="refresh-seconds">凭证刷新间隔<n-tooltip><template #trigger><n-icon class="hint-mark" :size="16"><HelpCircleOutline /></n-icon></template>大数据账号池里的平台凭证按这个间隔刷新。</n-tooltip></label> <label for="refresh-seconds">凭证刷新间隔<n-tooltip><template #trigger><n-icon class="hint-mark" :size="16"><HelpCircleOutline /></n-icon></template>号池里的平台凭证按这个间隔刷新。</n-tooltip></label>
<div class="setting-control setting-refresh"> <div class="setting-control setting-refresh">
<n-input-number id="refresh-seconds" v-model:value="seconds" size="small" button-placement="both" :min="60" :max="86400" :precision="0" /> <n-input-number id="refresh-seconds" v-model:value="seconds" size="small" button-placement="both" :min="60" :max="86400" :precision="0" />
<span class="setting-unit">秒</span> <span class="setting-unit">秒</span>
+195 -140
View File
@@ -1,47 +1,53 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from "vue"; import { computed, h, onMounted, ref } from "vue";
import { NButton, NInput, NInputNumber, NModal, NSelect, NSwitch, useDialog } from "naive-ui"; import { NButton, NIcon, NInput, NInputNumber, NModal, NSelect, NSwitch, NTimePicker, NTooltip, useDialog } from "naive-ui";
import type { SelectRenderTag } from "naive-ui";
import { CreateOutline, TrashOutline } from "@vicons/ionicons5";
import Shell from "../../shell/Shell.vue"; import Shell from "../../shell/Shell.vue";
import { api } from "../../shared/http"; import { api } from "../../shared/http";
import { useToast } from "../../shared/toast"; import { useToast } from "../../shared/toast";
interface Source {
id: number;
name: string;
kind: string;
periodDays: number;
enabled: boolean;
lastError: string;
config: Record<string, unknown>;
}
interface QueryTable { interface QueryTable {
code: number; code: number;
category: string; category: string;
tablename: string; tablename: string;
name: string; name: string;
} }
interface Schedule {
mode: "weekly" | "monthly";
weekday?: number;
monthDay?: number;
time: string;
}
interface Source {
id: number;
name: string;
kind: string;
enabled: boolean;
lastError: string;
config: { tables?: QueryTable[]; timeMode?: string; timeCount?: number; city?: string; schedule?: Schedule };
}
interface Group {
code: number;
name: string;
tables: { tablename: string; name: string }[];
}
const sources = ref<Source[]>([]); const sources = ref<Source[]>([]);
const show = ref(false); const show = ref(false);
const details = ref(false);
const editing = ref<Source | null>(null); const editing = ref<Source | null>(null);
const name = ref(""); const name = ref("");
const kind = ref("ftp");
const periodDays = ref(1);
const enabled = ref(true); const enabled = ref(true);
const host = ref(""); const groups = ref<Group[]>([]);
const port = ref(22);
const protocol = ref("sftp");
const username = ref("");
const password = ref("");
const path = 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 chosen = ref<QueryTable[]>([]);
const timeMode = ref("prev_month"); const timeMode = ref("prev_month");
const timeCount = ref(1); const timeCount = ref(1);
const city = ref(""); const city = ref("");
const scheduleMode = ref<"weekly" | "monthly">("weekly");
const weekday = ref(1);
const monthDay = ref(1);
const clock = ref("08:00");
const catalogLoading = ref(false); const catalogLoading = ref(false);
const tablesLoading = ref(false);
const dialog = useDialog(); const dialog = useDialog();
const toast = useToast(); const toast = useToast();
const timeOptions = [ const timeOptions = [
@@ -52,90 +58,50 @@ const timeOptions = [
{ label: "前几月", value: "prev_months" }, { label: "前几月", value: "prev_months" },
{ label: "前多少天", value: "prev_days" }, { label: "前多少天", value: "prev_days" },
]; ];
const weekdays = ["一", "二", "三", "四", "五", "六", "日"].map((label, index) => ({ label: `周${label}`, value: index + 1 }));
const monthDays = Array.from({ length: 31 }, (_, index) => ({ label: `${index + 1} 日`, value: index + 1 }));
const needsCount = computed(() => ["prev_weeks", "prev_months", "prev_days"].includes(timeMode.value)); const needsCount = computed(() => ["prev_weeks", "prev_months", "prev_days"].includes(timeMode.value));
const countLabel = computed(() => (timeMode.value === "prev_weeks" ? "周数" : timeMode.value === "prev_months" ? "月数" : "天数")); 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(() => groups.value.map((group) => ({
const tableOptions = computed(() => categoryTables.value.map((item) => ({ label: item.name, value: item.tablename }))); type: "group" as const,
const pickedNames = computed(() => chosen.value.filter((item) => item.code === categoryCode.value).map((item) => item.tablename)); label: group.name,
key: String(group.code),
children: group.tables.map((table) => ({ label: table.name, value: table.tablename })),
})));
const picked = computed(() => chosen.value.map((item) => item.tablename));
const pickedText = computed(() => chosen.value.length ? `已选 ${chosen.value.length}:${chosen.value.map((item) => item.name).join("、")}` : "");
const renderTag: SelectRenderTag = () => h("span", { class: "picker-inline" }, pickedText.value || "请选择表");
function scheduleText(source: Source) {
const schedule = source.config.schedule;
if (!schedule) return "未设置";
const clockText = schedule.time || "";
if (schedule.mode === "monthly") return `每月 ${schedule.monthDay} 日 ${clockText}`;
const label = weekdays.find((item) => item.value === schedule.weekday)?.label || "";
return `每${label} ${clockText}`;
}
function reset(source?: Source) { function reset(source?: Source) {
editing.value = source || null; editing.value = source || null;
name.value = source?.name || ""; name.value = source?.name || "";
kind.value = source?.kind || "ftp";
periodDays.value = source?.periodDays || 1;
enabled.value = source?.enabled ?? true; enabled.value = source?.enabled ?? true;
host.value = String(source?.config.host || ""); const stored = Array.isArray(source?.config.tables) ? source.config.tables : [];
port.value = Number(source?.config.port || 22); chosen.value = stored.filter((item) => item?.tablename).map((item) => ({
protocol.value = String(source?.config.protocol || "sftp");
username.value = String(source?.config.username || "");
password.value = "";
path.value = String(source?.config.path || "");
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, code: Number(item.code) || 0,
category: String(item.category || ""), category: String(item.category || ""),
tablename: String(item.tablename), tablename: String(item.tablename),
name: String(item.name || item.tablename), name: String(item.name || item.tablename),
})); }));
timeMode.value = String(source?.config.timeMode || "prev_month"); timeMode.value = source?.config.timeMode || "prev_month";
timeCount.value = Number(source?.config.timeCount || 1); timeCount.value = Number(source?.config.timeCount || 1);
city.value = String(source?.config.city || ""); city.value = source?.config.city || "";
categoryCode.value = chosen.value[0]?.code || categories.value[0]?.code || null; const schedule = source?.config.schedule;
categoryTables.value = []; scheduleMode.value = schedule?.mode === "monthly" ? "monthly" : "weekly";
weekday.value = Number(schedule?.weekday || 1);
monthDay.value = Number(schedule?.monthDay || 1);
clock.value = schedule?.time || "08:00";
show.value = true; show.value = true;
if (kind.value === "nqi") { if (!groups.value.length) void loadCatalog();
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() { async function load() {
@@ -143,15 +109,56 @@ async function load() {
sources.value = result.sources; sources.value = result.sources;
} }
async function loadCatalog() {
catalogLoading.value = true;
try {
const result = await api<{ groups: Group[] }>("/api/admin/nqi/catalog?tree=true");
groups.value = result.groups;
} catch (error) {
toast.error(error instanceof Error ? error.message : "数据表没有获取到");
} finally {
catalogLoading.value = false;
}
}
function lookup(tablename: string) {
for (const group of groups.value) {
const table = group.tables.find((item) => item.tablename === tablename);
if (table) return { code: group.code, category: group.name, tablename, name: table.name };
}
return chosen.value.find((item) => item.tablename === tablename) || null;
}
function setPicked(names: string[]) {
chosen.value = names.map(lookup).filter((item): item is QueryTable => Boolean(item));
}
function removeTable(tablename: string) {
chosen.value = chosen.value.filter((item) => item.tablename !== tablename);
}
async function save() { async function save() {
if (kind.value === "nqi" && !chosen.value.length) { if (!name.value.trim()) {
toast.error("请填写名称");
return false;
}
if (!chosen.value.length) {
toast.error("请选择要采集的表"); toast.error("请选择要采集的表");
return false; return false;
} }
const config = kind.value === "nqi" if (!clock.value) {
? { tables: chosen.value, timeMode: timeMode.value, timeCount: timeCount.value, city: city.value } toast.error("请填写采集时间");
: { protocol: protocol.value, host: host.value, port: port.value, username: username.value, password: password.value, path: path.value }; return false;
const body = { name: name.value, kind: kind.value, periodDays: periodDays.value, enabled: enabled.value, config }; }
const schedule = scheduleMode.value === "weekly"
? { mode: "weekly", weekday: weekday.value, time: clock.value }
: { mode: "monthly", monthDay: monthDay.value, time: clock.value };
const body = {
name: name.value,
kind: "nqi",
enabled: enabled.value,
config: { tables: chosen.value, timeMode: timeMode.value, timeCount: timeCount.value, city: city.value, schedule },
};
try { try {
if (editing.value) { if (editing.value) {
await api(`/api/admin/sources/${editing.value.id}`, { method: "PUT", body: JSON.stringify(body) }); await api(`/api/admin/sources/${editing.value.id}`, { method: "PUT", body: JSON.stringify(body) });
@@ -204,8 +211,7 @@ onMounted(load);
<thead> <thead>
<tr> <tr>
<th>名称</th> <th>名称</th>
<th>来源</th> <th>周期</th>
<th>周期(天)</th>
<th>状态</th> <th>状态</th>
<th class="col-actions">操作</th> <th class="col-actions">操作</th>
</tr> </tr>
@@ -213,16 +219,29 @@ onMounted(load);
<tbody> <tbody>
<tr v-for="source in sources" :key="source.id"> <tr v-for="source in sources" :key="source.id">
<td>{{ source.name }}</td> <td>{{ source.name }}</td>
<td>{{ source.kind === "nqi" ? "NQI" : "FTP/SFTP" }}</td> <td>{{ scheduleText(source) }}</td>
<td>{{ source.periodDays }}</td>
<td> <td>
<span v-if="source.lastError" class="status-bad">{{ source.lastError }}</span> <span v-if="source.lastError" class="status-bad">{{ source.lastError }}</span>
<span v-else :class="source.enabled ? 'status-ok' : 'status-wait'">{{ source.enabled ? "启用" : "停用" }}</span> <span v-else :class="source.enabled ? 'status-ok' : 'status-wait'">{{ source.enabled ? "启用" : "停用" }}</span>
</td> </td>
<td class="col-actions"> <td class="col-actions">
<div class="row-actions"> <div class="row-actions">
<n-button size="small" quaternary @click="reset(source)">编辑</n-button> <n-tooltip>
<n-button size="small" quaternary @click="confirmRemove(source)">删除</n-button> <template #trigger>
<n-button size="small" quaternary circle aria-label="编辑" @click="reset(source)">
<template #icon><n-icon :component="CreateOutline" /></template>
</n-button>
</template>
编辑
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary circle aria-label="删除" @click="confirmRemove(source)">
<template #icon><n-icon :component="TrashOutline" /></template>
</n-button>
</template>
删除
</n-tooltip>
</div> </div>
</td> </td>
</tr> </tr>
@@ -234,56 +253,92 @@ onMounted(load);
</div> </div>
</div> </div>
</section> </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"> <n-modal v-model:show="show" class="app-dialog app-dialog-collect" preset="card" :show-icon="false" title="采集">
<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="collect-form">
<div class="form-row"><label>名称</label><n-input v-model:value="name" /></div> <div class="form-row"><label>名称</label><n-input v-model:value="name" /></div>
<p class="form-section">连接</p>
<template v-if="kind === 'ftp'">
<div class="form-row"><label>协议</label><n-select v-model:value="protocol" :options="[{ label: 'SFTP', value: 'sftp' }, { label: 'FTP', value: 'ftp' }]" /></div>
<div class="form-row"><label>主机</label><n-input v-model:value="host" /></div>
<div class="form-row"><label>端口</label><n-input-number v-model:value="port" :show-button="false" /></div>
<div class="form-row"><label>账号</label><n-input v-model:value="username" /></div>
<div class="form-row"><label>密码</label><n-input v-model:value="password" type="password" /></div>
<div class="form-row"><label>路径</label><n-input v-model:value="path" /></div>
</template>
<template v-else>
<div class="form-row"><label>查询分类</label><n-select :value="categoryCode" :options="categoryOptions" :loading="catalogLoading" @update:value="loadTables" /></div>
<div class="form-row"> <div class="form-row">
<label>数据表</label> <label>数据表</label>
<div> <div class="table-picker">
<n-select multiple filterable :value="pickedNames" :options="tableOptions" :loading="tablesLoading" @update:value="setPicked" /> <n-select
<n-button size="small" quaternary :disabled="!categoryTables.length" @click="selectCategory">分类全选</n-button> class="table-select"
multiple
filterable
placeholder="请选择表"
:value="picked"
:options="tableOptions"
:loading="catalogLoading"
:render-tag="renderTag"
@update:value="setPicked"
/>
<div class="table-picker-meta">
<span>已选 {{ chosen.length }}</span>
<n-button text type="primary" :disabled="!chosen.length" @click="details = true">选择详情</n-button>
</div> </div>
</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>
<div class="form-row"><label>数据时间</label><n-select v-model:value="timeMode" :options="timeOptions" /></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 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> <div class="form-row"><label>城市</label><n-input v-model:value="city" placeholder="不填则不按城市过滤" /></div>
</template> <div class="form-row">
<p class="form-section">周期</p> <label>采集周期</label>
<div class="form-row"><label>周期(天)</label><n-input-number v-model:value="periodDays" :min="1" :max="31" :show-button="false" /></div> <n-select v-model:value="scheduleMode" :options="[{ label: '每周', value: 'weekly' }, { label: '每月', value: 'monthly' }]" />
</div>
<div class="form-row">
<label>{{ scheduleMode === 'weekly' ? '星期' : '日期' }}</label>
<div class="schedule-time">
<n-select v-if="scheduleMode === 'weekly'" v-model:value="weekday" :options="weekdays" />
<n-select v-else v-model:value="monthDay" :options="monthDays" />
<n-time-picker v-model:formatted-value="clock" format="HH:mm" value-format="HH:mm" />
</div>
</div>
<div class="form-row"><label>启用</label><n-switch v-model:value="enabled" /></div> <div class="form-row"><label>启用</label><n-switch v-model:value="enabled" /></div>
</div>
<template #footer>
<div class="dialog-actions">
<n-button @click="show = false">取消</n-button>
<n-button type="primary" @click="save">保存</n-button>
</div>
</template>
</n-modal>
<n-modal v-model:show="details" class="app-dialog" preset="card" title="已选表格">
<div v-if="chosen.length" class="picked-list">
<div v-for="item in chosen" :key="item.tablename" class="picked-row">
<div>
<strong>{{ item.name }}</strong>
<span>{{ item.category }}</span>
</div>
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary circle aria-label="移除" @click="removeTable(item.tablename)">
<template #icon><n-icon :component="TrashOutline" /></template>
</n-button>
</template>
移除
</n-tooltip>
</div>
</div>
<p v-else class="admin-status">还没有选择表格</p>
</n-modal> </n-modal>
</Shell> </Shell>
</template> </template>
<style scoped> <style scoped>
.picked-tables { .collect-form { display: grid; gap: 12px; }
display: flex; .table-picker { display: grid; gap: 6px; min-width: 0; }
flex-wrap: wrap; .table-picker-meta { display: flex; align-items: center; justify-content: space-between; color: var(--muted); font-size: 12px; }
gap: 6px; .table-select :deep(.n-base-selection-tags) { flex-wrap: nowrap; overflow: hidden; }
} .table-select :deep(.n-base-selection-tag-wrapper:not(:first-child)) { display: none; }
.picked-tables button { .table-select :deep(.picker-inline) {
border: 1px solid var(--line); display: block;
border-radius: 999px; max-width: 280px;
background: transparent; overflow: hidden;
color: var(--ink); text-overflow: ellipsis;
padding: 2px 8px; white-space: nowrap;
cursor: pointer;
} }
.schedule-time { display: grid; grid-template-columns: minmax(0, 1fr) 128px; gap: 8px; }
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
.picked-list { display: grid; gap: 8px; }
.picked-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.picked-row strong { display: block; }
.picked-row span { color: var(--muted); font-size: 12px; }
</style> </style>
-4
View File
@@ -1,5 +1,4 @@
<script setup lang="ts"> <script setup lang="ts">
import { NButton } from "naive-ui";
import ThemeButton from "../../shell/ThemeButton.vue"; import ThemeButton from "../../shell/ThemeButton.vue";
</script> </script>
@@ -13,9 +12,6 @@ import ThemeButton from "../../shell/ThemeButton.vue";
</div> </div>
<h2 id="denied-title" class="gate-title">请从应用托管进入管理</h2> <h2 id="denied-title" class="gate-title">请从应用托管进入管理</h2>
<p class="gate-text">管理页面不在这里登录。请回到应用托管,使用「管理」进入。</p> <p class="gate-text">管理页面不在这里登录。请回到应用托管,使用「管理」进入。</p>
<div class="gate-actions">
<n-button type="primary" tag="a" href="/hosting">返回应用托管</n-button>
</div>
</section> </section>
</div> </div>
</template> </template>
+12 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue"; import { onMounted, onUnmounted, ref } from "vue";
import { NButton, NDatePicker, NInput, NModal, NSelect } from "naive-ui"; import { NButton, NDatePicker, NIcon, NInput, NModal, NSelect, NTooltip } from "naive-ui";
import { DownloadOutline } from "@vicons/ionicons5";
import Shell from "../../shell/Shell.vue"; import Shell from "../../shell/Shell.vue";
import { appUrl } from "../../shared/base"; import { appUrl } from "../../shared/base";
import { api, token } from "../../shared/http"; import { api, token } from "../../shared/http";
@@ -169,7 +170,16 @@ onUnmounted(stopPoll);
<div v-if="row.error" class="status-bad">{{ row.error }}</div> <div v-if="row.error" class="status-bad">{{ row.error }}</div>
</td> </td>
<td class="col-actions"> <td class="col-actions">
<n-button v-if="row.status === 'done'" type="primary" size="small" @click="download(row)">下载结果</n-button> <div v-if="row.status === 'done'" class="row-actions">
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary circle aria-label="下载结果" @click="download(row)">
<template #icon><n-icon :component="DownloadOutline" /></template>
</n-button>
</template>
下载结果
</n-tooltip>
</div>
</td> </td>
</tr> </tr>
</tbody> </tbody>
+3 -7
View File
@@ -3,7 +3,7 @@ import { computed, h, onMounted, onUnmounted, ref } from "vue";
import type { Component } from "vue"; import type { Component } from "vue";
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { NButton, NIcon, NLayout, NLayoutSider, NMenu } from "naive-ui"; import { NButton, NIcon, NLayout, NLayoutSider, NMenu } from "naive-ui";
import { AppsOutline, CloudDownloadOutline, HomeOutline, KeyOutline, ListOutline, LogOutOutline, PeopleOutline, PersonOutline, SettingsOutline } from "@vicons/ionicons5"; import { CloudDownloadOutline, HomeOutline, KeyOutline, ListOutline, LogOutOutline, PeopleOutline, PersonOutline, SettingsOutline } from "@vicons/ionicons5";
import { appUrl } from "../shared/base"; import { appUrl } from "../shared/base";
import { api, clearSession, sessionInfo, token } from "../shared/http"; import { api, clearSession, sessionInfo, token } from "../shared/http";
import { hosted } from "../shared/installState"; import { hosted } from "../shared/installState";
@@ -22,7 +22,7 @@ const items = computed(() => role === "admin"
? [ ? [
{ label: "首页", key: "/admin", icon: renderIcon(HomeOutline) }, { label: "首页", key: "/admin", icon: renderIcon(HomeOutline) },
...(!hosted || loginMode.value === "local" ? [{ label: "用户", key: "/admin/users", icon: renderIcon(PeopleOutline) }] : []), ...(!hosted || loginMode.value === "local" ? [{ label: "用户", key: "/admin/users", icon: renderIcon(PeopleOutline) }] : []),
{ label: "大数据账号池", key: "/admin/pool", icon: renderIcon(KeyOutline) }, { label: "号池", key: "/admin/pool", icon: renderIcon(KeyOutline) },
{ label: "采集", key: "/admin/sources", icon: renderIcon(CloudDownloadOutline) }, { label: "采集", key: "/admin/sources", icon: renderIcon(CloudDownloadOutline) },
{ label: "设置", key: "/admin/settings", icon: renderIcon(SettingsOutline) }, { label: "设置", key: "/admin/settings", icon: renderIcon(SettingsOutline) },
] ]
@@ -79,10 +79,6 @@ async function logout() {
:options="items" :options="items"
@update:value="(key) => router.push(String(key))" @update:value="(key) => router.push(String(key))"
/> />
<a v-if="hosted && role === 'admin'" class="sider-back" :class="{ compact: collapsed }" href="/hosting" :title="collapsed ? '返回应用托管' : undefined" @click="clearSession()">
<n-icon :size="collapsed ? 22 : 18"><AppsOutline /></n-icon>
<span v-if="!collapsed">返回应用托管</span>
</a>
<div class="sider-user" :class="{ compact: collapsed }"> <div class="sider-user" :class="{ compact: collapsed }">
<n-icon :size="18"><PersonOutline /></n-icon> <n-icon :size="18"><PersonOutline /></n-icon>
<div v-if="!collapsed" class="who"> <div v-if="!collapsed" class="who">
@@ -90,7 +86,7 @@ async function logout() {
<span>已登录</span> <span>已登录</span>
</div> </div>
<ThemeButton /> <ThemeButton />
<n-button class="logout-btn" quaternary circle size="small" aria-label="退出" @click="logout"> <n-button v-if="!(hosted && role === 'admin')" class="logout-btn" quaternary circle size="small" aria-label="退出" @click="logout">
<template #icon><n-icon><LogOutOutline /></n-icon></template> <template #icon><n-icon><LogOutOutline /></n-icon></template>
</n-button> </n-button>
</div> </div>
+13 -2
View File
@@ -226,17 +226,28 @@ button, input, select { font: inherit; }
.admin-table .col-actions { .admin-table .col-actions {
width: 1%; width: 1%;
white-space: nowrap; white-space: nowrap;
text-align: right; text-align: center;
} }
.admin-table .col-format, .admin-table .col-format,
.admin-table .col-role { width: 88px; } .admin-table .col-role { width: 88px; }
.admin-table .col-pick { width: 128px; } .admin-table .col-pick { width: 128px; }
.row-actions { .row-actions {
display: flex; display: flex;
justify-content: flex-end; justify-content: center;
align-items: center; align-items: center;
gap: 4px; gap: 4px;
} }
.page-head-actions {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.page-head-actions .n-input { width: min(280px, 42vw); }
.n-card.app-dialog-collect,
.app-dialog-collect.app-dialog {
width: min(640px, calc(100vw - 32px));
}
/* forms: label left, control right */ /* forms: label left, control right */
.form-row { .form-row {