From 7ed299bbf6847254495fa8073a71e2ccf4de19c6 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 29 Oct 2026 18:11:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E5=B7=B2=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4=E7=9A=84=E7=99=BB=E5=BD=95=E3=80=81=E9=87=87=E9=9B=86?= =?UTF-8?q?=E5=92=8C=E4=BB=BB=E5=8A=A1=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 5 + PRODUCT.md | 2 +- README.md | 12 +- backend/alembic.ini | 26 + backend/alembic/env.py | 37 + backend/alembic/versions/0001_initial.py | 87 ++ backend/app/api/deps.py | 29 + backend/app/api/http.py | 455 +++++++ backend/app/bootstrap.py | 37 + backend/app/collect/io.py | 148 +++ backend/app/collect/remote.py | 51 + backend/app/config.py | 49 + backend/app/db.py | 56 + backend/app/main.py | 45 + backend/app/models.py | 86 ++ backend/app/nqi/client.py | 460 ++++++++ backend/app/nqi/constants.py | 23 + backend/app/nqi/flows.py | 40 + backend/app/nqi/sign.py | 43 + backend/app/runtime.py | 49 + backend/app/security.py | 59 + backend/app/tasks/queue.py | 32 + backend/app/tasks/runner.py | 252 ++++ backend/requirements.txt | 13 + backend/tests/test_core.py | 91 ++ backend/worker/main.py | 25 + web/index.html | 12 + web/package-lock.json | 1377 ++++++++++++++++++++++ web/package.json | 22 + web/src/App.vue | 45 + web/src/features/admin/PoolView.vue | 59 + web/src/features/admin/SettingsView.vue | 52 + web/src/features/admin/SourcesView.vue | 137 +++ web/src/features/admin/UsersView.vue | 71 ++ web/src/features/auth/LoginView.vue | 180 +++ web/src/features/user/TasksView.vue | 91 ++ web/src/main.ts | 35 + web/src/shared/http.ts | 58 + web/src/shared/theme.ts | 24 + web/src/shell/Shell.vue | 57 + web/src/styles.css | 88 ++ web/src/vite-env.d.ts | 1 + web/tsconfig.json | 15 + web/vite.config.ts | 12 + 44 files changed, 4546 insertions(+), 2 deletions(-) create mode 100644 backend/alembic.ini create mode 100644 backend/alembic/env.py create mode 100644 backend/alembic/versions/0001_initial.py create mode 100644 backend/app/api/deps.py create mode 100644 backend/app/api/http.py create mode 100644 backend/app/bootstrap.py create mode 100644 backend/app/collect/io.py create mode 100644 backend/app/collect/remote.py create mode 100644 backend/app/config.py create mode 100644 backend/app/db.py create mode 100644 backend/app/main.py create mode 100644 backend/app/models.py create mode 100644 backend/app/nqi/client.py create mode 100644 backend/app/nqi/constants.py create mode 100644 backend/app/nqi/flows.py create mode 100644 backend/app/nqi/sign.py create mode 100644 backend/app/runtime.py create mode 100644 backend/app/security.py create mode 100644 backend/app/tasks/queue.py create mode 100644 backend/app/tasks/runner.py create mode 100644 backend/requirements.txt create mode 100644 backend/tests/test_core.py create mode 100644 backend/worker/main.py create mode 100644 web/index.html create mode 100644 web/package-lock.json create mode 100644 web/package.json create mode 100644 web/src/App.vue create mode 100644 web/src/features/admin/PoolView.vue create mode 100644 web/src/features/admin/SettingsView.vue create mode 100644 web/src/features/admin/SourcesView.vue create mode 100644 web/src/features/admin/UsersView.vue create mode 100644 web/src/features/auth/LoginView.vue create mode 100644 web/src/features/user/TasksView.vue create mode 100644 web/src/main.ts create mode 100644 web/src/shared/http.ts create mode 100644 web/src/shared/theme.ts create mode 100644 web/src/shell/Shell.vue create mode 100644 web/src/styles.css create mode 100644 web/src/vite-env.d.ts create mode 100644 web/tsconfig.json create mode 100644 web/vite.config.ts diff --git a/.gitignore b/.gitignore index da011a2..30cfa06 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,10 @@ __pycache__/ *.pyc .venv/ +data/ +web/node_modules/ +web/dist/ node_modules/ dist/ +.env + diff --git a/PRODUCT.md b/PRODUCT.md index f85f7fc..fb876d3 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -38,7 +38,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和 ## Brand Commitments -产品名是 DecomEval。界面风格是石墨工作台:默认深色底板、细缝、蓝色主按钮。选中导航只有一条浅色左边线,可切日间。不使用运营商标志。 +产品名是 DecomEval。界面风格是石墨工作台:深色底板、细缝、蓝色主按钮。选中导航只有一条浅色左边线。日夜间默认跟随系统,也可以手动选择深色、浅色或跟随系统。不使用运营商标志。 ## Evidence on Hand diff --git a/README.md b/README.md index b9f9da4..d8749d1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,13 @@ # DecomEval -占位 +拆站评估。数据先采集入库,用户提交任务后从库中导出 xlsx、xls 或 csv。 + +```text +cd backend +.venv\Scripts\python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 +.venv\Scripts\python -m worker.main +cd ..\web +npm run dev +``` + +PostgreSQL 使用 `DECOM_DATABASE_URL=postgresql+psycopg://用户:密码@主机:5432/decom`。未设置时使用本机 SQLite。首次启动用 `DECOM_ADMIN_USERNAME` 和 `DECOM_ADMIN_PASSWORD` 创建管理员。生产环境同时运行接口和 `worker.main`,并设置 `DECOM_INLINE_WORKER=0`。 diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 0000000..989c9f7 --- /dev/null +++ b/backend/alembic.ini @@ -0,0 +1,26 @@ +[alembic] +script_location = alembic +sqlalchemy.url = sqlite:///./data/decom.db + +[loggers] +keys = root + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s diff --git a/backend/alembic/env.py b/backend/alembic/env.py new file mode 100644 index 0000000..1a356e4 --- /dev/null +++ b/backend/alembic/env.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +from app.config import database_url +from app.models import Base + +config = context.config +if config.config_file_name is not None: + fileConfig(config.config_file_name) +config.set_main_option("sqlalchemy.url", database_url()) +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + context.configure(url=database_url(), target_metadata=target_metadata, literal_binds=True) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + configuration = config.get_section(config.config_ini_section) or {} + configuration["sqlalchemy.url"] = database_url() + connectable = engine_from_config(configuration, prefix="sqlalchemy.", poolclass=pool.NullPool) + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/alembic/versions/0001_initial.py b/backend/alembic/versions/0001_initial.py new file mode 100644 index 0000000..6badfa4 --- /dev/null +++ b/backend/alembic/versions/0001_initial.py @@ -0,0 +1,87 @@ +"""初始表结构。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0001_initial" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "app_setting", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("login_mode", sa.String(16), nullable=False), + sa.Column("credential_refresh_seconds", sa.Integer(), nullable=False), + ) + op.create_table( + "app_user", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("username", sa.String(64), nullable=False), + sa.Column("password_hash", sa.String(200), nullable=False), + sa.Column("role", sa.String(16), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + ) + op.create_index("ix_app_user_username", "app_user", ["username"], unique=True) + op.create_table( + "nqi_account", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("login_id", sa.String(64), nullable=False), + sa.Column("user_name", sa.String(128), nullable=False), + sa.Column("city_name", sa.String(64), nullable=False), + sa.Column("org_name", sa.String(128), nullable=False), + sa.Column("cookies", sa.JSON(), nullable=False), + sa.Column("role", sa.String(16), nullable=False), + sa.Column("session_open", sa.Boolean(), nullable=False), + sa.Column("credential_valid", sa.Boolean(), nullable=False), + sa.Column("saved_at", sa.DateTime(timezone=True), nullable=False), + ) + op.create_index("ix_nqi_account_login_id", "nqi_account", ["login_id"], unique=True) + op.create_table( + "CellData", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("cell_key", sa.String(128), nullable=False), + sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("source", sa.String(16), nullable=False), + sa.Column("metrics", sa.JSON(), nullable=False), + sa.UniqueConstraint("cell_key", "observed_at", "source", name="uq_cell_time_source"), + ) + op.create_index("ix_celldata_cell_key", "CellData", ["cell_key"]) + op.create_index("ix_celldata_observed_at", "CellData", ["observed_at"]) + op.create_table( + "collection_source", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("name", sa.String(128), nullable=False), + sa.Column("kind", sa.String(16), nullable=False), + sa.Column("period_days", sa.Integer(), nullable=False), + sa.Column("config", sa.JSON(), nullable=False), + sa.Column("enabled", sa.Boolean(), nullable=False), + sa.Column("next_run_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("last_error", sa.Text(), nullable=False), + ) + op.create_table( + "export_task", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("owner_kind", sa.String(16), nullable=False), + sa.Column("owner_id", sa.String(64), nullable=False), + sa.Column("status", sa.String(16), nullable=False), + sa.Column("file_format", sa.String(8), nullable=False), + sa.Column("params", sa.JSON(), nullable=False), + sa.Column("result_name", sa.String(255), nullable=False), + sa.Column("error", sa.Text(), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + ) + op.create_index("ix_export_task_owner_id", "export_task", ["owner_id"]) + op.create_index("ix_export_task_status", "export_task", ["status"]) + + +def downgrade() -> None: + op.drop_table("export_task") + op.drop_table("collection_source") + op.drop_table("CellData") + op.drop_table("nqi_account") + op.drop_table("app_user") + op.drop_table("app_setting") diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py new file mode 100644 index 0000000..456be0c --- /dev/null +++ b/backend/app/api/deps.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from dataclasses import dataclass + +from fastapi import Header, HTTPException + +from app.security import read_token + + +@dataclass +class Actor: + kind: str + id: str + role: str + name: str + + +def current_actor(authorization: str | None = Header(default=None)) -> Actor: + if not authorization or not authorization.lower().startswith("bearer "): + raise HTTPException(status_code=401, detail="请先登录") + body = read_token(authorization.split(" ", 1)[1].strip()) + if body is None: + raise HTTPException(status_code=401, detail="登录已失效") + return Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or "")) + + +def require_admin(actor: Actor) -> None: + if actor.role != "admin": + raise HTTPException(status_code=403, detail="需要管理员") diff --git a/backend/app/api/http.py b/backend/app/api/http.py new file mode 100644 index 0000000..57a8b9b --- /dev/null +++ b/backend/app/api/http.py @@ -0,0 +1,455 @@ +from __future__ import annotations + +import base64 + +from fastapi import APIRouter, Depends, HTTPException +from fastapi.responses import Response +from sqlalchemy import select +from sqlalchemy.orm import Session + +from app.api.deps import Actor, current_actor, require_admin +from app.config import RESULT_DIR +from app.db import get_session, session_scope +from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow +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 +from app.tasks.runner import check_period, check_refresh, enqueue_export + +router = APIRouter(prefix="/api") + + +def _bad(message: str, status: int = 400) -> HTTPException: + return HTTPException(status_code=status, detail=message) + + +def _setting(session: Session) -> AppSetting: + setting = session.get(AppSetting, 1) + if setting is None: + setting = AppSetting(id=1, login_mode="local", credential_refresh_seconds=300) + session.add(setting) + session.flush() + return setting + + +def _token_for(kind: str, owner_id: str, role: str, name: str) -> dict: + return { + "status": "ok", + "token": issue_token({"kind": kind, "id": owner_id, "role": role, "name": name}), + "user": {"kind": kind, "id": owner_id, "role": role, "name": name}, + } + + +def _captcha_body(session_id: str, challenge) -> dict: + encoded = base64.b64encode(challenge.captcha_png).decode("ascii") + return { + "status": "captcha", + "sessionId": session_id, + "captcha": f"data:{challenge.captcha_type};base64,{encoded}", + } + + +def _public_source(source: CollectionSource) -> dict: + config = dict(source.config or {}) + if "password" in config: + config = {**config, "password": "", "passwordSet": bool(config.get("password"))} + return { + "id": source.id, + "name": source.name, + "kind": source.kind, + "periodDays": source.period_days, + "config": config, + "enabled": source.enabled, + "lastError": source.last_error, + } + + +@router.get("/auth/mode") +def auth_mode(session: Session = Depends(get_session)) -> dict: + return {"mode": _setting(session).login_mode} + + +@router.post("/auth/local") +def local_login(body: dict, session: Session = Depends(get_session)) -> dict: + if _setting(session).login_mode != "local": + raise _bad("当前使用大数据平台账号登录") + username = str(body.get("username") or "").strip() + password = str(body.get("password") or "") + user = session.scalar(select(User).where(User.username == username)) + if user is None or not verify_password(password, user.password_hash): + raise _bad("账号或密码不正确") + return _token_for("local", str(user.id), user.role, user.username) + + +@router.post("/auth/nqi/start") +async def nqi_start(body: dict) -> dict: + await purge() + username = str(body.get("username") or "").strip() + purpose = "pool" if body.get("purpose") == "pool" else "login" + if not username: + raise _bad("请输入账号") + with session_scope() as session: + if _setting(session).login_mode != "nqi": + raise _bad("当前使用自有账号登录") + account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username)) + resume_cookies = list(account.cookies or []) if account is not None and account.session_open and account.credential_valid else [] + resume_role = account.role if account is not None else "user" + resume_name = (account.user_name or account.login_id) if account is not None else username + if purpose == "login" and resume_cookies: + resumed = await _resume(resume_cookies) + if resumed is not None: + user, cookies = resumed + with session_scope() as session: + account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username)) + if account is not None: + account.cookies = cookies + account.user_name = user.get("userName") or account.user_name + account.credential_valid = True + account.saved_at = utcnow() + resume_role = account.role + resume_name = account.user_name or account.login_id + return _token_for("nqi", username, resume_role, resume_name) + client = NqiClient() + try: + challenge = await client.open_login() + except NqiError as exc: + await client.aclose() + raise _bad(str(exc)) from exc + session_id = remember(client, challenge, purpose) + return _captcha_body(session_id, challenge) + + +@router.post("/auth/nqi/captcha") +async def nqi_captcha(body: dict) -> dict: + pair = take(str(body.get("sessionId") or "")) + if pair is None: + raise _bad("验证码已失效,请重新打开登录") + client, challenge, _purpose = pair + try: + await client.refresh_captcha(challenge) + except NqiError as exc: + raise _bad(str(exc)) from exc + return _captcha_body(str(body.get("sessionId")), challenge) + + +@router.post("/auth/nqi/sms") +async def nqi_sms(body: dict) -> dict: + pair = take(str(body.get("sessionId") or "")) + if pair is None: + raise _bad("登录已过期,请重新打开登录") + client, challenge, _purpose = pair + username = str(body.get("username") or "").strip() + password = str(body.get("password") or "") + captcha = str(body.get("captcha") or "").strip() + if not username or not password or not captcha: + raise _bad("请填写账号、密码和验证码") + try: + if not challenge.config_ready: + await client.prepare_login(challenge, username, password, captcha) + message = await client.send_sms(challenge) + except NqiError as exc: + raise _bad(str(exc)) from exc + return {"ok": True, "message": message} + + +@router.post("/auth/nqi/finish") +async def nqi_finish(body: dict) -> dict: + session_id = str(body.get("sessionId") or "") + pair = take(session_id) + if pair is None: + raise _bad("验证码已失效,请重新打开登录") + client, challenge, purpose = pair + username = str(body.get("username") or "").strip() + password = str(body.get("password") or "") + captcha = str(body.get("captcha") or "").strip() + sms_code = str(body.get("smsCode") or "").strip() + if not username or not password or not captcha: + raise _bad("请填写账号、密码和验证码") + try: + if not challenge.config_ready: + code = await client.prepare_login(challenge, username, password, captcha) + if code == "1" and not sms_code: + return {"status": "sms_required"} + user = await client.submit_login(challenge, sms_code) + except NqiError as exc: + raise _bad(str(exc)) from exc + challenge.password = "" + cookies = client.export_cookies() + await client.aclose() + drop(session_id) + with session_scope() as session: + if _setting(session).login_mode != "nqi": + raise _bad("当前使用自有账号登录") + account = _save_pool(session, user, cookies) + login_id = account.login_id + role = account.role + name = account.user_name or account.login_id + if purpose == "pool": + return {"status": "ok"} + return _token_for("nqi", login_id, role, name) + + +@router.post("/auth/logout") +def logout(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + if actor.kind == "nqi": + account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == actor.id)) + if account is not None: + account.session_open = False + return {"ok": True} + + +@router.get("/me") +def me(actor: Actor = Depends(current_actor)) -> dict: + return {"user": {"kind": actor.kind, "id": actor.id, "role": actor.role, "name": actor.name}} + + +@router.get("/tasks") +def list_tasks(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + if actor.role == "admin": + raise _bad("管理员不在这里提交任务", 403) + rows = session.scalars( + select(ExportTask) + .where(ExportTask.owner_kind == actor.kind, ExportTask.owner_id == actor.id) + .order_by(ExportTask.id.desc()) + ).all() + return {"tasks": [_public_task(row) for row in rows]} + + +@router.post("/tasks") +def create_task(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + if actor.role == "admin": + raise _bad("管理员不在这里提交任务", 403) + file_format = str(body.get("format") or "") + if file_format not in {"xlsx", "xls", "csv"}: + raise _bad("结果文件只能是 xlsx、xls 或 csv") + task = ExportTask( + owner_kind=actor.kind, + owner_id=actor.id, + status="queued", + file_format=file_format, + params={ + "cellKey": str(body.get("cellKey") or "").strip(), + "start": str(body.get("start") or "").strip(), + "end": str(body.get("end") or "").strip(), + }, + ) + session.add(task) + session.flush() + task_id = task.id + session.commit() + enqueue_export(task_id) + return {"task": _public_task(task)} + + +@router.get("/tasks/{task_id}/file") +def download_task(task_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> Response: + task = session.get(ExportTask, task_id) + if task is None or task.owner_kind != actor.kind or task.owner_id != actor.id or task.status != "done": + raise _bad("结果还不能下载", 404) + path = RESULT_DIR / task.result_name + if not path.is_file(): + raise _bad("结果还不能下载", 404) + return Response(content=path.read_bytes(), media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{task.result_name}"'}) + + +@router.get("/admin/settings") +def admin_settings(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + setting = _setting(session) + return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds} + + +@router.put("/admin/settings") +def update_settings(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + setting = _setting(session) + mode = str(body.get("loginMode") or setting.login_mode) + if mode not in {"local", "nqi"}: + raise _bad("登录方式不正确") + if mode == "local" and session.scalar(select(User).where(User.role == "admin")) is None: + raise _bad("还没有自有账号管理员,不能切换") + if "credentialRefreshSeconds" in body: + try: + setting.credential_refresh_seconds = check_refresh(int(body.get("credentialRefreshSeconds"))) + except (TypeError, ValueError) as exc: + raise _bad(str(exc)) from exc + setting.login_mode = mode + return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds} + + +@router.get("/admin/users") +def list_users(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + rows = session.scalars(select(User).order_by(User.id)).all() + return {"users": [{"id": row.id, "username": row.username, "role": row.role} for row in rows]} + + +@router.post("/admin/users") +def create_user(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + username = str(body.get("username") or "").strip() + password = str(body.get("password") or "") + role = "admin" if body.get("role") == "admin" else "user" + if not username or not password: + raise _bad("请填写账号和密码") + if session.scalar(select(User).where(User.username == username)) is not None: + raise _bad("账号已存在") + session.add(User(username=username, password_hash=hash_password(password), role=role)) + return {"ok": True} + + +@router.delete("/admin/users/{user_id}") +def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + user = session.get(User, user_id) + if user is None: + raise _bad("账号不存在", 404) + if user.role == "admin" and actor.kind == "local" and actor.id == str(user.id): + raise _bad("不能删除当前管理员") + session.delete(user) + return {"ok": True} + + +@router.get("/admin/pool") +def list_pool(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all() + return { + "accounts": [ + { + "id": row.id, + "loginId": row.login_id, + "userName": row.user_name, + "cityName": row.city_name, + "role": row.role, + "sessionOpen": row.session_open, + "credentialValid": row.credential_valid, + } + for row in rows + ] + } + + +@router.delete("/admin/pool/{account_id}") +def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + account = session.get(NqiAccount, account_id) + if account is None: + raise _bad("账号不存在", 404) + session.delete(account) + return {"ok": True} + + +@router.put("/admin/pool/{account_id}/role") +def pool_role(account_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + account = session.get(NqiAccount, account_id) + if account is None: + raise _bad("账号不存在", 404) + account.role = "admin" if body.get("role") == "admin" else "user" + return {"ok": True} + + +@router.get("/admin/sources") +def list_sources(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + rows = session.scalars(select(CollectionSource).order_by(CollectionSource.id)).all() + return {"sources": [_public_source(row) for row in rows]} + + +@router.post("/admin/sources") +def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + source = CollectionSource(name="采集", kind="ftp", period_days=1, config={}, enabled=True, next_run_at=utcnow()) + _apply_source(source, body) + session.add(source) + session.flush() + return {"source": _public_source(source)} + + +@router.put("/admin/sources/{source_id}") +def update_source(source_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + source = session.get(CollectionSource, source_id) + if source is None: + raise _bad("采集不存在", 404) + _apply_source(source, body) + return {"source": _public_source(source)} + + +@router.delete("/admin/sources/{source_id}") +def delete_source(source_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict: + require_admin(actor) + source = session.get(CollectionSource, source_id) + if source is None: + raise _bad("采集不存在", 404) + session.delete(source) + return {"ok": True} + + +def _apply_source(source: CollectionSource, body: dict) -> None: + if "name" in body: + source.name = str(body.get("name") or "").strip() or source.name + if "kind" in body: + kind = str(body.get("kind") or "") + if kind not in {"ftp", "nqi"}: + raise _bad("采集来源不正确") + 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: + source.enabled = bool(body.get("enabled")) + if "config" in body and isinstance(body.get("config"), dict): + incoming = dict(body["config"]) + current = dict(source.config or {}) + if not incoming.get("password"): + incoming["password"] = current.get("password") or "" + source.config = incoming + + +def _public_task(task: ExportTask) -> dict: + return { + "id": task.id, + "status": task.status, + "format": task.file_format, + "cellKey": (task.params or {}).get("cellKey") or "", + "error": task.error, + "createdAt": task.created_at.isoformat() if task.created_at else "", + } + + +def _save_pool(session: Session, user: dict, cookies: list) -> NqiAccount: + login_id = str(user.get("loginId") or "").strip() + if not login_id: + raise _bad("平台没有返回账号") + account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == login_id)) + has_admin = session.scalar(select(NqiAccount.id).where(NqiAccount.role == "admin")) is not None + if account is None: + account = NqiAccount(login_id=login_id, role="user" if has_admin else "admin") + session.add(account) + account.user_name = user.get("userName") or "" + account.city_name = user.get("cityName") or "" + account.org_name = user.get("orgName") or "" + account.cookies = cookies + account.session_open = True + account.credential_valid = True + account.saved_at = utcnow() + session.flush() + return account + + +async def _resume(cookies: list): + client = NqiClient() + try: + client.import_cookies(cookies) + user = await client.current_user() + return user, client.export_cookies() + except NqiAuthError: + return None + except NqiError: + return None + finally: + await client.aclose() diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py new file mode 100644 index 0000000..ff62add --- /dev/null +++ b/backend/app/bootstrap.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import logging + +from pathlib import Path + +from alembic import command +from alembic.config import Config +from sqlalchemy import select + +from app.config import BACKEND_ROOT, admin_password, admin_username +from app.db import session_scope +from app.models import AppSetting, User +from app.security import hash_password + +logger = logging.getLogger("decom") + + +def init_db() -> None: + from app.config import DATA_DIR + + DATA_DIR.mkdir(parents=True, exist_ok=True) + config = Config(str(Path(BACKEND_ROOT) / "alembic.ini")) + config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic")) + command.upgrade(config, "head") + with session_scope() as session: + if session.get(AppSetting, 1) is None: + session.add(AppSetting(id=1, login_mode="local", credential_refresh_seconds=300)) + if admin_username() and admin_password() and session.scalar(select(User).where(User.role == "admin")) is None: + session.add( + User( + username=admin_username(), + password_hash=hash_password(admin_password()), + role="admin", + ) + ) + logger.info("已创建管理员 %s", admin_username()) diff --git a/backend/app/collect/io.py b/backend/app/collect/io.py new file mode 100644 index 0000000..db98d18 --- /dev/null +++ b/backend/app/collect/io.py @@ -0,0 +1,148 @@ +"""把表格读成小区多期记录,并按选择的格式写出。""" + +from __future__ import annotations + +import csv +import io +from datetime import datetime, timezone + +from openpyxl import Workbook, load_workbook +import xlwt + +CELL_HEADERS = ("小区", "cell_key", "cell") +TIME_HEADERS = ("时间", "observed_at", "time") + + +def decode_text(content: bytes) -> str: + for encoding in ("utf-8-sig", "gbk"): + try: + return content.decode(encoding) + except UnicodeDecodeError: + continue + return content.decode("utf-8", errors="replace") + + +def _parse_time(value: str) -> datetime: + text = value.strip() + if not text: + raise ValueError("缺少时间") + normalized = text.replace("/", "-").replace("T", " ") + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): + try: + parsed = datetime.strptime(normalized, fmt) + return parsed.replace(tzinfo=timezone.utc) + except ValueError: + continue + raise ValueError("时间格式无法识别") + + +def rows_from_table(headers: list[str], records: list[list[str]]) -> list[dict]: + cell_index = next((index for index, name in enumerate(headers) if name.strip() in CELL_HEADERS), None) + time_index = next((index for index, name in enumerate(headers) if name.strip() in TIME_HEADERS), None) + if cell_index is None or time_index is None: + raise ValueError("表格需要包含小区和时间") + parsed: list[dict] = [] + for record in records: + if cell_index >= len(record) or not str(record[cell_index]).strip(): + continue + metrics = {} + for index, name in enumerate(headers): + if index in {cell_index, time_index} or not name.strip(): + continue + metrics[name.strip()] = "" if index >= len(record) else str(record[index]).strip() + parsed.append( + { + "cell_key": str(record[cell_index]).strip(), + "observed_at": _parse_time(str(record[time_index]) if time_index < len(record) else ""), + "metrics": metrics, + } + ) + return parsed + + +def parse_csv(content: bytes) -> list[dict]: + reader = csv.reader(io.StringIO(decode_text(content))) + rows = list(reader) + if not rows: + return [] + return rows_from_table(rows[0], rows[1:]) + + +def parse_xlsx(content: bytes) -> list[dict]: + book = load_workbook(io.BytesIO(content), read_only=True, data_only=True) + sheet = book.active + rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)] + book.close() + if not rows: + return [] + return rows_from_table(rows[0], rows[1:]) + + +def parse_upload(name: str, content: bytes) -> list[dict]: + lowered = name.lower() + if lowered.endswith(".xlsx"): + return parse_xlsx(content) + return parse_csv(content) + + +def _flat_rows(rows: list[dict]) -> tuple[list[str], list[list[str]]]: + metric_names: list[str] = [] + for row in rows: + for key in row["metrics"]: + if key not in metric_names: + metric_names.append(key) + headers = ["小区", "时间", *metric_names] + body = [] + for row in rows: + moment = row["observed_at"] + if isinstance(moment, datetime): + text = moment.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + else: + text = str(moment) + body.append([row["cell_key"], text, *[str(row["metrics"].get(name, "")) for name in metric_names]]) + return headers, body + + +def write_csv(rows: list[dict]) -> bytes: + headers, body = _flat_rows(rows) + buffer = io.StringIO() + writer = csv.writer(buffer) + writer.writerow(headers) + writer.writerows(body) + return buffer.getvalue().encode("utf-8-sig") + + +def write_xlsx(rows: list[dict]) -> bytes: + headers, body = _flat_rows(rows) + book = Workbook() + sheet = book.active + sheet.append(headers) + for line in body: + sheet.append(line) + buffer = io.BytesIO() + book.save(buffer) + return buffer.getvalue() + + +def write_xls(rows: list[dict]) -> bytes: + headers, body = _flat_rows(rows) + book = xlwt.Workbook() + sheet = book.add_sheet("结果") + for column, name in enumerate(headers): + sheet.write(0, column, name) + for row_index, line in enumerate(body, start=1): + for column, value in enumerate(line): + sheet.write(row_index, column, value) + buffer = io.BytesIO() + book.save(buffer) + return buffer.getvalue() + + +def write_table(file_format: str, rows: list[dict]) -> tuple[str, bytes]: + if file_format == "xlsx": + return "result.xlsx", write_xlsx(rows) + if file_format == "xls": + return "result.xls", write_xls(rows) + if file_format == "csv": + return "result.csv", write_csv(rows) + raise ValueError("结果文件只能是 xlsx、xls 或 csv") diff --git a/backend/app/collect/remote.py b/backend/app/collect/remote.py new file mode 100644 index 0000000..8057704 --- /dev/null +++ b/backend/app/collect/remote.py @@ -0,0 +1,51 @@ +"""从 FTP/SFTP 或已登录的大数据平台取回表格。""" + +from __future__ import annotations + +import io +from ftplib import FTP +from urllib.parse import urlparse + +import paramiko + +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]: + address = str(config.get("url") or "").strip() + if not address: + raise ValueError("未配置 NQI 采集地址") + parsed = urlparse(address) + if parsed.scheme not in {"http", "https"}: + raise ValueError("NQI 采集地址需要是 http 或 https") + return await client.fetch_bytes(address) diff --git a/backend/app/config.py b/backend/app/config.py new file mode 100644 index 0000000..fa13a2a --- /dev/null +++ b/backend/app/config.py @@ -0,0 +1,49 @@ +"""运行配置。秘密只从环境变量或 data 目录读取,不写进代码。""" + +from __future__ import annotations + +import os +import secrets +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] +DATA_DIR = BACKEND_ROOT / "data" +RESULT_DIR = DATA_DIR / "results" + + +def database_url() -> str: + return os.environ.get("DECOM_DATABASE_URL", f"sqlite+pysqlite:///{(DATA_DIR / 'decom.db').as_posix()}") + + +def postgres_conninfo() -> str | None: + url = database_url() + if url.startswith("postgresql+psycopg://"): + return "postgresql://" + url.removeprefix("postgresql+psycopg://") + if url.startswith("postgresql://"): + return url + return None + + +def inline_worker() -> bool: + return os.environ.get("DECOM_INLINE_WORKER", "1") == "1" + + +def jwt_secret() -> str: + configured = os.environ.get("DECOM_JWT_SECRET", "").strip() + if configured: + return configured + path = DATA_DIR / "jwt.secret" + if path.is_file(): + return path.read_text(encoding="utf-8").strip() + path.parent.mkdir(parents=True, exist_ok=True) + value = secrets.token_hex(32) + path.write_text(value, encoding="utf-8") + return value + + +def admin_username() -> str: + return os.environ.get("DECOM_ADMIN_USERNAME", "").strip() + + +def admin_password() -> str: + return os.environ.get("DECOM_ADMIN_PASSWORD", "") diff --git a/backend/app/db.py b/backend/app/db.py new file mode 100644 index 0000000..2aba6a8 --- /dev/null +++ b/backend/app/db.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager + +from sqlalchemy import create_engine +from sqlalchemy.orm import Session, sessionmaker + +from app.config import database_url + +_engine = None +SessionLocal = sessionmaker(expire_on_commit=False) + + +def engine(): + global _engine + if _engine is None: + url = database_url() + connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {} + _engine = create_engine(url, connect_args=connect_args) + SessionLocal.configure(bind=_engine) + return _engine + + +def reset_engine() -> None: + global _engine + if _engine is not None: + _engine.dispose() + _engine = None + + +@contextmanager +def session_scope() -> Iterator[Session]: + engine() + session = SessionLocal() + try: + yield session + session.commit() + except Exception: + session.rollback() + raise + finally: + session.close() + + +def get_session() -> Iterator[Session]: + engine() + session = SessionLocal() + try: + yield session + session.commit() + except Exception: + session.rollback() + raise + finally: + session.close() diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..1a7e240 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import logging +from pathlib import Path + +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from fastapi.responses import FileResponse +from fastapi.staticfiles import StaticFiles + +from app.api.http import router +from app.bootstrap import init_db +from app.runtime import start_background + +logger = logging.getLogger("decom") +WEB_DIST = Path(__file__).resolve().parents[2] / "web" / "dist" + + +@asynccontextmanager +async def lifespan(_application: FastAPI): + init_db() + start_background() + yield + + +def create_app() -> FastAPI: + logging.basicConfig(level=logging.INFO) + application = FastAPI(title="DecomEval", lifespan=lifespan) + application.include_router(router) + + if (WEB_DIST / "index.html").is_file(): + application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets") + + @application.get("/{path:path}") + def pages(path: str) -> FileResponse: + target = WEB_DIST / path + if path and target.is_file(): + return FileResponse(target) + return FileResponse(WEB_DIST / "index.html") + + return application + + +app = create_app() diff --git a/backend/app/models.py b/backend/app/models.py new file mode 100644 index 0000000..3479339 --- /dev/null +++ b/backend/app/models.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text, UniqueConstraint +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + + +def utcnow() -> datetime: + return datetime.now(timezone.utc) + + +class Base(DeclarativeBase): + pass + + +class AppSetting(Base): + __tablename__ = "app_setting" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + login_mode: Mapped[str] = mapped_column(String(16), default="local") + credential_refresh_seconds: Mapped[int] = mapped_column(Integer, default=300) + + +class User(Base): + __tablename__ = "app_user" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + username: Mapped[str] = mapped_column(String(64), unique=True, index=True) + password_hash: Mapped[str] = mapped_column(String(200)) + role: Mapped[str] = mapped_column(String(16), default="user") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class NqiAccount(Base): + __tablename__ = "nqi_account" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + login_id: Mapped[str] = mapped_column(String(64), unique=True, index=True) + user_name: Mapped[str] = mapped_column(String(128), default="") + city_name: Mapped[str] = mapped_column(String(64), default="") + org_name: Mapped[str] = mapped_column(String(128), default="") + cookies: Mapped[list] = mapped_column(JSON, default=list) + role: Mapped[str] = mapped_column(String(16), default="user") + session_open: Mapped[bool] = mapped_column(Boolean, default=True) + credential_valid: Mapped[bool] = mapped_column(Boolean, default=True) + saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class CellData(Base): + __tablename__ = "CellData" + __table_args__ = (UniqueConstraint("cell_key", "observed_at", "source", name="uq_cell_time_source"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + cell_key: Mapped[str] = mapped_column(String(128), index=True) + observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True) + source: Mapped[str] = mapped_column(String(16)) + metrics: Mapped[dict] = mapped_column(JSON, default=dict) + + +class CollectionSource(Base): + __tablename__ = "collection_source" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(128)) + kind: Mapped[str] = mapped_column(String(16)) + period_days: Mapped[int] = mapped_column(Integer, default=1) + config: Mapped[dict] = mapped_column(JSON, default=dict) + enabled: Mapped[bool] = mapped_column(Boolean, default=True) + next_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + last_error: Mapped[str] = mapped_column(Text, default="") + + +class ExportTask(Base): + __tablename__ = "export_task" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + owner_kind: Mapped[str] = mapped_column(String(16)) + owner_id: Mapped[str] = mapped_column(String(64), index=True) + status: Mapped[str] = mapped_column(String(16), default="queued", index=True) + file_format: Mapped[str] = mapped_column(String(8)) + params: Mapped[dict] = mapped_column(JSON, default=dict) + result_name: Mapped[str] = mapped_column(String(255), default="") + error: Mapped[str] = mapped_column(Text, default="") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) diff --git a/backend/app/nqi/client.py b/backend/app/nqi/client.py new file mode 100644 index 0000000..9af9171 --- /dev/null +++ b/backend/app/nqi/client.py @@ -0,0 +1,460 @@ +"""门户登录。登录、短信和凭证续期与已验证的 NqiTools 相同。""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import re +import time +from dataclasses import dataclass, field +from urllib.parse import quote, urlencode + +import httpx +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import padding + +from app.nqi.constants import ( + CAS_CAPTCHA, + CAS_CONFIG, + CAS_LOGIN, + CAS_PASSWORD_CHECK, + CAS_SMS, + CAS_USER, + GIS_API, + ORIGIN, + PORTAL_ONLINE, + PORTAL_SERVICE, + USER_AGENT, +) +from app.nqi.sign import build_sign + +_EXECUTION = re.compile(r'name="execution"\s+value="([^"]+)"', re.I) +_PUBLIC_KEY = re.compile(r'setPublicKey\("([^"]+)"\)') +_GENERIC_LOGIN_FAILURE = "登录未成功,请检查验证码或短信验证码" + + +class NqiError(Exception): + pass + + +class NqiAuthError(NqiError): + pass + + +class NqiNetworkError(NqiError): + pass + + +def rsa_encrypt(public_key_b64: str, text: str) -> str: + der = base64.b64decode(public_key_b64) + key = serialization.load_der_public_key(der) + encrypted = key.encrypt(text.encode("utf-8"), padding.PKCS1v15()) + return base64.b64encode(encrypted).decode("ascii") + + +def login_page_url(url: str) -> str: + if "service=" in url: + return url + return f"{CAS_LOGIN}?service={quote(PORTAL_SERVICE, safe='')}" + + +def sms_notice(payload: dict) -> str: + if payload.get("success") is False: + raise NqiError(str(payload.get("msg") or "短信发送失败")) + nested = payload.get("data") + if isinstance(nested, str): + try: + nested = json.loads(nested) + except json.JSONDecodeError: + nested = None + if isinstance(nested, dict): + code = str(nested.get("Code") or "") + content = str(nested.get("Content") or "") + if code and code != "0000": + raise NqiError(content or "短信发送失败") + if content: + return content + return "短信发送已受理" + + +def needs_captcha(message: str) -> bool: + if not message or message == _GENERIC_LOGIN_FAILURE: + return False + text = message.replace("短信验证码", "") + if "验证码" in text: + return True + lowered = text.lower() + return "captcha" in lowered and "sms" not in lowered + + +@dataclass +class LoginChallenge: + execution: str + public_key: str + captcha_png: bytes + page_url: str + captcha_type: str = "image/jpeg" + username: str = "" + password: str = "" + captcha: str = "" + config_ready: bool = False + + +@dataclass +class NqiClient: + client: httpx.AsyncClient = field(init=False) + + def __post_init__(self) -> None: + self._inflight = 0 + self._idle = asyncio.Event() + self._idle.set() + self.client = httpx.AsyncClient( + headers={ + "User-Agent": USER_AGENT, + "Accept": "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9", + }, + timeout=httpx.Timeout(45.0, connect=15.0), + follow_redirects=True, + trust_env=False, + ) + raw_send = self.client.send + + async def send(request, *args, **kwargs): + self._inflight += 1 + self._idle.clear() + try: + return await raw_send(request, *args, **kwargs) + finally: + self._inflight = max(0, self._inflight - 1) + if self._inflight == 0: + self._idle.set() + + self.client.send = send + + async def aclose(self) -> None: + await self.client.aclose() + + async def wait_idle(self, timeout: float = 5.0) -> None: + deadline = time.monotonic() + timeout + while True: + if self._inflight == 0: + await asyncio.sleep(0) + if self._inflight == 0: + return + remaining = deadline - time.monotonic() + if remaining <= 0: + return + try: + await asyncio.wait_for(self._idle.wait(), min(0.2, remaining)) + except TimeoutError: + continue + + def export_cookies(self) -> list[dict[str, str]]: + exported: list[dict[str, str]] = [] + for cookie in self.client.cookies.jar: + exported.append( + { + "name": cookie.name, + "value": cookie.value, + "domain": cookie.domain or "", + "path": cookie.path or "/", + } + ) + return exported + + def import_cookies(self, cookies: list[dict]) -> None: + for cookie in cookies: + if not cookie.get("name"): + continue + self.client.cookies.set( + cookie["name"], + cookie.get("value", ""), + domain=cookie.get("domain") or "", + path=cookie.get("path") or "/", + ) + + def ticket(self) -> str: + for name in ("CASTGC", "TGC"): + value = self.client.cookies.get(name) + if value: + return value + return "" + + def _ajax_headers(self, challenge: LoginChallenge) -> dict[str, str]: + return { + "Accept": "*/*", + "Referer": challenge.page_url, + "Origin": ORIGIN, + "X-Requested-With": "XMLHttpRequest", + } + + async def open_login(self) -> LoginChallenge: + response = await self._request("GET", CAS_LOGIN, check_auth=False, params={"service": PORTAL_SERVICE}) + html = response.text + execution = _EXECUTION.search(html) + public_key = _PUBLIC_KEY.search(html) + if not execution or not public_key: + raise NqiError("登录页没有返回加密参数,请稍后重试") + page_url = login_page_url(str(response.url)) + captcha = await self._request("GET", CAS_CAPTCHA, check_auth=False, headers={"Referer": page_url}) + if captcha.status_code != 200 or not captcha.content: + raise NqiError("验证码获取失败") + return LoginChallenge( + execution=execution.group(1), + public_key=public_key.group(1), + captcha_png=captcha.content, + page_url=page_url, + captcha_type=_media_type(captcha), + ) + + async def refresh_captcha(self, challenge: LoginChallenge) -> bytes: + response = await self._request( + "GET", + CAS_CAPTCHA, + check_auth=False, + params={"id": "refresh"}, + headers={"Referer": challenge.page_url}, + ) + if response.status_code != 200 or not response.content: + raise NqiError("验证码刷新失败") + challenge.captcha_png = response.content + challenge.captcha_type = _media_type(response) + return response.content + + async def prepare_login(self, challenge: LoginChallenge, username: str, password: str, captcha: str) -> str: + challenge.username = username + challenge.password = password + challenge.captcha = captcha.strip() + payload = { + "loginId": rsa_encrypt(challenge.public_key, username), + "password": rsa_encrypt(challenge.public_key, password), + "captcha": challenge.captcha, + } + response = await self._request( + "POST", + CAS_CONFIG, + check_auth=False, + json=payload, + headers=self._ajax_headers(challenge), + ) + data = _json_or_error(response, "登录校验失败") + code = str(data.get("code", "")) + if code not in {"0", "1"}: + message = data.get("message") or data.get("msg") or "账号、密码或验证码不正确" + raise NqiError(str(message)) + challenge.config_ready = True + return code + + async def send_sms(self, challenge: LoginChallenge) -> str: + if not challenge.username or not challenge.password: + raise NqiError("请先填写账号和密码") + payload = { + "loginId": rsa_encrypt(challenge.public_key, challenge.username), + "password": rsa_encrypt(challenge.public_key, challenge.password), + } + response = await self._request( + "POST", + CAS_SMS, + check_auth=False, + json=payload, + headers=self._ajax_headers(challenge), + timeout=httpx.Timeout(120.0, connect=15.0), + ) + data = _json_or_error(response, "短信发送失败") + return sms_notice(data) + + async def submit_login(self, challenge: LoginChallenge, sms_code: str = "") -> dict: + if not challenge.config_ready: + raise NqiError("请先完成验证码校验") + form = [ + ("password", rsa_encrypt(challenge.public_key, challenge.password)), + ("username", rsa_encrypt(challenge.public_key, challenge.username)), + ("msgCode", sms_code.strip()), + ("captcha", challenge.captcha), + ("uuid", ""), + ("execution", challenge.execution), + ("_eventId", "submit"), + ("geolocation", ""), + ] + response = await self._request( + "POST", + challenge.page_url, + check_auth=False, + content=urlencode(form).encode("utf-8"), + headers={ + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Referer": challenge.page_url, + "Origin": ORIGIN, + "Content-Type": "application/x-www-form-urlencoded", + "Upgrade-Insecure-Requests": "1", + }, + ) + if not self.ticket(): + message = _login_failure_message(response) + found = _EXECUTION.search(response.text or "") + if found: + challenge.execution = found.group(1) + if needs_captcha(message): + challenge.config_ready = False + raise NqiError(message) + return await self.current_user() + + async def _cas_user_payload(self) -> dict: + ticket = self.ticket() + headers = {"Referer": f"{ORIGIN}/pro-portal/"} + if ticket: + headers["tgc"] = ticket + response = await self._request("GET", CAS_USER, headers=headers) + data = _json_or_error(response, "读取登录用户失败") + if not data.get("loginId") and not data.get("userName"): + raise NqiAuthError("登录已失效,请重新登录") + return data + + async def current_user(self) -> dict: + return _public_user(await self._cas_user_payload()) + + async def touch_session(self) -> dict: + data = await self._cas_user_payload() + await self._touch_password() + await self._touch_online() + role_id = str(data.get("roleId") or "") + if role_id: + try: + await self._signed_get(f"{GIS_API}/base/v2/roleCityMapping/cities", {"roleCodes": role_id}) + except NqiError: + pass + return _public_user(data) + + async def _touch_password(self) -> None: + headers = { + "Referer": f"{ORIGIN}/pro-portal/", + "Origin": ORIGIN, + "Content-Type": "application/json", + } + ticket = self.ticket() + if ticket: + headers["tgc"] = ticket + await self._request( + "POST", + CAS_PASSWORD_CHECK, + json={}, + headers=headers, + timeout=httpx.Timeout(20.0, connect=10.0), + ) + + async def _touch_online(self) -> None: + try: + await self._request( + "GET", + PORTAL_ONLINE, + headers={"Referer": f"{ORIGIN}/pro-portal/"}, + timeout=httpx.Timeout(20.0, connect=10.0), + follow_redirects=False, + ) + except NqiAuthError: + raise + except NqiError: + return + + async def fetch_bytes(self, url: str) -> tuple[str, bytes]: + response = await self._request("GET", url, headers={"Referer": f"{ORIGIN}/pro-portal/"}) + if response.status_code >= 400: + raise NqiError("采集地址没有返回数据") + name = url.rsplit("/", 1)[-1] or "nqi.csv" + return name, response.content + + async def _signed_get(self, url: str, params: dict) -> dict: + headers = build_sign(params) + headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/" + response = await self._request("GET", url, params=params, headers=headers) + return _api_payload(response) + + async def _request(self, method: str, url: str, *, check_auth: bool = True, **kwargs) -> httpx.Response: + send = getattr(self.client, method.lower()) + try: + response = await send(url, **kwargs) + except httpx.TimeoutException as exc: + raise NqiNetworkError("平台响应超时,请稍后重试") from exc + except httpx.RequestError as exc: + raise NqiNetworkError("连接失败,请稍后重试") from exc + except RuntimeError as exc: + if "client has been closed" in str(exc): + raise NqiAuthError("需要重新登录") from exc + raise + if check_auth and (response.status_code in {401, 403} or _landed_on_login(response)): + raise NqiAuthError("登录已失效,请重新登录") + return response + + +def _public_user(data: dict) -> dict: + return { + "loginId": data.get("loginId") or "", + "userName": data.get("userName") or "", + "cityName": data.get("cityName") or "", + "orgName": data.get("orgName") or "", + } + + +def _login_failure_message(response: httpx.Response) -> str: + content_type = response.headers.get("content-type", "") + if "json" in content_type: + try: + data = response.json() + except json.JSONDecodeError: + data = None + if isinstance(data, dict): + message = data.get("message") or data.get("msg") + if message: + return str(message) + for pattern in ( + r'id="errMsg"[^>]*>(.*?)]*>(.*?)]*>(.*?)]+>", "", match.group(1)) + detail = re.sub(r"\s+", " ", detail).strip() + if detail: + return detail + return _GENERIC_LOGIN_FAILURE + + +def _media_type(response: httpx.Response) -> str: + raw = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip() + return raw or "image/jpeg" + + +def _landed_on_login(response: httpx.Response) -> bool: + url = getattr(response, "url", None) + if url is None: + return False + path = getattr(url, "path", "") or "" + if path: + return path.rstrip("/").endswith("/cas/login") + return "/cas/login" in str(url) + + +def _json_or_error(response: httpx.Response, fallback: str) -> dict: + if response.status_code in {401, 403}: + raise NqiAuthError("登录已失效,请重新登录") + if response.status_code >= 500: + raise NqiNetworkError("平台暂时不可用,请稍后重试") + try: + data = response.json() + except json.JSONDecodeError as exc: + raise NqiError(fallback) from exc + if not isinstance(data, dict): + raise NqiError(fallback) + return data + + +def _api_payload(response: httpx.Response) -> dict: + data = _json_or_error(response, "平台接口没有返回数据") + code = data.get("code") + if code not in (0, "0", None): + raise NqiError(str(data.get("msg") or data.get("message") or "平台接口返回失败")) + return data diff --git a/backend/app/nqi/constants.py b/backend/app/nqi/constants.py new file mode 100644 index 0000000..a5e304a --- /dev/null +++ b/backend/app/nqi/constants.py @@ -0,0 +1,23 @@ +"""平台地址与门户页面公开的签名参数。与已验证的 NqiTools 保持一致。""" + +from __future__ import annotations + +ORIGIN = "https://nqi.gmcc.net:20443" +CAS_LOGIN = f"{ORIGIN}/cas/login" +CAS_CONFIG = f"{ORIGIN}/cas/getConfig" +CAS_SMS = f"{ORIGIN}/cas/sendCode1" +CAS_CAPTCHA = f"{ORIGIN}/cas/captcha.jpg" +PORTAL_SERVICE = f"{ORIGIN}/pro-portal/" +CAS_USER = f"{ORIGIN}/pro-portalv2/api/cas/getCasUser" +CAS_PASSWORD_CHECK = f"{ORIGIN}/pro-portalv2/api/user/checkUserPasswordUpdated" +PORTAL_ONLINE = f"{ORIGIN}/pro-portal/pure/LogEnter!getOnLineCount.action" +GIS_API = f"{ORIGIN}/pro-gis-tenant/gmcc-wyzc/api" + +APP_KEY = "1e395dc741b64ce1913cf411e6c08384" +APP_SECRET = "2d6f5e13b9d54c99bea58f46c2a45ddb" +SIGN_VERSION = "1.0.0" + +USER_AGENT = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36" +) diff --git a/backend/app/nqi/flows.py b/backend/app/nqi/flows.py new file mode 100644 index 0000000..c8fb1f7 --- /dev/null +++ b/backend/app/nqi/flows.py @@ -0,0 +1,40 @@ +"""登录过程只放在内存里,超时后丢掉密码。""" + +from __future__ import annotations + +import time +import uuid + +from app.nqi.client import LoginChallenge, NqiClient + +FLOW_TTL_SECONDS = 10 * 60 +flows: dict[str, tuple[NqiClient, LoginChallenge, str]] = {} + + +async def purge(now: float | None = None) -> None: + moment = time.monotonic() if now is None else now + expired: list[str] = [] + for session_id, (client, challenge, _purpose) in list(flows.items()): + created = getattr(challenge, "created_at", None) + if created is None or moment - float(created) < FLOW_TTL_SECONDS: + continue + expired.append(session_id) + for session_id in expired: + client, challenge, _purpose = flows.pop(session_id) + challenge.password = "" + await client.aclose() + + +def remember(client: NqiClient, challenge: LoginChallenge, purpose: str) -> str: + session_id = uuid.uuid4().hex + challenge.created_at = time.monotonic() + flows[session_id] = (client, challenge, purpose) + return session_id + + +def take(session_id: str) -> tuple[NqiClient, LoginChallenge, str] | None: + return flows.get(session_id) + + +def drop(session_id: str) -> None: + flows.pop(session_id, None) diff --git a/backend/app/nqi/sign.py b/backend/app/nqi/sign.py new file mode 100644 index 0000000..8ddddec --- /dev/null +++ b/backend/app/nqi/sign.py @@ -0,0 +1,43 @@ +"""复现门户脚本里的请求签名。""" + +from __future__ import annotations + +import hashlib +import time +import uuid +from urllib.parse import quote + +from app.nqi.constants import APP_KEY, APP_SECRET, SIGN_VERSION + +_SKIP = {"sign", "SIG", "UPPER_SIG"} + + +def encode_uri_component(value: str) -> str: + return quote(value, safe="-_.!~*'()") + + +def build_sign( + params: dict | None = None, + *, + encode: bool = True, + timestamp: str | None = None, + nonce: str | None = None, +) -> dict[str, str]: + stamp = timestamp if timestamp is not None else str(int(time.time())) + nonce_str = nonce if nonce is not None else uuid.uuid4().hex + payload: dict[str, str] = {} + for key, value in (params or {}).items(): + text = "" if value is None else str(value) + payload[str(key)] = text if text == "" or not encode else encode_uri_component(text) + payload["timestamp"] = stamp + payload["nonceStr"] = nonce_str + payload["version"] = SIGN_VERSION + raw = "".join(f"{key}{payload[key]}" for key in sorted(payload) if key not in _SKIP) + sign = hashlib.md5((raw + APP_SECRET).encode("utf-8")).hexdigest().upper() + return { + "sign": sign, + "timestamp": stamp, + "nonceStr": nonce_str, + "version": SIGN_VERSION, + "appKey": APP_KEY, + } diff --git a/backend/app/runtime.py b/backend/app/runtime.py new file mode 100644 index 0000000..ceb8d45 --- /dev/null +++ b/backend/app/runtime.py @@ -0,0 +1,49 @@ +"""凭证刷新和采集周期。用户任务由队列或本进程线程执行。""" + +from __future__ import annotations + +import asyncio +import logging +import threading +import time + +from sqlalchemy import select + +from app.db import session_scope +from app.models import AppSetting +from app.tasks.runner import refresh_accounts, scan_sources + +logger = logging.getLogger("decom") +_started = False + + +def start_background() -> None: + global _started + if _started: + return + _started = True + threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start() + threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start() + + +def _refresh_loop() -> None: + while True: + seconds = 300 + try: + with session_scope() as session: + setting = session.get(AppSetting, 1) + if setting is not None: + seconds = setting.credential_refresh_seconds + asyncio.run(refresh_accounts()) + except Exception as exc: + logger.info("凭证刷新未完成: %s", exc) + time.sleep(max(60, seconds)) + + +def _collect_loop() -> None: + while True: + try: + scan_sources() + except Exception as exc: + logger.info("采集调度未完成: %s", exc) + time.sleep(60) diff --git a/backend/app/security.py b/backend/app/security.py new file mode 100644 index 0000000..c49dc92 --- /dev/null +++ b/backend/app/security.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import os +import time +from typing import Any + +from app.config import jwt_secret + +ITERATIONS = 200_000 +TOKEN_TTL = 12 * 60 * 60 + + +def hash_password(password: str) -> str: + salt = os.urandom(16) + digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS) + return f"{salt.hex()}${digest.hex()}" + + +def verify_password(password: str, stored: str) -> bool: + salt_hex, digest_hex = stored.split("$", 1) + digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), ITERATIONS) + return hmac.compare_digest(digest.hex(), digest_hex) + + +def _encode(data: dict[str, Any]) -> str: + raw = json.dumps(data, separators=(",", ":")).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def _decode(raw: str) -> dict[str, Any]: + padded = raw + "=" * (-len(raw) % 4) + return json.loads(base64.urlsafe_b64decode(padded.encode("ascii"))) + + +def issue_token(payload: dict[str, Any]) -> str: + body = {**payload, "exp": int(time.time()) + TOKEN_TTL} + raw = _encode(body) + signature = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest() + return f"{raw}.{signature}" + + +def read_token(token: str) -> dict[str, Any] | None: + raw, _, signature = token.partition(".") + if not raw or not signature: + return None + expected = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest() + if not hmac.compare_digest(expected, signature): + return None + try: + body = _decode(raw) + except (ValueError, json.JSONDecodeError): + return None + if int(body.get("exp") or 0) < int(time.time()): + return None + return body diff --git a/backend/app/tasks/queue.py b/backend/app/tasks/queue.py new file mode 100644 index 0000000..7623105 --- /dev/null +++ b/backend/app/tasks/queue.py @@ -0,0 +1,32 @@ +"""PostgreSQL 上的 Procrastinate 队列。SQLite 或本进程模式不走这里。""" + +from __future__ import annotations + +import procrastinate + +from app.config import postgres_conninfo +from app.tasks.runner import execute_collection, execute_export + +conninfo = postgres_conninfo() or "postgresql://invalid" +queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo)) + + +@queue.task(name="decom_export", queue="decom") +def decom_export(task_id: int) -> None: + execute_export(task_id) + + +@queue.task(name="decom_collect", queue="decom") +def decom_collect(source_id: int) -> None: + execute_collection(source_id) + + +def defer(name: str, **kwargs) -> None: + job = decom_export if name == "decom_export" else decom_collect + job.defer(**kwargs) + + +def serve() -> None: + with queue.open(): + queue.schema_manager.apply_schema() + queue.run_worker(queues=["decom"], concurrency=4) diff --git a/backend/app/tasks/runner.py b/backend/app/tasks/runner.py new file mode 100644 index 0000000..1525b7e --- /dev/null +++ b/backend/app/tasks/runner.py @@ -0,0 +1,252 @@ +"""用户任务只读库里已有的数据,再写成表格。采集另走自己的队列。""" + +from __future__ import annotations + +import logging +import threading +from datetime import 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 RESULT_DIR, inline_worker, postgres_conninfo +from app.db import session_scope +from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow +from app.nqi.client import NqiAuthError, NqiClient, NqiError + +logger = logging.getLogger("decom") +_pool = threading.Semaphore(4) + + +def check_period(days: int) -> int: + if days < 1 or days > 31: + raise ValueError("周期最短一天,最长一个月") + return days + + +def check_refresh(seconds: int) -> int: + if seconds < 60 or seconds > 24 * 60 * 60: + raise ValueError("刷新间隔需要在 1 分钟到 1 天之间") + return seconds + + +def upsert_rows(session, source: str, rows: list[dict]) -> int: + count = 0 + for row in rows: + existing = session.scalar( + select(CellData).where( + CellData.cell_key == row["cell_key"], + CellData.observed_at == row["observed_at"], + CellData.source == source, + ) + ) + if existing is None: + session.add( + CellData( + cell_key=row["cell_key"], + observed_at=row["observed_at"], + source=source, + metrics=row["metrics"], + ) + ) + count += 1 + else: + existing.metrics = row["metrics"] + return count + + +def query_cells(session, params: dict) -> list[dict]: + statement = select(CellData).order_by(CellData.observed_at, CellData.cell_key) + cell_key = str(params.get("cellKey") or "").strip() + if cell_key: + statement = statement.where(CellData.cell_key == cell_key) + start = _optional_time(params.get("start")) + end = _optional_time(params.get("end")) + if start is not None: + statement = statement.where(CellData.observed_at >= start) + if end is not None: + statement = statement.where(CellData.observed_at <= end) + rows = session.scalars(statement).all() + return [ + {"cell_key": row.cell_key, "observed_at": row.observed_at, "metrics": row.metrics or {}} + for row in rows + ] + + +def _optional_time(value) -> datetime | None: + if not value: + return None + text = str(value).replace("/", "-").replace("T", " ") + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): + try: + return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc) + except ValueError: + continue + return None + + +def execute_export(task_id: int) -> None: + with _pool: + with session_scope() as session: + task = session.get(ExportTask, task_id) + if task is None or task.status not in {"queued", "running"}: + return + task.status = "running" + params = dict(task.params or {}) + file_format = task.file_format + try: + with session_scope() as session: + rows = query_cells(session, params) + name, content = write_table(file_format, rows) + RESULT_DIR.mkdir(parents=True, exist_ok=True) + path = RESULT_DIR / f"{task_id}-{name}" + path.write_bytes(content) + with session_scope() as session: + task = session.get(ExportTask, task_id) + if task is None: + return + task.status = "done" + task.result_name = path.name + task.finished_at = utcnow() + except Exception as exc: + logger.info("导出失败: %s", exc) + with session_scope() as session: + task = session.get(ExportTask, task_id) + if task is None: + return + task.status = "failed" + task.error = str(exc) or "导出失败" + task.finished_at = utcnow() + + +def execute_collection(source_id: int) -> None: + with session_scope() as session: + source = session.get(CollectionSource, source_id) + if source is None or not source.enabled: + return + kind = source.kind + config = dict(source.config or {}) + account = None + if kind == "nqi": + 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 [] + else: + cookies = [] + try: + if kind == "ftp": + name, content = fetch_ftp(config) + elif kind == "nqi": + if not cookies: + raise ValueError("账号池里没有可用凭证") + name, content = _fetch_nqi_sync(cookies, config) + else: + raise ValueError("未知的采集来源") + rows = parse_upload(name, content) + with session_scope() as session: + source = session.get(CollectionSource, source_id) + if source is None: + return + upsert_rows(session, kind, rows) + source.last_error = "" + except Exception as exc: + logger.info("采集失败: %s", exc) + with session_scope() as session: + source = session.get(CollectionSource, source_id) + if source is not None: + source.last_error = str(exc) or "采集失败" + + +def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]: + import asyncio + + async def run() -> tuple[str, bytes]: + client = NqiClient() + try: + client.import_cookies(cookies) + try: + await client.current_user() + except NqiAuthError as exc: + raise ValueError("账号池凭证已失效") from exc + return await fetch_nqi(client, config) + finally: + await client.aclose() + + return asyncio.run(run) + + +def enqueue_export(task_id: int) -> None: + if _defer("decom_export", task_id=task_id): + return + threading.Thread(target=execute_export, args=(task_id,), daemon=True).start() + + +def enqueue_collection(source_id: int) -> None: + if _defer("decom_collect", source_id=source_id): + return + threading.Thread(target=execute_collection, args=(source_id,), daemon=True).start() + + +def _defer(name: str, **kwargs) -> bool: + if inline_worker() or not postgres_conninfo(): + return False + try: + from app.tasks.queue import defer + + defer(name, **kwargs) + return True + except Exception as exc: + logger.info("排队未投递,改为本进程执行: %s", exc) + return False + + +def scan_sources() -> None: + now = utcnow() + due_ids: list[int] = [] + with session_scope() as session: + sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all() + for source in sources: + if source.next_run_at is not None and source.next_run_at > now: + continue + source.next_run_at = now + timedelta(days=source.period_days) + due_ids.append(source.id) + for source_id in due_ids: + enqueue_collection(source_id) + + +async def refresh_accounts() -> None: + with session_scope() as session: + accounts = session.scalars(select(NqiAccount)).all() + snapshots = [(item.id, list(item.cookies or [])) for item in accounts] + for account_id, cookies in snapshots: + if not cookies: + continue + outcome = await _touch(cookies) + with session_scope() as session: + account = session.get(NqiAccount, account_id) + if account is None or outcome is None: + continue + valid, user, refreshed = outcome + account.credential_valid = valid + if valid and user is not None: + account.user_name = user.get("userName") or account.user_name + account.city_name = user.get("cityName") or account.city_name + account.org_name = user.get("orgName") or account.org_name + account.cookies = refreshed + account.saved_at = utcnow() + + +async def _touch(cookies: list): + client = NqiClient() + try: + client.import_cookies(cookies) + user = await client.touch_session() + return True, user, client.export_cookies() + except NqiAuthError: + return False, None, cookies + except (NqiError, OSError): + return None + finally: + await client.aclose() diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..d2606d4 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,13 @@ +fastapi +uvicorn +sqlalchemy>=2 +alembic +psycopg[binary] +procrastinate +httpx +cryptography +python-multipart +openpyxl +xlwt +paramiko +pytest diff --git a/backend/tests/test_core.py b/backend/tests/test_core.py new file mode 100644 index 0000000..599d607 --- /dev/null +++ b/backend/tests/test_core.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import os +import time +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +os.environ["DECOM_DATABASE_URL"] = "sqlite+pysqlite:///" + (Path(__file__).resolve().parents[1] / "data" / "test.db").as_posix() +os.environ["DECOM_INLINE_WORKER"] = "1" +os.environ["DECOM_ADMIN_USERNAME"] = "admin" +os.environ["DECOM_ADMIN_PASSWORD"] = "admin-pass" +os.environ["DECOM_JWT_SECRET"] = "test-secret" + +from app.collect.io import parse_csv, write_csv # noqa: E402 +from app.db import reset_engine # noqa: E402 +from app.main import create_app # noqa: E402 +from app.nqi.client import needs_captcha, rsa_encrypt # noqa: E402 +from app.tasks.runner import check_period # noqa: E402 + +PUBLIC_KEY = ( + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+" + "chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB" +) + + +@pytest.fixture() +def client(): + database = Path(os.environ["DECOM_DATABASE_URL"].removeprefix("sqlite+pysqlite:///")) + if database.exists(): + database.unlink() + reset_engine() + application = create_app() + with TestClient(application) as test_client: + yield test_client + reset_engine() + if database.exists(): + database.unlink() + + +def test_period_bounds(): + assert check_period(1) == 1 + assert check_period(31) == 31 + with pytest.raises(ValueError): + check_period(0) + with pytest.raises(ValueError): + check_period(32) + + +def test_csv_roundtrip_and_gbk(): + content = "小区,时间,拆除前\nGZ-1,2026-01-02 03:04:05,-91\n".encode("gbk") + rows = parse_csv(content) + assert rows[0]["cell_key"] == "GZ-1" + assert rows[0]["metrics"]["拆除前"] == "-91" + text = write_csv(rows).decode("utf-8-sig") + assert "GZ-1" in text + + +def test_needs_captcha_ignores_sms(): + assert needs_captcha("图形验证码错误") is True + assert needs_captcha("短信验证码错误") is False + rsa_encrypt(PUBLIC_KEY, "user") + + +def test_local_login_task_and_admin(client: TestClient): + denied = client.post("/api/auth/local", json={"username": "admin", "password": "wrong"}) + assert denied.status_code == 400 + logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"}) + assert logged.status_code == 200 + token = logged.json()["token"] + headers = {"Authorization": f"Bearer {token}"} + blocked = client.get("/api/tasks", headers=headers) + assert blocked.status_code == 403 + created = client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers) + assert created.status_code == 200 + user = client.post("/api/auth/local", json={"username": "user", "password": "user-pass"}) + user_headers = {"Authorization": f"Bearer {user.json()['token']}"} + task = client.post("/api/tasks", json={"format": "csv", "cellKey": ""}, headers=user_headers) + assert task.status_code == 200 + assert task.json()["task"]["status"] == "queued" + task_id = task.json()["task"]["id"] + for _ in range(20): + listing = client.get("/api/tasks", headers=user_headers).json()["tasks"] + if listing[0]["status"] == "done": + break + time.sleep(0.1) + assert listing[0]["status"] == "done" + downloaded = client.get(f"/api/tasks/{task_id}/file", headers=user_headers) + assert downloaded.status_code == 200 + assert "小区" in downloaded.content.decode("utf-8-sig") diff --git a/backend/worker/main.py b/backend/worker/main.py new file mode 100644 index 0000000..e91fc87 --- /dev/null +++ b/backend/worker/main.py @@ -0,0 +1,25 @@ +"""执行排队的导出和采集。""" + +from __future__ import annotations + +from app.bootstrap import init_db +from app.config import postgres_conninfo +from app.runtime import start_background + + +def main() -> None: + init_db() + start_background() + if postgres_conninfo(): + from app.tasks.queue import serve + + serve() + return + import time + + while True: + time.sleep(3600) + + +if __name__ == "__main__": + main() diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..ea89a90 --- /dev/null +++ b/web/index.html @@ -0,0 +1,12 @@ + + + + + + DecomEval + + +
+ + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..4208b9b --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,1377 @@ +{ + "name": "decomeval-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "decomeval-web", + "version": "0.1.0", + "dependencies": { + "naive-ui": "^2.43.2", + "vue": "^3.5.13", + "vue-router": "^4.5.1" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.7", + "typescript": "~6.0.3", + "vite": "^8.0.16", + "vue-tsc": "^3.3.5" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", + "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.11.tgz", + "integrity": "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@css-render/plugin-bem": { + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@css-render/plugin-bem/-/plugin-bem-0.15.14.tgz", + "integrity": "sha512-QK513CJ7yEQxm/P3EwsI+d+ha8kSOcjGvD6SevM41neEMxdULE+18iuQK6tEChAWMOQNQPLG/Rw3Khb69r5neg==", + "license": "MIT", + "peerDependencies": { + "css-render": "~0.15.14" + } + }, + "node_modules/@css-render/vue3-ssr": { + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@css-render/vue3-ssr/-/vue3-ssr-0.15.14.tgz", + "integrity": "sha512-//8027GSbxE9n3QlD73xFY6z4ZbHbvrOVB7AO6hsmrEzGbg+h2A09HboUyDgu+xsmj7JnvJD39Irt+2D0+iV8g==", + "license": "MIT", + "peerDependencies": { + "vue": "^3.0.11" + } + }, + "node_modules/@emotion/hash": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz", + "integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==", + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@juggle/resize-observer": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@juggle/resize-observer/-/resize-observer-3.4.0.tgz", + "integrity": "sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==", + "license": "Apache-2.0" + }, + "node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@vitejs/plugin-vue": { + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.10.tgz", + "integrity": "sha512-b80aUQh3n+qEzzZm5oQp3rT2QImeCx58K6eFl/RkJ3d65KW0kTuv5lNsLRVAjbW9YRUpo/wzmvzMgV34bTAItA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", + "vue": "^3.2.25 || ^3.6.0-rc.10" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz", + "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.28" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz", + "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz", + "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.44.tgz", + "integrity": "sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.9", + "@vue/shared": "3.5.44", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.44.tgz", + "integrity": "sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.44.tgz", + "integrity": "sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.9", + "@vue/compiler-core": "3.5.44", + "@vue/compiler-dom": "3.5.44", + "@vue/compiler-ssr": "3.5.44", + "@vue/shared": "3.5.44", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.29", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.44.tgz", + "integrity": "sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "3.3.13", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.3.13.tgz", + "integrity": "sha512-axA0Xemn5LuUKuKWob0/kVq7xQ2mJJM6VqA9Exvt35nM9yRC31goWVve/G/Zb2ZCLsXC8FHYjjfXlnshknSCew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "@vue/compiler-dom": "^3.5.0", + "@vue/shared": "^3.5.0", + "alien-signals": "^3.2.1", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1", + "picomatch": "^4.0.4" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.44.tgz", + "integrity": "sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.44.tgz", + "integrity": "sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.44.tgz", + "integrity": "sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.44", + "@vue/runtime-core": "3.5.44", + "@vue/shared": "3.5.44", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.44.tgz", + "integrity": "sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.44", + "@vue/runtime-dom": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.44.tgz", + "integrity": "sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==", + "license": "MIT" + }, + "node_modules/alien-signals": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.2.1.tgz", + "integrity": "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-validator": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz", + "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==", + "license": "MIT" + }, + "node_modules/css-render": { + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/css-render/-/css-render-0.15.14.tgz", + "integrity": "sha512-9nF4PdUle+5ta4W5SyZdLCCmFd37uVimSjg1evcTqKJCyvCEEj12WKzOSBNak6r4im4J4iYXKH1OWpUV5LBYFg==", + "license": "MIT", + "dependencies": { + "@emotion/hash": "~0.8.0", + "csstype": "~3.0.5" + } + }, + "node_modules/css-render/node_modules/csstype": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.11.tgz", + "integrity": "sha512-sa6P2wJ+CAbgyy4KFssIb/JNMLxFvKF1pCYCSXS8ZMuqZnMsrxqI2E5sPyoTpxoPU/gVZMzr2zjOfg8GIZOMsw==", + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/date-fns": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/date-fns-tz": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz", + "integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==", + "license": "MIT", + "peerDependencies": { + "date-fns": "^3.0.0 || ^4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/evtd": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/evtd/-/evtd-0.2.4.tgz", + "integrity": "sha512-qaeGN5bx63s/AXgQo8gj6fBkxge+OoLddLniox5qtLAEY5HSnuSlISXVPxnSae1dWblvTh4/HoMIB+mbMsvZzw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/highlight.js": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz", + "integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/naive-ui": { + "version": "2.45.3", + "resolved": "https://registry.npmjs.org/naive-ui/-/naive-ui-2.45.3.tgz", + "integrity": "sha512-D83gJ+6zUdkQ5DuUbmlfyaM1t8pV5WMPa6KmL9mByqQuiL12qBdA0n/iEIth4dQw1x/duNGpOS2anpt5FKO1kw==", + "license": "MIT", + "dependencies": { + "@css-render/plugin-bem": "^0.15.14", + "@css-render/vue3-ssr": "^0.15.14", + "@types/lodash": "^4.17.20", + "@types/lodash-es": "^4.17.12", + "async-validator": "^4.2.5", + "css-render": "^0.15.14", + "csstype": "^3.1.3", + "date-fns": "^4.1.0", + "date-fns-tz": "^3.2.0", + "evtd": "^0.2.4", + "highlight.js": "^11.8.0", + "lodash": "^4.17.21", + "lodash-es": "^4.17.21", + "seemly": "^0.3.10", + "treemate": "^0.3.11", + "vdirs": "^0.1.8", + "vooks": "^0.2.12", + "vueuc": "^0.4.66" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "vue": "^3.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.155.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" + } + }, + "node_modules/seemly": { + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/seemly/-/seemly-0.3.10.tgz", + "integrity": "sha512-2+SMxtG1PcsL0uyhkumlOU6Qo9TAQ/WyH7tthnPIOQB05/12jz9naq6GZ6iZ6ApVsO3rr2gsnTf3++OV63kE1Q==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/treemate": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/treemate/-/treemate-0.3.11.tgz", + "integrity": "sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==", + "license": "MIT" + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vdirs": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/vdirs/-/vdirs-0.1.8.tgz", + "integrity": "sha512-H9V1zGRLQZg9b+GdMk8MXDN2Lva0zx72MPahDKc30v+DtwKjfyOSXWRIX4t2mhDubM1H09gPhWeth/BJWPHGUw==", + "license": "MIT", + "dependencies": { + "evtd": "^0.2.2" + }, + "peerDependencies": { + "vue": "^3.0.11" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vooks": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/vooks/-/vooks-0.2.12.tgz", + "integrity": "sha512-iox0I3RZzxtKlcgYaStQYKEzWWGAduMmq+jS7OrNdQo1FgGfPMubGL3uGHOU9n97NIvfFDBGnpSvkWyb/NSn/Q==", + "license": "MIT", + "dependencies": { + "evtd": "^0.2.2" + }, + "peerDependencies": { + "vue": "^3.0.0" + } + }, + "node_modules/vscode-uri": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz", + "integrity": "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.44", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.44.tgz", + "integrity": "sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.44", + "@vue/compiler-sfc": "3.5.44", + "@vue/runtime-dom": "3.5.44", + "@vue/server-renderer": "3.5.44", + "@vue/shared": "3.5.44" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "3.3.13", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.3.13.tgz", + "integrity": "sha512-jE4/bXdOMSHVxEGgQCqNllJy+9N3Gx6tfSAsg0yhFK/MAN6eXqISihupnDEKSCt12VVnjN2gI3AqLYcqoh5x/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.28", + "@vue/language-core": "3.3.13" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/vueuc": { + "version": "0.4.66", + "resolved": "https://registry.npmjs.org/vueuc/-/vueuc-0.4.66.tgz", + "integrity": "sha512-hHrZl+0AsrUvqYPBXSXQ2QaSrO3razjeUseLAhJWlOS/Hdfw/Y2MU05fOTP1qn1A3121gMxsHLaEz2V6CkWdTg==", + "license": "MIT", + "dependencies": { + "@css-render/vue3-ssr": "^0.15.10", + "@juggle/resize-observer": "^3.3.1", + "css-render": "^0.15.10", + "evtd": "^0.2.4", + "seemly": "^0.3.6", + "vdirs": "^0.1.4", + "vooks": "^0.2.4" + }, + "peerDependencies": { + "vue": "^3.0.11" + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..816e4fd --- /dev/null +++ b/web/package.json @@ -0,0 +1,22 @@ +{ + "name": "decomeval-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "naive-ui": "^2.43.2", + "vue": "^3.5.13", + "vue-router": "^4.5.1" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.7", + "typescript": "~6.0.3", + "vite": "^8.0.16", + "vue-tsc": "^3.3.5" + } +} diff --git a/web/src/App.vue b/web/src/App.vue new file mode 100644 index 0000000..915db74 --- /dev/null +++ b/web/src/App.vue @@ -0,0 +1,45 @@ + + + diff --git a/web/src/features/admin/PoolView.vue b/web/src/features/admin/PoolView.vue new file mode 100644 index 0000000..9a16ca9 --- /dev/null +++ b/web/src/features/admin/PoolView.vue @@ -0,0 +1,59 @@ + + + diff --git a/web/src/features/admin/SettingsView.vue b/web/src/features/admin/SettingsView.vue new file mode 100644 index 0000000..0e68845 --- /dev/null +++ b/web/src/features/admin/SettingsView.vue @@ -0,0 +1,52 @@ + + + diff --git a/web/src/features/admin/SourcesView.vue b/web/src/features/admin/SourcesView.vue new file mode 100644 index 0000000..9b972dc --- /dev/null +++ b/web/src/features/admin/SourcesView.vue @@ -0,0 +1,137 @@ + + + diff --git a/web/src/features/admin/UsersView.vue b/web/src/features/admin/UsersView.vue new file mode 100644 index 0000000..4f7e994 --- /dev/null +++ b/web/src/features/admin/UsersView.vue @@ -0,0 +1,71 @@ + + + diff --git a/web/src/features/auth/LoginView.vue b/web/src/features/auth/LoginView.vue new file mode 100644 index 0000000..ebcf313 --- /dev/null +++ b/web/src/features/auth/LoginView.vue @@ -0,0 +1,180 @@ + + + diff --git a/web/src/features/user/TasksView.vue b/web/src/features/user/TasksView.vue new file mode 100644 index 0000000..781ad73 --- /dev/null +++ b/web/src/features/user/TasksView.vue @@ -0,0 +1,91 @@ + + + diff --git a/web/src/main.ts b/web/src/main.ts new file mode 100644 index 0000000..d00d35d --- /dev/null +++ b/web/src/main.ts @@ -0,0 +1,35 @@ +import { createApp } from "vue"; +import { createRouter, createWebHistory } from "vue-router"; +import App from "./App.vue"; +import LoginView from "./features/auth/LoginView.vue"; +import TasksView from "./features/user/TasksView.vue"; +import SettingsView from "./features/admin/SettingsView.vue"; +import UsersView from "./features/admin/UsersView.vue"; +import PoolView from "./features/admin/PoolView.vue"; +import SourcesView from "./features/admin/SourcesView.vue"; +import { token } from "./shared/http"; +import "./styles.css"; + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: "/login", component: LoginView }, + { path: "/", redirect: "/tasks" }, + { path: "/tasks", component: TasksView, meta: { role: "user" } }, + { path: "/admin/settings", component: SettingsView, meta: { role: "admin" } }, + { path: "/admin/users", component: UsersView, meta: { role: "admin" } }, + { path: "/admin/pool", component: PoolView, meta: { role: "admin" } }, + { path: "/admin/sources", component: SourcesView, meta: { role: "admin" } }, + ], +}); + +router.beforeEach((to) => { + if (to.path === "/login") return token() ? "/" : true; + if (!token()) return "/login"; + const role = sessionStorage.getItem("decom-role"); + if (to.meta.role === "admin" && role !== "admin") return "/tasks"; + if (to.meta.role === "user" && role === "admin") return "/admin/settings"; + return true; +}); + +createApp(App).use(router).mount("#app"); diff --git a/web/src/shared/http.ts b/web/src/shared/http.ts new file mode 100644 index 0000000..7c73adc --- /dev/null +++ b/web/src/shared/http.ts @@ -0,0 +1,58 @@ +export class ApiError extends Error { + status: number; + + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +export function token() { + return sessionStorage.getItem("decom-token") || ""; +} + +export function setToken(value: string) { + if (value) sessionStorage.setItem("decom-token", value); + else sessionStorage.removeItem("decom-token"); +} + +export function saveSession(tokenValue: string, user: { role: string; name: string }) { + setToken(tokenValue); + sessionStorage.setItem("decom-role", user.role); + sessionStorage.setItem("decom-name", user.name); +} + +export function clearSession() { + setToken(""); + sessionStorage.removeItem("decom-role"); + sessionStorage.removeItem("decom-name"); +} + +export async function api(path: string, options: RequestInit = {}): Promise { + const headers = new Headers(options.headers); + if (!(options.body instanceof FormData) && options.body && !headers.has("Content-Type")) { + headers.set("Content-Type", "application/json"); + } + const current = token(); + if (current) headers.set("Authorization", `Bearer ${current}`); + const response = await fetch(path, { ...options, headers }); + if (response.status === 401) { + setToken(""); + sessionStorage.removeItem("decom-role"); + sessionStorage.removeItem("decom-name"); + } + if (!response.ok) { + let message = "请求失败"; + try { + const payload = await response.json(); + message = payload.detail || message; + } catch { + message = response.statusText || message; + } + throw new ApiError(response.status, message); + } + if (response.headers.get("content-type")?.includes("application/json")) { + return response.json() as Promise; + } + return response as unknown as T; +} diff --git a/web/src/shared/theme.ts b/web/src/shared/theme.ts new file mode 100644 index 0000000..046506c --- /dev/null +++ b/web/src/shared/theme.ts @@ -0,0 +1,24 @@ +import { computed, ref } from "vue"; + +export type ThemeChoice = "system" | "dark" | "light"; + +const STORAGE_KEY = "decom-theme"; +const media = window.matchMedia("(prefers-color-scheme: dark)"); +const stored = localStorage.getItem(STORAGE_KEY); +export const themeChoice = ref(stored === "dark" || stored === "light" || stored === "system" ? stored : "system"); +const systemDark = ref(media.matches); + +media.addEventListener("change", () => { + systemDark.value = media.matches; +}); + +export const isDark = computed(() => { + if (themeChoice.value === "dark") return true; + if (themeChoice.value === "light") return false; + return systemDark.value; +}); + +export function setThemeChoice(choice: ThemeChoice) { + themeChoice.value = choice; + localStorage.setItem(STORAGE_KEY, choice); +} diff --git a/web/src/shell/Shell.vue b/web/src/shell/Shell.vue new file mode 100644 index 0000000..9606abc --- /dev/null +++ b/web/src/shell/Shell.vue @@ -0,0 +1,57 @@ + + + diff --git a/web/src/styles.css b/web/src/styles.css new file mode 100644 index 0000000..c2dec8b --- /dev/null +++ b/web/src/styles.css @@ -0,0 +1,88 @@ +:root { + color: var(--ink); + background: var(--bg); + font-family: "Segoe UI", "Microsoft YaHei", sans-serif; + font-size: 14px; +} +* { box-sizing: border-box; } +html, body, #app { margin: 0; height: 100%; } +body { background: var(--bg); } +button, input, select { font: inherit; } +::selection { background: var(--accent-soft); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +.shell { display: flex; height: 100%; min-height: 0; } +.sider { + width: 216px; + flex: none; + display: flex; + flex-direction: column; + background: var(--sidebar); + border-right: 1px solid var(--line); +} +.brand { + height: 56px; + display: flex; + align-items: center; + padding: 0 16px; + border-bottom: 1px solid var(--line); + font-weight: 650; +} +.nav { padding-top: 8px; } +.nav button, .text-button { + width: 100%; + text-align: left; + background: transparent; + color: var(--muted); + border: 0; + padding: 10px 16px; + cursor: pointer; +} +.nav button.on { color: var(--ink); box-shadow: inset 2px 0 0 var(--accent); } +.sider-foot { + margin-top: auto; + padding: 12px; + border-top: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 8px; +} +.who { color: var(--muted); font-size: 12px; } +.main { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.topbar { + position: sticky; + top: 0; + z-index: 2; + height: 56px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 16px; + background: var(--bg); + border-bottom: 1px solid var(--line); +} +.topbar h1 { margin: 0; font-size: 18px; display: flex; align-items: center; gap: 6px; } +.content { padding: 16px; overflow: auto; } +.panel { background: var(--panel); border: 1px solid var(--line); } +.filters, .form-grid { display: grid; grid-template-columns: 96px minmax(0, 280px); gap: 8px 12px; align-items: center; } +.hint { + width: 16px; + height: 16px; + border: 1px solid var(--line); + border-radius: 50%; + color: var(--muted); + font-size: 11px; + line-height: 14px; + text-align: center; + cursor: default; +} +.gate { + min-height: 100%; + display: flex; + align-items: center; + justify-content: center; + padding: 32px 16px; +} +.gate-card { width: min(440px, 100%); background: var(--panel); border: 1px solid var(--line); padding: 28px; } +.captcha { height: 40px; cursor: pointer; } +.row-actions { display: flex; gap: 8px; } diff --git a/web/src/vite-env.d.ts b/web/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/web/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..bded6d7 --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "jsx": "preserve", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "lib": ["ES2022", "DOM"], + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 0000000..094ee78 --- /dev/null +++ b/web/vite.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vite"; +import vue from "@vitejs/plugin-vue"; + +export default defineConfig({ + plugins: [vue()], + server: { + port: 5173, + proxy: { + "/api": "http://127.0.0.1:8000", + }, + }, +});