diff --git a/Configure.json b/Configure.json
index e2e7b72..d7bc1e6 100644
--- a/Configure.json
+++ b/Configure.json
@@ -1,8 +1,5 @@
{
"Update": "2026/07/13 12:02:36",
- "MetrixEnabled": true,
- "SourceType": "external",
- "WarehouseType": "mysql",
"MySQL_DBInfo": {
"host": "127.0.0.1",
"port": 3306,
@@ -10,14 +7,6 @@
"dbname": "CapacityReport",
"passwd": "123456"
},
- "Metrix": {
- "base_url": "http://host.docker.internal:8000",
- "storage_id": "",
- "database_conn_id": "",
- "target_database": "",
- "recent_days": 7,
- "token": ""
- },
"DataMappings": {
"directories": [
{
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index a84f516..90c6693 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -13,7 +13,7 @@
| pandas / openpyxl | Excel/CSV 数据读取与处理 |
| chardet | CSV 编码探测 |
| pymysql | 直连 MySQL 读写 |
-| cryptography | 本地授权文件加密 |
+| cryptography | MySQL 8 `caching_sha2_password` 认证 |
| paramiko | SFTP 远程下载 |
### 前端(Vue 3)
@@ -46,27 +46,28 @@
```text
CapacityReport/
├─ app/ # 后端(FastAPI)
-│ ├─ main.py # 入口:创建应用、鉴权中间件、注册路由、托管前端
+│ ├─ main.py # 入口:创建应用、鉴权中间件、注册路由、托管前端(注入 )
│ ├─ state.py # 运行时共享状态(配置、历史、任务锁、上传会话)
│ ├─ config.py # 配置读写(AppConfig 与各配置块)
-│ ├─ auth.py # 登录账号(auth.ini)、JWT、密码修改
+│ ├─ auth.py # 登录账号(auth.ini)、JWT、密码修改、Metrix 平台代理身份
│ ├─ db_init.py # 启动时确保必要数据表存在
│ ├─ database.py # DatabaseManager:直连 MySQL 表操作
│ ├─ warehouse.py # 数据库访问的统一封装
│ ├─ processor.py # DataProcessor:解压/转换/入库/执行报表 SQL;ProcessLogger
│ ├─ history.py # HistoryManager:处理历史记录与日志
│ ├─ api/routers/ # 各业务接口(按模块拆分,见下表)
-│ ├─ services/ # 业务服务(远程下载、调度、CellData、授权等)
+│ ├─ services/ # 业务服务(远程下载、调度、CellData 等)
│ └─ utils/ # 通用工具(文件、文件名日期解析)
├─ frontend/ # 前端(Vue 3 + Vite)
│ └─ src/
│ ├─ AppShell.vue # 整体框架:登录、侧边导航、顶栏、主题切换
│ ├─ App.vue / main.ts # 应用根与入口
+│ ├─ base.ts # 站点所在路径(直接访问为 /,托管时为 /apps/capacityreport/)
│ ├─ router.ts # 路由表(6 个功能页)
│ ├─ types.ts # 前端类型定义
│ ├─ api/client.ts # 请求封装(token、错误处理、下载)
│ ├─ components/ # 各功能页面与公共组件
-│ └─ composables/ # 可复用逻辑(页头、主题、剪贴板、日志等)
+│ └─ composables/ # 可复用逻辑(页头、主题、会话、剪贴板、日志等)
├─ src-tauri/ # Tauri 桌面壳(Rust)
│ ├─ src/main.rs # 启动/停止 Python sidecar、下载、打开目录
│ └─ tauri.conf.json # 桌面打包配置(WebView2、NSIS 等)
@@ -83,7 +84,16 @@ CapacityReport/
└─ requirements.txt # Python 依赖
```
-运行时数据(不进版本库):`cache/`(任务工作目录、历史记录 `history.json`)、`logs/`、`auth.ini`(账号)、`license.dat`(授权)。
+运行时数据(不进版本库):`cache/`(任务工作目录、历史记录 `history.json`)、`logs/`、`auth.ini`(账号)。
+
+## 托管到 Metrix
+
+`python scripts/package_metrix.py` 会构建前端和镜像,生成 `dist/metrix/capacityreport-<版本>.zip`,在 Metrix「应用托管」上传部署即可。包内 `metrix-app.json` 使用 `user_auth: metrix`、`admin_auth: none`,数据目录 `/data` 挂在平台数据卷上。
+
+- 身份:平台给容器注入 `METRIX_APP_PROXY_TOKEN` 后进入托管模式。只有请求里的 `X-Metrix-Proxy-Token` 与之一致时才认 `X-Metrix-User-Id`、`X-Metrix-Display-Name`、`X-Metrix-App-Role` 等身份头;应用自己的 JWT、`/api/login` 和 `/api/change-password` 都停用。谁能访问由 Metrix 的应用角色决定。
+- 路径:平台反代时会去掉 `/apps/capacityreport` 前缀并带上 `X-Forwarded-Prefix`,后端据此改写 `index.html` 里的 ``。前端用相对路径构建(`vite base: './'`),接口地址和路由都以 `base.ts` 的 `basePath` 为准。
+- 前端启动时请求 `/api/session`:托管模式隐藏登录页、退出按钮和「修改密码」页,顶栏显示当前用户名。
+- 不设置 `METRIX_APP_PROXY_TOKEN` 时行为与原来一致,直接访问、Docker 和桌面端都不受影响。
## 功能与代码对照
@@ -92,7 +102,7 @@ CapacityReport/
公共代码(多数功能都会用到):
- 前端框架与导航:`frontend/src/AppShell.vue`、`router.ts`、`api/client.ts`、`composables/`
-- 后端入口与共享:`app/main.py`、`app/state.py`、`app/config.py`、`app/api/routers/task_runtime.py`(任务阶段、授权日志、历史保留清理)
+- 后端入口与共享:`app/main.py`、`app/state.py`、`app/config.py`、`app/api/routers/task_runtime.py`(任务阶段、历史保留清理)
### 数据处理
@@ -109,7 +119,6 @@ CapacityReport/
| 服务 | `app/services/remote_download.py` | FTP/SFTP 远程下载 |
| 服务 | `app/services/auto_scheduler.py` | 后台自动调度(按目标周检查远程数据就绪) |
| 服务 | `app/services/cell_data.py` | CellData 解析入库、执行 `CellData.sql`、跨库复制 |
-| 服务 | `app/services/license.py` | 按数据日期校验授权期限 |
| 工具 | `app/utils/file_dates.py` | 文件名日期解析、按目录筛选最近 7 天文件 |
### 容量看板
@@ -156,15 +165,13 @@ CapacityReport/
### 系统设置
-页面路由 `/settings`。配置数据库、远程数据源、字段映射、自动调度等,并提供修改密码。
+页面路由 `/settings`。配置数据库、远程数据源、字段映射、自动调度等,并提供修改密码(托管到 Metrix 时不显示)。
| 类型 | 文件 | 职责 |
| --- | --- | --- |
| 前端 | `frontend/src/components/SettingsPanel.vue` | 各类配置表单、连接测试、配置导入导出 |
-| 前端 | `frontend/src/components/LicenseActivationModal.vue` | 授权延期窗口(连点品牌图标 8 次打开) |
+| 前端 | `frontend/src/composables/session.ts` | 会话信息:是否托管、当前用户名 |
| 接口 | `app/api/routers/config.py` | 各配置块读写、配置上传/下载、MySQL/远程/CellData 连接测试、CellData 规则校验 |
-| 接口 | `app/api/routers/auth.py` | 登录、修改密码 |
-| 接口 | `app/api/routers/license.py` | 授权状态查询与激活 |
+| 接口 | `app/api/routers/auth.py` | 会话信息、登录、修改密码 |
| 服务 | `app/config.py` | AppConfig 及各配置块的解析与保存 |
-| 服务 | `app/auth.py` | 账号(`auth.ini`)、JWT |
-| 服务 | `app/services/license.py` | 授权加密文件读写、激活码校验 |
+| 服务 | `app/auth.py` | 账号(`auth.ini`)、JWT、Metrix 平台代理身份 |
diff --git a/README.md b/README.md
index 2e3c689..f320b37 100644
--- a/README.md
+++ b/README.md
@@ -54,6 +54,7 @@ CapacityReport 用于处理每周的网络容量报表数据:从本地上传
| `python scripts/build_server.py` | 编译 Server 便携版 |
| `python scripts/build_tauri.py` | 编译 Tauri 桌面版 |
| `python scripts/build_docker.py` | 编译 / 更新 Docker 镜像 |
+| `python scripts/package_metrix.py` | 打包 Metrix 应用包 |
| `python scripts/clean.py` | 清理缓存与编译产物 |
### 本地运行
@@ -81,8 +82,11 @@ python scripts/dev.py
python scripts/build_server.py # Server 便携版(dist/server/)
python scripts/build_tauri.py # Tauri 桌面版(dist/desktop/)
python scripts/build_docker.py # Docker 镜像 + 离线包(dist/docker/)
+python scripts/package_metrix.py # Metrix 应用包(dist/metrix/capacityreport-<版本>.zip)
```
+Metrix 应用包在「应用托管」上传部署,使用 Metrix 账号访问,说明见 [DEVELOPMENT.md](DEVELOPMENT.md#托管到-metrix)。
+
桌面版需在目标系统本机构建(Windows 包在 Windows、Linux 包在 Linux、macOS 包在 macOS);Windows 安装包内置 WebView2 离线安装器。Docker 离线包部署:
```bash
diff --git a/USAGE.md b/USAGE.md
index ee1f0d8..3b519a8 100644
--- a/USAGE.md
+++ b/USAGE.md
@@ -7,6 +7,7 @@
- 启动服务后在浏览器访问 `http://localhost:9081`(桌面版直接打开应用窗口)。
- 默认账号:用户名 `root`,密码 `Capacity`。
- 登录后可在「系统设置 → 修改密码」修改密码。建议使用 Chrome / Edge 等现代浏览器。
+- 托管到 Metrix 时使用 Metrix 账号:在 Metrix「应用托管」中给用户授权后,从应用入口打开即可,不需要再登录 CapacityReport,也没有退出和修改密码入口。
## 整体使用流程
@@ -55,8 +56,7 @@ flowchart LR
```mermaid
flowchart LR
S0[远程下载中] --> S1[更新 CellData]
- S1 --> S2[授权校验]
- S2 --> S3[解压数据]
+ S1 --> S3[解压数据]
S3 --> S4[转换 Excel]
S4 --> S5[导入数据]
S5 --> S6[运行脚本]
@@ -67,7 +67,6 @@ flowchart LR
| --- | --- |
| 远程下载中 | 从 FTP/SFTP 下载数据(仅远程方式) |
| 更新 CellData | 启用 CellData 数据源时,容量处理前先刷新小区信息 |
-| 授权校验中 | 按数据日期校验授权期限 |
| 解压数据中 | 解压上传/下载的 ZIP |
| 转换 Excel 中 | 将 Excel 转换为 CSV |
| 导入数据中 | 数据写入 MySQL 暂存表 |
@@ -135,7 +134,7 @@ flowchart LR
| 远程数据源 | 容量数据 FTP/SFTP、CellData 数据源(含扫描路径、规则设置) |
| 自动调度 | 开关、检查间隔、目标周期、预期目录、调度状态 |
| 规则映射 | Sheet 过滤规则、字段映射、数据目录映射 |
-| 修改密码 | 修改登录密码 |
+| 修改密码 | 修改登录密码(托管到 Metrix 时不显示) |
页面顶部可下载 / 上传配置文件(`Configure.json`),方便备份与迁移。
@@ -147,7 +146,6 @@ flowchart LR
| 文件命名日期 | 容量数据 ZIP 文件名需含时间戳(`XXX_YYYYMMDDHHMM` 或 `XXX_YYYYMMDDHHMM_YYYYMMDDHHMM`),系统以**第一个**时间戳作为数据日期 |
| 每目录 7 天窗口 | 每个目录只保留并处理最近 7 个自然日的文件 |
| CellData 文件 | 来源为 `Result_300_*.zip`,时间取文件名末尾时间戳;本地上传必须按频段目录组织 |
-| 授权期限 | 处理时按数据日期校验授权,超期会失败;可在弹出的激活框输入激活码延长 30 天 |
| 自动调度前提 | 开启自动调度会强制开启远程自动化与处理后删除源文件,请确认远程目录配置正确 |
| 数据安全 | 清空表、删除表、删除行、删除历史均不可恢复,操作前请确认 |
| 端口占用 | 服务默认使用 `9081` 端口,若被占用可在运行时指定其他端口 |
diff --git a/app/api/routers/auth.py b/app/api/routers/auth.py
index 77de9f5..3153b2b 100644
--- a/app/api/routers/auth.py
+++ b/app/api/routers/auth.py
@@ -1,12 +1,27 @@
-from fastapi import APIRouter, Body
+from fastapi import APIRouter, Body, Request
from fastapi.responses import JSONResponse
-from app.auth import create_jwt_token, get_auth_config, save_auth_password
+from app.auth import (
+ create_jwt_token,
+ get_auth_config,
+ is_hosted,
+ resolve_platform_context,
+ save_auth_password,
+)
router = APIRouter(tags=["auth"])
+@router.get("/api/session")
+async def get_session(request: Request):
+ if not is_hosted():
+ return {"hosted": False, "user": None}
+ context = resolve_platform_context(request)
+ user = {"name": context.payload["name"], "role": context.payload["role"]} if context else None
+ return {"hosted": True, "user": user}
+
+
@router.post("/api/login")
async def login(
username: str = Body(..., embed=True),
@@ -33,4 +48,3 @@ async def change_password(
save_auth_password(new_password)
return {"success": True, "message": "密码修改成功"}
-
diff --git a/app/api/routers/config.py b/app/api/routers/config.py
index 5fca356..2c32894 100644
--- a/app/api/routers/config.py
+++ b/app/api/routers/config.py
@@ -14,11 +14,8 @@ from app.config import (
DataMappingsConfig,
DEFAULT_CELL_DATA_MAPPING,
HistoryRetentionConfig,
- MetrixConfig,
MySQLConfig,
RemoteDataConfig,
- SOURCE_TYPES,
- WAREHOUSE_TYPES,
)
from app.services.remote_download import RemoteDataDownloader
@@ -62,41 +59,6 @@ async def update_remote_config(config: dict[str, Any] = Body(...)):
return {"success": True, "message": "远程数据配置已更新", "update": state.config.update}
-@router.post("/api/config/metrix-enabled")
-async def update_metrix_enabled(enabled: bool = Body(..., embed=True)):
- state.reload_config()
- state.config.metrix_enabled = enabled
- if not enabled:
- state.config.source_type = "external"
- state.config.warehouse_type = "mysql"
- state.config.save()
- return {"success": True, "message": "已更新", "update": state.config.update}
-
-
-@router.post("/api/config/backend")
-async def update_backend(
- source_type: str = Body(...),
- warehouse_type: str = Body(...),
-):
- if source_type not in SOURCE_TYPES:
- raise HTTPException(status_code=400, detail="不支持的源类型")
- if warehouse_type not in WAREHOUSE_TYPES:
- raise HTTPException(status_code=400, detail="不支持的仓库类型")
- state.reload_config()
- state.config.source_type = source_type
- state.config.warehouse_type = warehouse_type
- state.config.save()
- return {"success": True, "message": "后端类型已更新", "update": state.config.update}
-
-
-@router.post("/api/config/metrix")
-async def update_metrix_config(config: dict[str, Any] = Body(...)):
- state.reload_config()
- state.config.metrix = MetrixConfig.from_dict(config)
- state.config.save()
- return {"success": True, "message": "Metrix 连接配置已更新", "update": state.config.update}
-
-
@router.post("/api/config/data-mappings")
async def update_data_mappings_config(config: dict[str, Any] = Body(...)):
state.reload_config()
@@ -255,23 +217,6 @@ async def upload_config(file: UploadFile = File(...)):
def _apply_config_data(data: dict[str, Any]) -> None:
- if "MetrixEnabled" in data:
- state.config.metrix_enabled = bool(data["MetrixEnabled"])
-
- if data.get("SourceType") in SOURCE_TYPES:
- state.config.source_type = data["SourceType"]
- if data.get("WarehouseType") in WAREHOUSE_TYPES:
- state.config.warehouse_type = data["WarehouseType"]
-
- # 未启用 Metrix 时强制回落为外部储存 + 直连 MySQL,避免导入后状态不一致
- if not state.config.metrix_enabled:
- state.config.source_type = "external"
- state.config.warehouse_type = "mysql"
-
- metrix_data = data.get("Metrix")
- if isinstance(metrix_data, dict):
- state.config.metrix = MetrixConfig.from_dict(metrix_data)
-
data_mappings = data.get("DataMappings")
if isinstance(data_mappings, dict):
state.config.data_mappings = DataMappingsConfig.from_dict(data_mappings)
diff --git a/app/api/routers/dashboard.py b/app/api/routers/dashboard.py
index 610f66b..2c688d0 100644
--- a/app/api/routers/dashboard.py
+++ b/app/api/routers/dashboard.py
@@ -1,7 +1,7 @@
"""容量看板分析接口。
基于 4G/5G 结果表(含富集 + 高负荷判定 + 优化建议列)做聚合分析,供前端容量看板展示。
-读经 `make_warehouse`(直连 MySQL 或 Metrix 平台),分析对象为“主仓库”里的结果表。
+读经 `make_warehouse`(直连 MySQL),分析对象为“主仓库”里的结果表。
"""
from __future__ import annotations
diff --git a/app/api/routers/database.py b/app/api/routers/database.py
index f8f0027..c226eca 100644
--- a/app/api/routers/database.py
+++ b/app/api/routers/database.py
@@ -12,7 +12,6 @@ from starlette.background import BackgroundTask
from app import state
from app.config import CACHE_DIR
from app.database import DatabaseManager, detect_csv_encoding
-from app.services.platform import make_client
from app.utils.files import remove_file_safely
from app.warehouse import make_cell_data_warehouse, make_warehouse
@@ -55,7 +54,6 @@ def _dataframe_from_table(db: DatabaseManager, table_name: str) -> pd.DataFrame:
def _db(database_source: DatabaseSource = "main"):
- """Direct MySQL DatabaseManager, or a Metrix-backed warehouse with the same interface."""
config = state.current_config()
if database_source == "cell_data":
return make_cell_data_warehouse(config)
@@ -335,8 +333,8 @@ def execute_sql(
raise HTTPException(status_code=500, detail=str(exc)) from exc
-# Sync def so FastAPI runs it in a threadpool: exporting large tables (and the Metrix
-# export-job polling) is blocking and would otherwise freeze the single-worker event loop.
+# Sync def so FastAPI runs it in a threadpool: exporting large tables is blocking and
+# would otherwise freeze the single-worker event loop.
@router.post("/api/download")
def download_table(
table_name: Optional[str] = Body(None, embed=True),
@@ -353,10 +351,6 @@ def download_table(
if file_format == "csv" and len(requested_tables) != 1:
raise HTTPException(status_code=400, detail="CSV 每次只能导出一张表")
- config = state.current_config()
- if database_source == "main" and config.warehouse_type == "metrix":
- return _download_via_metrix(config, requested_tables, file_format)
-
db = _db(database_source)
try:
available_tables = set(db.get_tables())
@@ -399,32 +393,3 @@ def download_table(
media_type=media_type,
background=BackgroundTask(remove_file_safely, filepath),
)
-
-
-def _download_via_metrix(config, requested_tables: list[str], file_format: str) -> FileResponse:
- """Metrix 仓库模式:用平台导出任务生成文件后流式返回(避免分页上限丢行)。"""
- metrix = config.metrix.normalized()
- client = make_client(metrix)
- try:
- job_id = client.submit_export(metrix.database_conn_id, requested_tables, file_format, metrix.target_database)
- job = client.wait_job(job_id)
- if job.get("status") != "success":
- raise HTTPException(status_code=500, detail=f"导出失败: {job.get('error_code') or job.get('status')}")
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- filename_prefix = requested_tables[0] if len(requested_tables) == 1 else "tables"
- filename = f"{filename_prefix}_{timestamp}.{file_format}"
- filepath = CACHE_DIR / filename
- CACHE_DIR.mkdir(parents=True, exist_ok=True)
- client.download_job_file(job_id, filepath)
- except HTTPException:
- raise
- except Exception as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
-
- media_type = "text/csv" if file_format == "csv" else "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
- return FileResponse(
- path=str(filepath),
- filename=filename,
- media_type=media_type,
- background=BackgroundTask(remove_file_safely, filepath),
- )
diff --git a/app/api/routers/license.py b/app/api/routers/license.py
deleted file mode 100644
index 83e1d53..0000000
--- a/app/api/routers/license.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from fastapi import APIRouter, Body, HTTPException
-
-from app.services.license import InvalidActivationCodeError, activate, get_license_info
-
-
-router = APIRouter(tags=["license"])
-
-
-@router.get("/api/license/status")
-async def get_license_status():
- info = get_license_info()
- return {"success": True, **info.to_dict()}
-
-
-@router.post("/api/license/activate")
-async def activate_license(code: str = Body(..., embed=True)):
- try:
- info = activate(code)
- except InvalidActivationCodeError as exc:
- raise HTTPException(status_code=400, detail=exc.to_detail()) from exc
-
- return {
- "success": True,
- "message": "激活成功,到期日期已延长 30 天",
- **info.to_dict(),
- }
diff --git a/app/api/routers/remote.py b/app/api/routers/remote.py
index 028125e..38760dd 100644
--- a/app/api/routers/remote.py
+++ b/app/api/routers/remote.py
@@ -1,4 +1,3 @@
-import time
from datetime import date, datetime
from pathlib import Path
from threading import Thread
@@ -7,32 +6,23 @@ from typing import Any, Callable, Iterable
from fastapi import APIRouter, Body, HTTPException
from app import state
-from app.api.routers.task_runtime import (
- apply_history_retention_safely,
- log_license_check,
- set_task_stage,
-)
+from app.api.routers.task_runtime import apply_history_retention_safely, set_task_stage
from app.config import AppConfig, CACHE_DIR, RemoteDataConfig
from app.processor import DataProcessor, ProcessLogger
from app.config import CELLDATA_SCRIPT
from app.services.cell_data import copy_celldata_tables_to_capacity, execute_celldata_script, refresh_cell_data
-from app.services.license import LicenseError, check_processing_allowed
-from app.services.platform import PlatformStorageDownloader, make_source_downloader
-from app.services.pipeline import RESULT_TABLES, run_import_and_report
from app.services.remote_download import RemoteDataDownloader
router = APIRouter(tags=["remote"])
+RESULT_TABLES = ["4G_结果表", "5G_结果表"]
@router.post("/api/remote/test")
def test_remote_connection(config: dict[str, Any] | None = Body(None)):
app_config = state.current_config()
try:
- if app_config.source_type == "metrix":
- PlatformStorageDownloader(app_config).test_connection()
- return {"success": True, "message": "平台储存连接成功"}
- # FTP/SFTP: test the posted form config if provided, else the saved one.
+ # Test the posted form config if provided, else the saved one.
remote_config = RemoteDataConfig.from_dict(config) if config else app_config.remote_data
RemoteDataDownloader(remote_config).test_connection()
return {"success": True, "message": "远程服务器连接成功"}
@@ -133,14 +123,11 @@ def _run_remote_processing(
) -> None:
final_status = "failed"
try:
- if app_config.source_type == "metrix":
- logger.info(f"开始从平台储存下载,目录: {remote_config.remote_dir}")
- else:
- logger.info(
- f"开始远程下载,协议: {remote_config.protocol.upper()},"
- f"服务器: {remote_config.host}:{remote_config.port},目录: {remote_config.remote_dir}"
- )
- downloader = make_source_downloader(app_config, logger.info)
+ logger.info(
+ f"开始远程下载,协议: {remote_config.protocol.upper()},"
+ f"服务器: {remote_config.host}:{remote_config.port},目录: {remote_config.remote_dir}"
+ )
+ downloader = RemoteDataDownloader(remote_config, logger.info)
download_result = downloader.download_to(work_dir, target_dates=target_dates)
logger.success(
f"下载完成,共 {download_result.file_count} 个文件,"
@@ -154,18 +141,11 @@ def _run_remote_processing(
_try_refresh_cell_data(app_config, work_dir, logger)
- if app_config.warehouse_type == "metrix":
- started = time.time()
- run_import_and_report(work_dir, app_config, logger)
- status, error, elapsed = "completed", None, round(time.time() - started, 2)
- else:
- logger.set_stage("license")
- log_license_check(logger, check_processing_allowed(work_dir))
- processor = DataProcessor(app_config, work_dir, logger)
- result = processor.process()
- status = "completed" if result.get("success") else "failed"
- error = result.get("error")
- elapsed = result.get("elapsed_time", 0)
+ processor = DataProcessor(app_config, work_dir, logger)
+ result = processor.process()
+ status = "completed" if result.get("success") else "failed"
+ error = result.get("error")
+ elapsed = result.get("elapsed_time", 0)
if status == "completed" and remote_config.auto_delete_source:
try:
deleted_count = downloader.delete_source_files(download_result.remote_files)
@@ -191,7 +171,6 @@ def _run_remote_processing(
"error": error,
}
except Exception as exc:
- error_detail = exc.to_detail() if isinstance(exc, LicenseError) else None
if source == "scheduler":
logger.error(f"自动调度任务失败: {exc}")
else:
@@ -202,7 +181,6 @@ def _run_remote_processing(
"status": "failed",
"stage": "failed",
"error": str(exc),
- "error_detail": error_detail,
}
finally:
apply_history_retention_safely()
diff --git a/app/api/routers/script.py b/app/api/routers/script.py
index 0a016f3..b4ec5ea 100644
--- a/app/api/routers/script.py
+++ b/app/api/routers/script.py
@@ -115,10 +115,6 @@ def _run_script(
logger.info(f"开始执行{label}...")
if script_type == "celldata":
_run_celldata_script(script_path, app_config, logger)
- elif app_config.warehouse_type == "metrix":
- from app.services.pipeline import run_report_sql
-
- run_report_sql(app_config, logger)
else:
temp_work_dir = CACHE_DIR / task_id
temp_work_dir.mkdir(parents=True, exist_ok=True)
diff --git a/app/api/routers/task_runtime.py b/app/api/routers/task_runtime.py
index 2c2fcf8..1231f0b 100644
--- a/app/api/routers/task_runtime.py
+++ b/app/api/routers/task_runtime.py
@@ -1,5 +1,4 @@
import logging
-from typing import Any
from app import state
@@ -17,18 +16,6 @@ def set_task_stage(task_id: str, stage: str, logs: list[str], status: str = "pro
state.global_task_lock["stage"] = stage
-def log_license_check(logger: Any, info: Any) -> None:
- if info.current_date:
- logger.info(
- f"授权校验通过,数据日期: {info.current_date.isoformat()},"
- f"到期日期: {info.expires_on.isoformat()}"
- )
- elif info.zip_count:
- logger.warning("未从 ZIP 文件名识别到日期,已跳过授权日期比对")
- else:
- logger.warning("未找到 ZIP 文件,已跳过授权日期比对")
-
-
def apply_history_retention_safely() -> None:
try:
state.apply_history_retention()
diff --git a/app/api/routers/tasks.py b/app/api/routers/tasks.py
index 9e30b5d..23e0b43 100644
--- a/app/api/routers/tasks.py
+++ b/app/api/routers/tasks.py
@@ -6,16 +6,11 @@ from typing import Any
from fastapi import APIRouter, Body, HTTPException
from app import state
-from app.api.routers.task_runtime import (
- apply_history_retention_safely,
- log_license_check,
- set_task_stage,
-)
+from app.api.routers.task_runtime import apply_history_retention_safely, set_task_stage
from app.config import AppConfig
from app.processor import DataProcessor, ProcessLogger
from app.config import CELLDATA_SCRIPT
from app.services.cell_data import copy_celldata_tables_to_capacity, execute_celldata_script, refresh_cell_data
-from app.services.license import LicenseError, check_processing_allowed
router = APIRouter(tags=["tasks"])
@@ -142,7 +137,6 @@ async def get_processing_status(task_id: str = Body(..., embed=True)):
"stage": task_info.get("stage"),
"logs": logs,
"error": task_info.get("error"),
- "error_detail": task_info.get("error_detail"),
}
record = state.history_manager.get(task_id)
@@ -171,23 +165,12 @@ def _task_finished(task_id: str) -> bool:
def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_config: AppConfig) -> None:
try:
_try_refresh_cell_data(app_config, work_dir, logger)
- if app_config.warehouse_type == "metrix":
- import time
-
- from app.services.pipeline import RESULT_TABLES, run_import_and_report
-
- started = time.time()
- run_import_and_report(work_dir, app_config, logger)
- status, error, elapsed, result_tables = "completed", None, round(time.time() - started, 2), RESULT_TABLES
- else:
- logger.set_stage("license")
- log_license_check(logger, check_processing_allowed(work_dir))
- processor = DataProcessor(app_config, work_dir, logger)
- result = processor.process()
- status = "completed" if result.get("success") else "failed"
- error = result.get("error")
- elapsed = result.get("elapsed_time", 0)
- result_tables = ["4G_结果表", "5G_结果表"]
+ processor = DataProcessor(app_config, work_dir, logger)
+ result = processor.process()
+ status = "completed" if result.get("success") else "failed"
+ error = result.get("error")
+ elapsed = result.get("elapsed_time", 0)
+ result_tables = ["4G_结果表", "5G_结果表"]
state.history_manager.update(
task_id,
status=status,
@@ -202,7 +185,6 @@ def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_con
"error": error,
}
except Exception as exc:
- error_detail = exc.to_detail() if isinstance(exc, LicenseError) else None
logger.error(str(exc))
state.history_manager.update(task_id, status="failed", error=str(exc))
state.processing_tasks[task_id] = {
@@ -210,7 +192,6 @@ def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_con
"status": "failed",
"stage": "failed",
"error": str(exc),
- "error_detail": error_detail,
}
finally:
apply_history_retention_safely()
diff --git a/app/auth.py b/app/auth.py
index 5e271e3..be80c0a 100644
--- a/app/auth.py
+++ b/app/auth.py
@@ -3,9 +3,11 @@ import configparser
import hashlib
import hmac
import json
+import os
import time
from dataclasses import dataclass
from typing import Optional
+from urllib.parse import unquote
from starlette.requests import Request
@@ -16,6 +18,7 @@ SECRET_KEY = "CapaReportSecretKey2026"
AUTH_INI_PATH = BASE_DIR / "auth.ini"
DEFAULT_USERNAME = "root"
DEFAULT_PASSWORD = "Capacity"
+PLATFORM_ROLES = {"admin", "user"}
@dataclass(frozen=True)
@@ -126,6 +129,45 @@ def resolve_access_context(request: Request) -> AuthContext | None:
return None
+def platform_proxy_token() -> str:
+ return os.environ.get("METRIX_APP_PROXY_TOKEN", "").strip()
+
+
+def is_hosted() -> bool:
+ """托管到 Metrix 时平台会注入代理令牌,此时只认平台代理带来的身份。"""
+ return bool(platform_proxy_token())
+
+
+def resolve_platform_context(request: Request) -> AuthContext | None:
+ expected = platform_proxy_token()
+ if not expected:
+ return None
+ given = request.headers.get("x-metrix-proxy-token") or ""
+ if not hmac.compare_digest(given.encode("utf-8"), expected.encode("utf-8")):
+ return None
+
+ user_id = _platform_header(request, "x-metrix-user-id")
+ role = _platform_header(request, "x-metrix-app-role").lower()
+ if not user_id or role not in PLATFORM_ROLES:
+ return None
+ username = _platform_header(request, "x-metrix-username")
+ display_name = _platform_header(request, "x-metrix-display-name")
+ return AuthContext(
+ kind="platform",
+ payload={
+ "user_id": user_id,
+ "username": username,
+ "name": display_name or username or user_id,
+ "role": role,
+ },
+ )
+
+
+def _platform_header(request: Request, name: str) -> str:
+ """平台对身份头做了 URL 编码,中文用户名和显示名都要解码。"""
+ return unquote(request.headers.get(name) or "", encoding="utf-8", errors="replace").strip()
+
+
def _encode_json(data: dict) -> str:
raw = json.dumps(data, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
diff --git a/app/config.py b/app/config.py
index 3234001..67cbd0e 100644
--- a/app/config.py
+++ b/app/config.py
@@ -72,11 +72,6 @@ class MySQLConfig:
).normalized()
-# Source backends: external (FTP/SFTP), or Metrix storage platform.
-SOURCE_TYPES = ("external", "metrix")
-# Warehouse backends: direct MySQL, or Metrix database platform.
-WAREHOUSE_TYPES = ("mysql", "metrix")
-
DEFAULT_CELL_DATA_SCAN_PATHS = [
"/网优日常优化数据文档/日常性能报表/{maxyear}年/300表",
]
@@ -173,61 +168,6 @@ DEFAULT_CELL_DATA_MAPPING: Dict[str, Any] = {
}
-@dataclass
-class MetrixConfig:
- """Connection to a Metrix platform, used when source_type/warehouse_type is 'metrix'.
-
- Metrix appears in the UI as two connection types ("存储平台"/"数据库平台") that share the
- same base_url + token; storage_id is the file source, database_conn_id + target_database
- are the warehouse.
- """
- base_url: str = "http://host.docker.internal:8000"
- token: str = ""
- storage_id: str = ""
- database_conn_id: str = ""
- target_database: str = ""
- recent_days: int = 7
-
- def normalized(self) -> "MetrixConfig":
- try:
- recent_days = max(int(self.recent_days), 1)
- except (TypeError, ValueError):
- recent_days = 7
- return MetrixConfig(
- base_url=str(self.base_url or "").strip(),
- token=str(self.token or "").strip(),
- storage_id=str(self.storage_id or "").strip(),
- database_conn_id=str(self.database_conn_id or "").strip(),
- target_database=str(self.target_database or "").strip(),
- recent_days=recent_days,
- )
-
- def to_dict(self, include_token: bool = False) -> Dict[str, Any]:
- n = self.normalized()
- data = {
- "base_url": n.base_url,
- "storage_id": n.storage_id,
- "database_conn_id": n.database_conn_id,
- "target_database": n.target_database,
- "recent_days": n.recent_days,
- }
- if include_token:
- data["token"] = n.token
- return data
-
- @classmethod
- def from_dict(cls, data: Dict[str, Any] | None) -> "MetrixConfig":
- data = data or {}
- return cls(
- base_url=str(data.get("base_url", "http://host.docker.internal:8000")),
- token=str(data.get("token", "")),
- storage_id=str(data.get("storage_id", "")),
- database_conn_id=str(data.get("database_conn_id", "")),
- target_database=str(data.get("target_database", "")),
- recent_days=data.get("recent_days", 7),
- ).normalized()
-
-
@dataclass
class DataMappingsConfig:
"""Source directories mapped to staging tables."""
@@ -533,28 +473,10 @@ class HistoryRetentionConfig:
).normalized()
-def _normalize_source_type(value: Any, protocol: str = "sftp") -> str:
- text = str(value or "").strip().lower()
- if text in SOURCE_TYPES:
- return text
- if text in ("ftp", "sftp"):
- return "external"
- return "external"
-
-
-def _normalize_warehouse_type(value: Any) -> str:
- text = str(value or "").strip().lower()
- return text if text in WAREHOUSE_TYPES else "mysql"
-
-
@dataclass
class AppConfig:
update: str = ""
- metrix_enabled: bool = False
- source_type: str = "external"
- warehouse_type: str = "mysql"
mysql: MySQLConfig = field(default_factory=MySQLConfig)
- metrix: MetrixConfig = field(default_factory=MetrixConfig)
data_mappings: DataMappingsConfig = field(default_factory=DataMappingsConfig)
remote_data: RemoteDataConfig = field(default_factory=RemoteDataConfig)
cell_data: CellDataConfig = field(default_factory=CellDataConfig)
@@ -573,18 +495,13 @@ class AppConfig:
mysql_config = MySQLConfig.from_dict(data.get("MySQL_DBInfo"))
remote_config = RemoteDataConfig.from_dict(data.get("RemoteData"))
- metrix_config = MetrixConfig.from_dict(data.get("Metrix"))
data_mappings = DataMappingsConfig.from_dict(data.get("DataMappings"))
cell_data = CellDataConfig.from_dict(data.get("CellData"))
history_retention = HistoryRetentionConfig.from_dict(data.get("HistoryRetention"))
return cls(
update=data.get("Update", ""),
- metrix_enabled=bool(data.get("MetrixEnabled", False)),
- source_type=_normalize_source_type(data.get("SourceType"), remote_config.protocol),
- warehouse_type=_normalize_warehouse_type(data.get("WarehouseType")),
mysql=mysql_config,
- metrix=metrix_config,
data_mappings=data_mappings,
remote_data=remote_config,
cell_data=cell_data,
@@ -605,11 +522,7 @@ class AppConfig:
"""转换为配置文件结构(包含敏感字段,用于保存和下载)"""
return {
"Update": self.update,
- "MetrixEnabled": self.metrix_enabled,
- "SourceType": self.source_type,
- "WarehouseType": self.warehouse_type,
"MySQL_DBInfo": self.mysql.normalized().to_dict(include_password=True),
- "Metrix": self.metrix.normalized().to_dict(include_token=True),
"DataMappings": self.data_mappings.normalized().to_dict(),
"RemoteData": self.remote_data.normalized().to_dict(include_password=True),
"CellData": self.cell_data.normalized().to_dict(include_password=True),
@@ -622,11 +535,7 @@ class AppConfig:
"""转换为字典(用于返回给前端,隐藏密码)"""
return {
"update": self.update,
- "metrix_enabled": self.metrix_enabled,
- "source_type": self.source_type,
- "warehouse_type": self.warehouse_type,
"mysql": self.mysql.normalized().to_dict(),
- "metrix": self.metrix.normalized().to_dict(),
"data_mappings": self.data_mappings.normalized().to_dict(),
"remote_data": self.remote_data.normalized().to_dict(),
"cell_data": self.cell_data.normalized().to_dict(),
@@ -639,11 +548,7 @@ class AppConfig:
"""转换为完整字典(包含密码,用于编辑时回显)"""
return {
"update": self.update,
- "metrix_enabled": self.metrix_enabled,
- "source_type": self.source_type,
- "warehouse_type": self.warehouse_type,
"mysql": self.mysql.normalized().to_dict(include_password=True),
- "metrix": self.metrix.normalized().to_dict(include_token=True),
"data_mappings": self.data_mappings.normalized().to_dict(),
"remote_data": self.remote_data.normalized().to_dict(include_password=True),
"cell_data": self.cell_data.normalized().to_dict(include_password=True),
diff --git a/app/db_init.py b/app/db_init.py
index 6a214d4..6a3c18f 100644
--- a/app/db_init.py
+++ b/app/db_init.py
@@ -1,13 +1,13 @@
"""数据库前置检查:先确保各「库」存在(不存在则自动创建),再确保各库「必须存在的结构表」已建好。
约定(见 db_init/README.md):
-- 建库:对 celldata 与 capacityreport(仅直连 MySQL 时) 两个目标库执行 CREATE DATABASE IF NOT EXISTS,
+- 建库:对 celldata 与 capacityreport 两个目标库执行 CREATE DATABASE IF NOT EXISTS,
库名以用户配置为准;连接时若库不存在不会报错(先用不带 database 的连接建库)。
- 建表:初始化 SQL 放在 BASE_DIR/db_init/,文件名形如 ``<库标识>.<表名>.sql``,仅当目标表「不存在」时执行,
因此 sector_band_ref 这类带预设数据的表只在首次创建时写入,绝不覆盖用户自定义。
- 库标识 -> 实际连接(库名以用户配置为准,不写死):
- celldata -> AppConfig.cell_data.mysql(CellData 库,始终直连 MySQL)
- capacityreport -> AppConfig.mysql(主仓库,仅当 warehouse_type == 'mysql' 直连时检查)
+ celldata -> AppConfig.cell_data.mysql(CellData 库)
+ capacityreport -> AppConfig.mysql(容量主库)
- 全过程 best-effort:单个库/单张表失败只记录日志并继续,不阻断启动或处理流程。
"""
from __future__ import annotations
@@ -36,12 +36,10 @@ def _log(logger, message: str) -> None:
def _target_mysql(app_config: AppConfig, db_key: str) -> Optional[MySQLConfig]:
- """库标识 -> MySQL 连接配置;不适用(如主库走 Metrix)时返回 None。"""
+ """库标识 -> MySQL 连接配置;未知标识返回 None。"""
if db_key == "celldata":
return app_config.cell_data.mysql.normalized()
if db_key == "capacityreport":
- if app_config.warehouse_type != "mysql":
- return None
return app_config.mysql.normalized()
return None
diff --git a/app/main.py b/app/main.py
index 8d419d1..4723f6e 100644
--- a/app/main.py
+++ b/app/main.py
@@ -1,12 +1,13 @@
import argparse
import os
+import re
from contextlib import asynccontextmanager
from pathlib import Path
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import FileResponse, JSONResponse
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from app import state
from app.api.routers import (
@@ -18,13 +19,12 @@ from app.api.routers import (
database,
health,
history,
- license,
remote,
script,
tasks,
upload,
)
-from app.auth import resolve_access_context, resolve_login_context
+from app.auth import is_hosted, resolve_access_context, resolve_login_context, resolve_platform_context
from app.config import BASE_DIR
from app.services.auto_scheduler import AutoScheduler
@@ -34,11 +34,15 @@ APP_HOST = "0.0.0.0"
APP_PORT = 9081
# Code/frontend live in the image (/app); runtime state lives on the data volume (BASE_DIR=/data).
FRONTEND_DIST_DIR = Path(os.environ.get("CAPAREPORT_FRONTEND_DIR") or (BASE_DIR / "frontend" / "dist"))
+OPEN_API_PATHS = {"/api/login", "/api/session"}
LOGIN_ONLY_API_PREFIXES = (
"/api/config",
"/api/change-password",
- "/api/license",
)
+# 托管后账号由 Metrix 管理,应用自己的登录与改密码接口停用。
+HOSTED_DISABLED_API_PATHS = {"/api/login", "/api/change-password"}
+FORWARDED_PREFIX_PATTERN = re.compile(r"^/apps/[a-z0-9-]+$")
+BASE_TAG_PATTERN = re.compile(r"]*>", re.IGNORECASE)
@asynccontextmanager
@@ -88,7 +92,13 @@ async def auth_middleware(request: Request, call_next):
return await call_next(request)
path = request.url.path
- if path == "/api/login":
+ if not path.startswith("/api/"):
+ return await call_next(request)
+
+ if is_hosted():
+ return await _hosted_auth(request, call_next, path)
+
+ if path in OPEN_API_PATHS:
return await call_next(request)
if _is_login_only_api(path):
@@ -96,13 +106,25 @@ async def auth_middleware(request: Request, call_next):
return JSONResponse(status_code=401, content={"detail": "未登录或登录已过期"})
return await call_next(request)
- if path.startswith("/api/"):
- access_context = resolve_access_context(request)
- if access_context is None:
- return JSONResponse(status_code=401, content={"detail": "未授权,请提供有效的 Token"})
+ access_context = resolve_access_context(request)
+ if access_context is None:
+ return JSONResponse(status_code=401, content={"detail": "未授权,请提供有效的 Token"})
- request.state.auth_context = access_context
+ request.state.auth_context = access_context
+ return await call_next(request)
+
+async def _hosted_auth(request: Request, call_next, path: str):
+ if path in HOSTED_DISABLED_API_PATHS:
+ return JSONResponse(status_code=404, content={"detail": "接口不存在"})
+ if path == "/api/session":
+ return await call_next(request)
+
+ platform_context = resolve_platform_context(request)
+ if platform_context is None:
+ return JSONResponse(status_code=401, content={"detail": "未授权,请从 Metrix 平台访问"})
+
+ request.state.auth_context = platform_context
return await call_next(request)
@@ -114,7 +136,6 @@ def register_routes(app: FastAPI) -> None:
remote.router,
tasks.router,
history.router,
- license.router,
database.router,
config.router,
cache.router,
@@ -129,30 +150,45 @@ def register_routes(app: FastAPI) -> None:
def register_frontend(app: FastAPI) -> None:
@app.get("/", include_in_schema=False)
@app.get("/{path:path}", include_in_schema=False)
- async def serve_frontend(path: str = ""):
+ async def serve_frontend(request: Request, path: str = ""):
if path.startswith("api/"):
raise HTTPException(status_code=404, detail="接口不存在")
- return _serve_frontend_path(path)
+ return _serve_frontend_path(path, request.headers.get("x-forwarded-prefix", ""))
-def _serve_frontend_path(path: str):
+def _serve_frontend_path(path: str, forwarded_prefix: str = ""):
if not FRONTEND_DIST_DIR.exists():
return JSONResponse(
status_code=503,
content={"detail": "前端构建产物不存在,请先执行 cd frontend && npm install && npm run build"},
)
- requested_file = _safe_file(FRONTEND_DIST_DIR, path)
- if requested_file and requested_file.exists() and requested_file.is_file():
- return FileResponse(str(requested_file))
-
index_file = FRONTEND_DIST_DIR / "index.html"
+ requested_file = _safe_file(FRONTEND_DIST_DIR, path)
+ if requested_file and requested_file.is_file() and requested_file != index_file.resolve():
+ return FileResponse(str(requested_file))
+ # 缺失的静态资源直接 404,不能回落成 index.html,否则浏览器会把 HTML 当脚本执行。
+ if path.startswith("assets/"):
+ raise HTTPException(status_code=404, detail="资源不存在")
+
if index_file.exists():
- return FileResponse(str(index_file))
+ return _render_index(index_file, forwarded_prefix)
return JSONResponse(status_code=503, content={"detail": "前端入口文件不存在"})
+def _render_index(index_file: Path, forwarded_prefix: str) -> HTMLResponse:
+ prefix = forwarded_prefix.strip()
+ href = f"{prefix}/" if FORWARDED_PREFIX_PATTERN.match(prefix) else "/"
+ tag = f''
+ html = index_file.read_text(encoding="utf-8")
+ if BASE_TAG_PATTERN.search(html):
+ html = BASE_TAG_PATTERN.sub(tag, html, count=1)
+ else:
+ html = html.replace("
", f"\n {tag}", 1)
+ return HTMLResponse(html, headers={"Cache-Control": "no-store", "Vary": "X-Forwarded-Prefix"})
+
+
def _safe_file(root: Path, path: str) -> Path | None:
if not path:
return None
diff --git a/app/services/auto_scheduler.py b/app/services/auto_scheduler.py
index a0be2db..4f63757 100644
--- a/app/services/auto_scheduler.py
+++ b/app/services/auto_scheduler.py
@@ -11,7 +11,6 @@ from fastapi import HTTPException
from app import state
from app.config import CACHE_DIR, AutoSchedulerConfig
-from app.services.platform import make_source_downloader
from app.services.remote_download import RemoteDataDownloader, RemoteFileInfo
from app.utils.file_dates import parse_file_date_range, required_week_days
@@ -190,7 +189,7 @@ class AutoScheduler:
return self._trigger_processing(target_dates, ready_flag, manual)
target_days = required_week_days(scheduler.week_offset)
- downloader = make_source_downloader(app_config)
+ downloader = RemoteDataDownloader(app_config.remote_data)
data_mappings = app_config.data_mappings.normalized()
auto_directories = {
item["path"]
diff --git a/app/services/csv_processor.py b/app/services/csv_processor.py
deleted file mode 100644
index ee80e42..0000000
--- a/app/services/csv_processor.py
+++ /dev/null
@@ -1,412 +0,0 @@
-"""纯数据处理流水线(容器版,无数据库代码)。
-
-输入:包含已下载周 ZIP/CSV/Excel 的工作目录。
-输出:每张暂存表一个规范化 CSV({表名: csv 路径});由平台数据库导入 API 建表入库,
- 再由平台 run-script 跑报表 SQL 生成结果表。这里不含任何数据库/LOAD DATA 代码。
-"""
-from __future__ import annotations
-
-import shutil
-import zipfile
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from pathlib import Path
-from typing import Callable
-
-import chardet
-import pandas as pd
-
-from app.utils.file_dates import select_recent_items_by_directory
-
-ZERO_TEXTS = {"", "-", "--", "—", "–", "NA", "N/A", "NULL", "NONE", "NAN", "\\N"}
-DATETIME_FORMATS = [
- "ISO8601",
- "%Y-%m-%d %H:%M:%S",
- "%Y-%m-%d %H:%M",
- "%Y/%m/%d %H:%M:%S",
- "%Y/%m/%d %H:%M",
- "%Y-%m-%d",
- "%Y/%m/%d",
- "%Y年%m月%d日 %H:%M:%S",
- "%Y年%m月%d日",
- "%Y%m%d%H%M%S",
- "%Y%m%d",
-]
-MAX_WORKERS = 8
-
-
-class CsvProcessor:
- def __init__(self, work_dir: Path, config: dict, log: Callable[[str], None]):
- self.work_dir = Path(work_dir)
- self.config = config
- self.log = log
- self.recent_days = int(config.get("recent_days", 7))
- self.sheet_filter = set(config.get("sheet_filter", []))
- self.directories = _build_directory_mappings(config.get("directories") or [])
- self.field_map, self.type_map = _build_global_map(config.get("extract_fields", []))
- self.table_maps = _build_table_maps(config.get("table_field_mappings") or {})
- self.out_dir = self.work_dir / ".out"
-
- def process(self) -> dict[str, Path]:
- self._unzip_files()
- self._excel_to_csv()
- return self._build_table_csvs()
-
- # --- step 1: unzip ---------------------------------------------------
- def _unzip_files(self) -> None:
- zips = self._filter_recent(list(self.work_dir.rglob("*.zip")), "ZIP")
- self.log(f"解压 ZIP: {len(zips)} 个")
- for zip_file in zips:
- try:
- _extract_zip(zip_file, self.log)
- except Exception as exc: # noqa: BLE001 - keep going on a bad archive
- self.log(f"[WARN] 解压失败 {zip_file.name}: {exc}")
-
- # --- step 2: excel -> csv -------------------------------------------
- def _excel_to_csv(self) -> None:
- excels = self._filter_recent(list(self._scan(self.work_dir, (".xlsx", ".xls"))), "Excel")
- if not excels:
- return
- self.log(f"Excel 转 CSV: {len(excels)} 个文件")
- with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
- futures = {pool.submit(self._one_excel, f): f for f in excels}
- for future in as_completed(futures):
- excel = futures[future]
- try:
- future.result()
- except Exception as exc: # noqa: BLE001
- self.log(f"[WARN] Excel 处理失败 {excel.name}: {exc}")
-
- def _one_excel(self, excel_file: Path) -> None:
- xl = pd.ExcelFile(excel_file, engine="openpyxl")
- try:
- for sheet in xl.sheet_names:
- if sheet in self.sheet_filter:
- continue
- out = excel_file.parent / f"{excel_file.stem}_{sheet}.csv"
- xl.parse(sheet).to_csv(out, index=False, encoding="utf-8")
- finally:
- xl.close()
-
- # --- step 3: build one normalized CSV per staging table -------------
- def _build_table_csvs(self) -> dict[str, Path]:
- data_dirs = self._find_data_dirs()
- if not data_dirs:
- self.log("[WARN] 未找到任何数据目录")
- return {}
- self.out_dir.mkdir(parents=True, exist_ok=True)
- result: dict[str, Path] = {}
- for table, directories in data_dirs.items():
- csv_files: list[Path] = []
- for directory in directories:
- csv_files.extend(self._filter_recent(list(self._scan(directory, (".csv",))), "CSV", root=directory))
- if not csv_files:
- continue
- field_map, type_map = self._maps_for_table(table)
- out_path = self.out_dir / f"{table}.csv"
- rows = self._write_table_csv(table, csv_files, field_map, type_map, out_path)
- if rows > 0:
- result[table] = out_path
- self.log(f"暂存表 {table}: {rows} 行 -> {out_path.name}")
- return result
-
- def _write_table_csv(self, table, csv_files, field_map, type_map, out_path: Path) -> int:
- # First pass: union of target columns across this table's CSV files.
- union: list[str] = []
- seen: set[str] = set()
- frames: list[tuple[Path, list[str]]] = []
- for csv_file in csv_files:
- headers = _read_headers(csv_file)
- targets = _ordered_targets(headers, field_map)
- if not targets:
- continue
- frames.append((csv_file, headers))
- for target in targets:
- if target not in seen:
- seen.add(target)
- union.append(target)
- if not union:
- return 0
-
- total = 0
- header_written = False
- for csv_file, _headers in frames:
- df = self._normalize(csv_file, field_map, type_map, union)
- if df is None or df.empty:
- continue
- df.to_csv(out_path, index=False, header=not header_written, mode="w" if not header_written else "a", encoding="utf-8")
- header_written = True
- total += len(df)
- return total
-
- def _normalize(self, csv_file: Path, field_map, type_map, union: list[str]):
- try:
- df = pd.read_csv(
- csv_file,
- encoding=_detect_encoding(csv_file),
- dtype=str,
- na_values=[""],
- keep_default_na=False,
- low_memory=True,
- )
- except Exception as exc: # noqa: BLE001
- self.log(f"[WARN] 读取 CSV 失败 {csv_file.name}: {exc}")
- return None
-
- col_map: dict[str, str] = {}
- mapped: set[str] = set()
- for col in df.columns:
- target = field_map.get(col)
- if target and target not in mapped:
- col_map[col] = target
- mapped.add(target)
- if not col_map:
- return None
-
- out = df[list(col_map.keys())].copy()
- out.columns = list(col_map.values())
- out = out.fillna("")
- for col in out.columns:
- col_type = type_map.get(col, "string")
- if col_type == "datetime":
- out[col] = _convert_datetime(out[col])
- elif col_type == "int":
- out[col] = _convert_int(out[col])
- elif col_type == "float":
- out[col] = _convert_float(out[col])
- else:
- out[col] = out[col].astype("string").str.replace("%", "", regex=False).str.slice(0, 255)
- # Reindex to the shared union columns; fill missing per type so numeric
- # staging columns never carry '' (the report SQL re-types them later).
- for col in union:
- if col not in out.columns:
- out[col] = "0" if type_map.get(col) in ("int", "float") else ""
- return out[union]
-
- # --- directory detection --------------------------------------------
- def _find_data_dirs(self) -> dict[str, list[Path]]:
- data_dirs: dict[str, list[Path]] = {}
- for item in self.directories:
- directory = self.work_dir / item["path"]
- if directory.exists() and directory.is_dir():
- _add_data_dir(data_dirs, item["table"], directory)
- return data_dirs
-
- def _maps_for_table(self, table: str):
- if table in self.table_maps:
- return self.table_maps[table]
- return self.field_map, self.type_map
-
- # --- helpers ---------------------------------------------------------
- def _scan(self, directory: Path, extensions: tuple[str, ...]):
- for ext in extensions:
- yield from directory.rglob(f"*{ext}")
-
- def _filter_recent(self, files: list[Path], label: str, root: Path | None = None) -> list[Path]:
- if not files:
- return files
- base = (root or self.work_dir).resolve()
-
- def parent_key(file_path: Path) -> str:
- try:
- parent = file_path.parent.resolve().relative_to(base)
- except ValueError:
- parent = file_path.parent
- text = str(parent).replace("\\", "/")
- return "" if text == "." else text
-
- selected, summaries = select_recent_items_by_directory(
- files,
- parent_key=parent_key,
- name_key=lambda f: f.name,
- days=self.recent_days,
- )
- for summary in summaries:
- if summary.skipped_count and summary.start_date and summary.max_date:
- self.log(
- f"{label} {summary.directory or '.'}: 取 {summary.start_date}~{summary.max_date} "
- f"{summary.selected_count}/{summary.total_count},跳过 {summary.skipped_count} 个旧文件"
- )
- return sorted(selected)
-
-
-def _build_global_map(extract_fields: list[dict]) -> tuple[dict[str, str], dict[str, str]]:
- field_map: dict[str, str] = {}
- type_map: dict[str, str] = {}
- for field in extract_fields:
- target = field.get("Field")
- if not target:
- continue
- type_map[target] = field.get("Type", "string")
- for source in field.get("Extract", []):
- field_map[source] = target
- return field_map, type_map
-
-
-def _build_directory_mappings(items: list[dict]) -> list[dict[str, str]]:
- mappings: list[dict[str, str]] = []
- seen: set[tuple[str, str]] = set()
- for item in items:
- if not isinstance(item, dict):
- continue
- path = str(item.get("path", "")).replace("\\", "/").strip().strip("/")
- table = str(item.get("table", "")).strip()
- if not path or not table:
- continue
- key = (path, table)
- if key in seen:
- continue
- seen.add(key)
- mappings.append({"path": path, "table": table})
- return mappings
-
-
-def _add_data_dir(data_dirs: dict[str, list[Path]], table: str, directory: Path) -> None:
- existing = data_dirs.setdefault(table, [])
- resolved = directory.resolve()
- if all(path.resolve() != resolved for path in existing):
- existing.append(directory)
-
-
-def _build_table_maps(table_field_mappings: dict) -> dict[str, tuple[dict[str, str], dict[str, str]]]:
- maps: dict[str, tuple[dict[str, str], dict[str, str]]] = {}
- for table, fields in table_field_mappings.items():
- field_map: dict[str, str] = {}
- type_map: dict[str, str] = {}
- for field in fields:
- source = field.get("Source")
- target = field.get("Target")
- if source and target:
- field_map[source] = target
- type_map[target] = field.get("Type", "string")
- maps[table] = (field_map, type_map)
- return maps
-
-
-def _ordered_targets(headers: list[str], field_map: dict[str, str]) -> list[str]:
- targets: list[str] = []
- seen: set[str] = set()
- for col in headers:
- target = field_map.get(col)
- if target and target not in seen:
- seen.add(target)
- targets.append(target)
- return targets
-
-
-def _read_headers(csv_file: Path) -> list[str]:
- try:
- df = pd.read_csv(csv_file, encoding=_detect_encoding(csv_file), nrows=0, dtype=str)
- return list(df.columns)
- except Exception: # noqa: BLE001
- return []
-
-
-def _detect_encoding(file_path: Path) -> str:
- with open(file_path, "rb") as handle:
- result = chardet.detect(handle.read(8192))
- encoding = (result.get("encoding") or "utf-8").lower()
- if "utf" in encoding:
- return "utf-8"
- if "gb" in encoding:
- return "gbk"
- return "utf-8"
-
-
-def _extract_zip(zip_file: Path, log: Callable[[str], None]) -> None:
- for enc in ("utf-8", "gbk", "cp437"):
- try:
- with zipfile.ZipFile(zip_file, "r", metadata_encoding=enc) as zf:
- _extract_members(zf, zip_file.parent, log)
- return
- except (UnicodeDecodeError, zipfile.BadZipFile):
- continue
- raise RuntimeError("无法解压(编码检测失败)")
-
-
-def _extract_members(zf: zipfile.ZipFile, target_dir: Path, log: Callable[[str], None]) -> None:
- root = target_dir.resolve()
- for member in zf.infolist():
- name = member.filename.replace("\\", "/")
- target = (root / name).resolve()
- try:
- target.relative_to(root)
- except ValueError:
- log(f"[WARN] 跳过不安全的 ZIP 条目: {member.filename}")
- continue
- if member.is_dir():
- target.mkdir(parents=True, exist_ok=True)
- continue
- target.parent.mkdir(parents=True, exist_ok=True)
- with zf.open(member) as source, target.open("wb") as out:
- shutil.copyfileobj(source, out)
-
-
-def _clean_numeric_text(series: pd.Series) -> pd.Series:
- return (
- series.str.strip()
- .str.replace(",", "", regex=False)
- .str.replace(",", "", regex=False)
- .str.replace("%", "", regex=False)
- .str.replace("%", "", regex=False)
- .str.replace("\t", "", regex=False)
- .str.replace(" ", "", regex=False)
- )
-
-
-def _numeric_series(series: pd.Series) -> pd.Series:
- text = series.astype("string")
- has_percent = text.str.contains(r"[%%]", regex=True, na=False)
- cleaned = _clean_numeric_text(text)
- zero_mask = cleaned.isna() | cleaned.str.upper().isin(ZERO_TEXTS)
- numeric = pd.to_numeric(cleaned.mask(zero_mask, "0"), errors="coerce").fillna(0)
- numeric[has_percent & numeric.notna()] = numeric[has_percent & numeric.notna()] / 100
- return numeric
-
-
-def _convert_int(series: pd.Series) -> pd.Series:
- try:
- rounded = _numeric_series(series).round()
- return pd.Series([int(v) for v in rounded], index=series.index, dtype=object)
- except Exception: # noqa: BLE001
- return series
-
-
-def _convert_float(series: pd.Series) -> pd.Series:
- try:
- numeric = _numeric_series(series)
- return pd.Series([float(v) for v in numeric], index=series.index, dtype=object)
- except Exception: # noqa: BLE001
- return series
-
-
-def _convert_datetime(series: pd.Series) -> pd.Series:
- try:
- valid = series.notna() & (series != "") & (series.astype(str).str.strip() != "")
- if not valid.any():
- return pd.Series([None] * len(series), index=series.index)
- parsed = pd.Series([pd.NaT] * len(series), index=series.index)
- remaining = valid.copy()
- for fmt in DATETIME_FORMATS:
- if not remaining.any():
- break
- try:
- temp = pd.to_datetime(series[remaining], errors="coerce", format=fmt)
- except Exception: # noqa: BLE001
- continue
- ok = temp.notna()
- if ok.any():
- idx = remaining[remaining].index[ok]
- parsed.loc[idx] = temp[ok].values
- remaining.loc[idx] = False
- if remaining.any():
- try:
- temp = pd.to_datetime(series[remaining], errors="coerce", format="mixed", dayfirst=False)
- ok = temp.notna()
- if ok.any():
- idx = remaining[remaining].index[ok]
- parsed.loc[idx] = temp[ok].values
- except Exception: # noqa: BLE001
- pass
- return parsed.dt.strftime("%Y-%m-%d %H:%M:%S")
- except Exception: # noqa: BLE001
- return series
diff --git a/app/services/license.py b/app/services/license.py
deleted file mode 100644
index 6bf2b96..0000000
--- a/app/services/license.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""本地授权期限校验。"""
-import base64
-import hashlib
-import hmac
-import json
-import re
-from dataclasses import dataclass
-from datetime import date, datetime, timedelta
-from pathlib import Path
-from typing import Any
-
-from app.config import BASE_DIR
-
-
-DEFAULT_EXPIRES_ON = date(2026, 12, 30)
-EXTEND_DAYS = 30
-LICENSE_FILE = BASE_DIR / "license.dat"
-_SECRET = b"CapacityReport local license v1"
-_ZIP_DATE_RE = re.compile(r"(? dict[str, Any]:
- return {"code": self.code, "message": str(self)}
-
-
-class LicenseExpiredError(LicenseError):
- """数据日期超过授权到期日期。"""
-
- code = "LICENSE_EXPIRED"
-
- def __init__(self, expires_on: date, current_date: date):
- self.expires_on = expires_on
- self.current_date = current_date
- super().__init__(
- f"授权已过期:数据日期 {current_date.isoformat()} 已超过到期日期 {expires_on.isoformat()}"
- )
-
- def to_detail(self) -> dict[str, Any]:
- return {
- "code": self.code,
- "message": str(self),
- "expires_on": self.expires_on.isoformat(),
- "current_date": self.current_date.isoformat(),
- "key_label": format_key_label(self.expires_on),
- }
-
-
-class InvalidActivationCodeError(LicenseError):
- """激活码错误。"""
-
- code = "LICENSE_INVALID"
-
- def __init__(self, expires_on: date):
- self.expires_on = expires_on
- super().__init__("激活码无效,请按当前 key 重新计算后输入")
-
- def to_detail(self) -> dict[str, Any]:
- return {
- "code": self.code,
- "message": str(self),
- "expires_on": self.expires_on.isoformat(),
- "key_label": format_key_label(self.expires_on),
- }
-
-
-@dataclass(frozen=True)
-class LicenseInfo:
- expires_on: date
- current_date: date | None = None
- zip_count: int = 0
-
- @property
- def key_label(self) -> str:
- return format_key_label(self.expires_on)
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "expires_on": self.expires_on.isoformat(),
- "key_label": self.key_label,
- "current_date": self.current_date.isoformat() if self.current_date else None,
- "zip_count": self.zip_count,
- }
-
-
-def get_license_info() -> LicenseInfo:
- return LicenseInfo(expires_on=read_expires_on())
-
-
-def activate(code: str) -> LicenseInfo:
- expires_on = read_expires_on()
- expected = activation_hash(expires_on)
- normalized_code = (code or "").strip().lower()
- if not hmac.compare_digest(normalized_code, expected):
- raise InvalidActivationCodeError(expires_on)
-
- new_expires_on = expires_on + timedelta(days=EXTEND_DAYS)
- write_expires_on(new_expires_on)
- return LicenseInfo(expires_on=new_expires_on)
-
-
-def check_processing_allowed(work_dir: Path) -> LicenseInfo:
- expires_on = read_expires_on()
- zip_count, current_date = extract_max_zip_date(work_dir)
- info = LicenseInfo(expires_on=expires_on, current_date=current_date, zip_count=zip_count)
-
- if current_date and current_date > expires_on:
- raise LicenseExpiredError(expires_on, current_date)
-
- return info
-
-
-def extract_max_zip_date(work_dir: Path) -> tuple[int, date | None]:
- max_date: date | None = None
- zip_count = 0
- for zip_file in work_dir.rglob("*.zip"):
- zip_count += 1
- for raw_value in _ZIP_DATE_RE.findall(zip_file.name):
- parsed_date = _parse_zip_timestamp(raw_value)
- if parsed_date and (max_date is None or parsed_date > max_date):
- max_date = parsed_date
-
- return zip_count, max_date
-
-
-def activation_hash(expires_on: date) -> str:
- return hashlib.sha256(format_key_label(expires_on).encode("utf-8")).hexdigest()
-
-
-def format_key_label(value: date) -> str:
- return value.strftime("%Y/%m/%d")
-
-
-def read_expires_on() -> date:
- if not LICENSE_FILE.exists():
- write_expires_on(DEFAULT_EXPIRES_ON)
- return DEFAULT_EXPIRES_ON
-
- try:
- encrypted = base64.urlsafe_b64decode(LICENSE_FILE.read_text(encoding="utf-8").encode("ascii"))
- raw = _xor_bytes(encrypted)
- data = json.loads(raw.decode("utf-8"))
- payload = data["payload"]
- signature = data["signature"]
- payload_raw = _dump_json(payload)
- expected_signature = hmac.new(_SECRET, payload_raw, hashlib.sha256).hexdigest()
- if not hmac.compare_digest(signature, expected_signature):
- raise ValueError("signature mismatch")
-
- return date.fromisoformat(str(payload["expires_on"]))
- except Exception:
- write_expires_on(DEFAULT_EXPIRES_ON)
- return DEFAULT_EXPIRES_ON
-
-
-def write_expires_on(expires_on: date) -> None:
- payload = {"expires_on": expires_on.isoformat()}
- payload_raw = _dump_json(payload)
- data = {
- "payload": payload,
- "signature": hmac.new(_SECRET, payload_raw, hashlib.sha256).hexdigest(),
- }
- encrypted = _xor_bytes(_dump_json(data))
- LICENSE_FILE.write_text(base64.urlsafe_b64encode(encrypted).decode("ascii"), encoding="utf-8")
-
-
-def _parse_zip_timestamp(value: str) -> date | None:
- fmt = "%Y%m%d%H%M%S" if len(value) == 14 else "%Y%m%d%H%M"
- try:
- return datetime.strptime(value, fmt).date()
- except ValueError:
- return None
-
-
-def _dump_json(data: dict[str, Any]) -> bytes:
- return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
-
-
-def _xor_bytes(data: bytes) -> bytes:
- output = bytearray()
- counter = 0
- while len(output) < len(data):
- block = hashlib.sha256(_SECRET + counter.to_bytes(4, "big")).digest()
- output.extend(block)
- counter += 1
- return bytes(value ^ key for value, key in zip(data, output))
diff --git a/app/services/pipeline.py b/app/services/pipeline.py
deleted file mode 100644
index 1aee6e4..0000000
--- a/app/services/pipeline.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Metrix 仓库模式的处理流水线:CSV 处理 → 平台导入暂存表 → run-script(single_session) 跑报表 SQL。
-
-仅当 warehouse_type == "metrix" 时使用;直连 MySQL 模式走原版 DataProcessor。
-"""
-from __future__ import annotations
-
-from pathlib import Path
-
-from app.config import SQL_SCRIPT, AppConfig, MetrixConfig
-from app.processor import ProcessLogger
-from app.services.csv_processor import CsvProcessor
-from app.services.platform import make_client
-
-RESULT_TABLES = ["4G_结果表", "5G_结果表"]
-
-
-def validate_metrix(metrix: MetrixConfig) -> None:
- missing = []
- if not metrix.base_url:
- missing.append("平台地址")
- if not metrix.token:
- missing.append("API Token")
- if not metrix.database_conn_id:
- missing.append("数据库连接 ID")
- if missing:
- raise RuntimeError("Metrix 连接配置不完整: " + ", ".join(missing))
-
-
-def build_processor_config(app_config: AppConfig) -> dict:
- metrix = app_config.metrix.normalized()
- mappings = app_config.data_mappings.normalized()
- return {
- "recent_days": metrix.recent_days,
- "sheet_filter": list(app_config.sheet_filter),
- "directories": list(mappings.directories),
- "extract_fields": app_config.extract_fields,
- "table_field_mappings": mappings.table_field_mappings,
- }
-
-
-def read_report_sql() -> str:
- if not SQL_SCRIPT.exists():
- return ""
- return SQL_SCRIPT.read_text(encoding="utf-8").strip()
-
-
-def run_report_sql(app_config: AppConfig, logger: ProcessLogger) -> list[dict]:
- metrix = app_config.metrix.normalized()
- validate_metrix(metrix)
- report_sql = read_report_sql()
- if not report_sql:
- raise RuntimeError("报表 SQL(ReportScript.sql)为空或不存在")
- client = make_client(metrix)
- logger.info("执行报表 SQL(single_session)...")
- result = client.run_script(
- metrix.database_conn_id,
- content=report_sql,
- database=metrix.target_database,
- single_session=True,
- run_timeout=7200,
- )
- statements = result.get("results", [])
- failed = [item for item in statements if not item.get("ok")]
- if result.get("stopped") or failed:
- for item in failed[:5]:
- logger.error(f"[SQL] 第 {item.get('index')} 条失败: {item.get('message')}")
- raise RuntimeError("报表 SQL 执行失败")
- logger.success(f"报表 SQL 执行完成,共 {len(statements)} 条语句")
- return statements
-
-
-def run_import_and_report(work_dir: Path, app_config: AppConfig, logger: ProcessLogger) -> dict:
- """处理工作目录数据 → 平台导入暂存表 → 跑报表 SQL。失败抛 RuntimeError。"""
- metrix = app_config.metrix.normalized()
- validate_metrix(metrix)
-
- logger.set_stage("converting")
- tables = CsvProcessor(work_dir, build_processor_config(app_config), logger.info).process()
- if not tables:
- raise RuntimeError("处理后没有产出任何暂存表数据")
-
- client = make_client(metrix)
- conn_id = metrix.database_conn_id
- target_db = metrix.target_database
-
- # 导入前 DROP 旧暂存表,让自动建表按当周实际列重建。
- logger.set_stage("importing")
- drop_sql = "".join(f"DROP TABLE IF EXISTS `{table}`;\n" for table in tables)
- drop_result = client.run_script(conn_id, content=drop_sql, database=target_db, run_timeout=600)
- if drop_result.get("stopped"):
- raise RuntimeError("清理旧暂存表失败")
-
- for table, csv_path in tables.items():
- logger.info(f"导入暂存表 {table} ...")
- job_id = client.import_csv(conn_id, table, csv_path, mode="overwrite", database=target_db, create_table=True)
- job = client.wait_job(job_id)
- if job.get("status") != "success":
- raise RuntimeError(f"暂存表 {table} 导入失败: {job.get('error_code') or job.get('status')}")
- logger.success(f"暂存表 {table} 导入完成")
-
- logger.set_stage("scripting")
- statements = run_report_sql(app_config, logger)
- return {"tables": list(tables.keys()), "statements": len(statements)}
diff --git a/app/services/platform.py b/app/services/platform.py
deleted file mode 100644
index 48e7d60..0000000
--- a/app/services/platform.py
+++ /dev/null
@@ -1,312 +0,0 @@
-"""Metrix 平台集成:API 客户端 + 储存下载器。
-
-当 source_type/warehouse_type 选 "metrix" 时,源数据走平台储存模块、数据仓库走平台数据库模块。
-连接信息(地址/token/storage_id/database_conn_id/target_database)来自 Configure.json 的 Metrix 段。
-储存下载器与 RemoteDataDownloader 接口一致,可被源工厂直接替换。
-"""
-from __future__ import annotations
-
-import time
-from datetime import date
-from pathlib import Path
-from typing import Iterable
-
-import requests
-
-from app.config import AppConfig, MetrixConfig
-from app.services.remote_download import RemoteDownloadResult, RemoteFileInfo
-from app.utils.file_dates import parse_file_date_range, select_recent_items_by_directory
-
-
-class PlatformClient:
- """平台储存 + 数据库模块的最小 API 封装(Bearer Token 鉴权)。"""
-
- def __init__(self, base_url: str, token: str, timeout: int = 60):
- if not base_url:
- raise ValueError("缺少平台地址,请在系统设置的 Metrix 连接中填写")
- if not token:
- raise ValueError("缺少平台 API Token,请在系统设置的 Metrix 连接中填写")
- self.base = base_url.rstrip("/")
- self.timeout = timeout
- self.session = requests.Session()
- self.session.headers["Authorization"] = f"Bearer {token}"
-
- # --- 储存模块 --------------------------------------------------------
- def list_storage_files(self, storage_id: str, path: str = "/", recursive: bool = True) -> list[dict]:
- resp = self.session.get(
- f"{self.base}/api/storages/{storage_id}/files",
- params={"path": path, "recursive": "true" if recursive else "false"},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- return resp.json().get("entries", [])
-
- def download_storage_file(self, storage_id: str, path: str, dest: Path) -> None:
- dest.parent.mkdir(parents=True, exist_ok=True)
- with self.session.get(
- f"{self.base}/api/storages/{storage_id}/download",
- params={"path": path},
- stream=True,
- timeout=self.timeout,
- ) as resp:
- resp.raise_for_status()
- with dest.open("wb") as handle:
- for chunk in resp.iter_content(chunk_size=1024 * 64):
- if chunk:
- handle.write(chunk)
-
- def batch_delete_storage(self, storage_id: str, paths: list[str]) -> int:
- deleted = 0
- for start in range(0, len(paths), 100):
- chunk = [p for p in paths[start:start + 100] if p]
- if not chunk:
- continue
- resp = self.session.post(
- f"{self.base}/api/storages/{storage_id}/batch-delete",
- json={"paths": chunk},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- deleted += len(chunk)
- return deleted
-
- # --- 数据库模块 ------------------------------------------------------
- def import_csv(self, conn_id: str, table: str, csv_path: Path, mode: str = "overwrite",
- database: str = "", create_table: bool = True, upload_timeout: int = 1800) -> str:
- with csv_path.open("rb") as handle:
- resp = self.session.post(
- f"{self.base}/api/databases/{conn_id}/import",
- files={"file": (csv_path.name, handle, "text/csv")},
- data={
- "format": "csv",
- "target_table": table,
- "mode": mode,
- "database": database,
- "mapping": "{}",
- "create_table": "true" if create_table else "false",
- },
- timeout=upload_timeout,
- )
- resp.raise_for_status()
- return resp.json()["job_id"]
-
- def wait_job(self, job_id: str, interval: int = 2, max_wait: int = 7200) -> dict:
- deadline = time.time() + max_wait
- while time.time() < deadline:
- resp = self.session.get(
- f"{self.base}/api/database-transfer-jobs/{job_id}", timeout=self.timeout
- )
- resp.raise_for_status()
- job = resp.json()
- if job.get("status") in ("success", "failed"):
- return job
- time.sleep(interval)
- raise TimeoutError(f"导入任务 {job_id} 超过 {max_wait}s 仍未完成")
-
- def run_script(self, conn_id: str, content: str = "",
- database: str = "", single_session: bool = False, run_timeout: int = 7200) -> dict:
- # 始终按传入的 SQL 文本执行(来自本地 ReportScript.sql),不走 Metrix 库内脚本(script_id)那条路。
- body: dict = {"content": content, "database": database, "stop_on_error": True, "single_session": single_session}
- resp = self.session.post(
- f"{self.base}/api/databases/{conn_id}/run-script",
- json=body,
- timeout=run_timeout,
- )
- resp.raise_for_status()
- return resp.json()
-
- # --- 数据库读 / 导出(供仓库代理使用)-------------------------------
- def list_tables(self, conn_id: str, database: str = "") -> list[str]:
- resp = self.session.get(
- f"{self.base}/api/databases/{conn_id}/tables",
- params={"database": database},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- return [str(item.get("name")) for item in resp.json() if item.get("name")]
-
- def table_columns(self, conn_id: str, table: str, database: str = "") -> list[dict]:
- resp = self.session.get(
- f"{self.base}/api/databases/{conn_id}/tables/{table}",
- params={"database": database},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- return resp.json().get("columns", [])
-
- def table_data(self, conn_id: str, table: str, database: str = "", page: int = 1, page_size: int = 50,
- order_by: str = "", order_dir: str = "asc") -> dict:
- params = {"database": database, "table": table, "page": page, "page_size": page_size}
- if order_by:
- params["order_by"] = order_by
- params["order_dir"] = "desc" if str(order_dir).lower().startswith("desc") else "asc"
- resp = self.session.get(
- f"{self.base}/api/databases/{conn_id}/table-data", params=params, timeout=self.timeout
- )
- resp.raise_for_status()
- return resp.json()
-
- def submit_export(self, conn_id: str, tables: list[str], fmt: str, database: str = "") -> str:
- resp = self.session.post(
- f"{self.base}/api/databases/{conn_id}/export",
- json={"format": fmt, "database": database, "tables": tables},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- return resp.json()["job_id"]
-
- def download_job_file(self, job_id: str, dest: Path) -> None:
- dest.parent.mkdir(parents=True, exist_ok=True)
- with self.session.get(
- f"{self.base}/api/database-transfer-jobs/{job_id}/download", stream=True, timeout=self.timeout
- ) as resp:
- resp.raise_for_status()
- with dest.open("wb") as handle:
- for chunk in resp.iter_content(chunk_size=1024 * 64):
- if chunk:
- handle.write(chunk)
-
-
-def make_client(metrix: MetrixConfig) -> PlatformClient:
- metrix = metrix.normalized()
- return PlatformClient(metrix.base_url, metrix.token)
-
-
-def make_source_downloader(app_config: AppConfig, logger=None):
- """Return a file-source downloader matching app_config.source_type. FTP/SFTP use the
- original RemoteDataDownloader; 'metrix' uses PlatformStorageDownloader. Both share the
- interface test_connection / list_remote_zip_files / download_to / delete_source_files."""
- if app_config.source_type == "metrix":
- return PlatformStorageDownloader(app_config, logger)
- from app.services.remote_download import RemoteDataDownloader
-
- return RemoteDataDownloader(app_config.remote_data, logger)
-
-
-class PlatformStorageDownloader:
- """平台储存版下载器,接口与 RemoteDataDownloader 对齐,可被源工厂直接替换。"""
-
- def __init__(self, app_config: AppConfig, logger=None):
- self.metrix = app_config.metrix.normalized()
- self.remote_dir = (app_config.remote_data.remote_dir or "/").strip() or "/"
- self.logger = logger
- self.client = make_client(self.metrix)
-
- def _log(self, message: str) -> None:
- if self.logger:
- self.logger(message)
-
- def test_connection(self) -> None:
- if not self.metrix.storage_id:
- raise ValueError("缺少储存连接 ID,请在系统设置的 Metrix 连接中填写")
- self.client.list_storage_files(self.metrix.storage_id, self.remote_dir, recursive=False)
-
- def list_remote_zip_files(self, directory: str | None = None) -> list[RemoteFileInfo]:
- path = self._join(self.remote_dir, directory.strip("/")) if directory else self.remote_dir
- entries = self.client.list_storage_files(self.metrix.storage_id, path, recursive=True)
- files: list[RemoteFileInfo] = []
- for entry in entries:
- if entry.get("is_dir"):
- continue
- name = str(entry.get("name", ""))
- if not name.lower().endswith(".zip"):
- continue
- files.append(self._info(str(entry.get("path", "")), int(entry.get("size", 0) or 0)))
- return files
-
- def download_to(self, destination: Path, target_dates: Iterable[date] | None = None) -> RemoteDownloadResult:
- destination = Path(destination)
- destination.mkdir(parents=True, exist_ok=True)
- zip_files = self.list_remote_zip_files()
- date_filter = set(target_dates or [])
-
- if date_filter:
- selected = self._select_by_dates(zip_files, date_filter)
- elif zip_files:
- selected, summaries = select_recent_items_by_directory(
- zip_files,
- parent_key=lambda item: item.parent,
- name_key=lambda item: item.name,
- )
- for summary in summaries:
- if summary.skipped_count and summary.start_date and summary.max_date:
- self._log(
- f"储存目录 {summary.directory or '.'}: 仅下载 "
- f"{summary.start_date.isoformat()} 至 {summary.max_date.isoformat()} 的 "
- f"{summary.selected_count}/{summary.total_count} 个 ZIP,跳过 {summary.skipped_count} 个旧文件"
- )
- else:
- selected = []
-
- result = RemoteDownloadResult()
- for remote_file in selected:
- dest = destination / remote_file.relative_path
- self._log(f"下载: {remote_file.relative_path}")
- self.client.download_storage_file(self.metrix.storage_id, remote_file.path, dest)
- result.file_count += 1
- result.total_bytes += remote_file.size or (dest.stat().st_size if dest.exists() else 0)
- result.remote_files.append(remote_file.path)
- return result
-
- def delete_source_files(self, remote_files: Iterable[str] | None = None) -> int:
- files = [path for path in (remote_files or []) if path]
- if not files:
- return 0
- self._log(f"清理储存源文件,共 {len(files)} 个")
- return self.client.batch_delete_storage(self.metrix.storage_id, files)
-
- # --- helpers ---------------------------------------------------------
- def _select_by_dates(self, zip_files: list[RemoteFileInfo], target_dates: set[date]) -> list[RemoteFileInfo]:
- grouped: dict[str, list[RemoteFileInfo]] = {}
- for remote_file in zip_files:
- grouped.setdefault(remote_file.parent, []).append(remote_file)
-
- selected: list[RemoteFileInfo] = []
- for parent, files in sorted(grouped.items(), key=lambda item: item[0]):
- picked = [
- remote_file
- for remote_file in files
- if (date_range := parse_file_date_range(remote_file.name))
- and (
- date_range.covers_all(target_dates)
- if date_range.span_days > 1
- else date_range.covers_any(target_dates)
- )
- ]
- selected.extend(picked)
- skipped = len(files) - len(picked)
- if skipped:
- self._log(
- f"储存目录 {parent or '.'}: 仅下载目标日期 "
- f"{min(target_dates).isoformat()} 至 {max(target_dates).isoformat()} 的 "
- f"{len(picked)}/{len(files)} 个 ZIP,跳过 {skipped} 个非目标文件"
- )
- return selected
-
- @staticmethod
- def _join(parent: str, child: str) -> str:
- parent = (parent or "").replace("\\", "/").rstrip("/")
- if not parent:
- return child
- if parent == "/":
- return f"/{child}"
- return f"{parent}/{child}"
-
- def _info(self, remote_path: str, size: int = 0) -> RemoteFileInfo:
- normalized_root = self.remote_dir.replace("\\", "/").rstrip("/")
- normalized_path = remote_path.replace("\\", "/")
- if normalized_root and normalized_root != "/" and normalized_path.startswith(f"{normalized_root}/"):
- relative_path = normalized_path[len(normalized_root) + 1:]
- else:
- relative_path = normalized_path.lstrip("/")
- relative = Path(relative_path)
- parent = str(relative.parent).replace("\\", "/")
- if parent == ".":
- parent = ""
- return RemoteFileInfo(
- path=remote_path,
- relative_path=relative_path,
- parent=parent,
- name=relative.name,
- size=size,
- )
diff --git a/app/warehouse.py b/app/warehouse.py
index fa54ae8..fc3034e 100644
--- a/app/warehouse.py
+++ b/app/warehouse.py
@@ -1,229 +1,13 @@
-"""数据仓库抽象:直连 MySQL 或 Metrix 数据库平台。
-
-`make_warehouse(config)` 按 warehouse_type 返回:
-- 直连 MySQL: 原版 `DatabaseManager`(已具备下列方法)。
-- Metrix: `MetrixWarehouse`,用平台数据库 API 实现相同方法,供查看/导出路由透明替换。
-
-两者都提供: test_connection / get_server_info / get_tables / get_table_info /
-query_table / truncate_table / drop_table / drop_all_tables / execute_sql。
-"""
+"""数据仓库入口:容量库与 CellData 库都直连 MySQL。"""
from __future__ import annotations
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple
-
from app.config import AppConfig
from app.database import DatabaseManager
-from app.services.platform import make_client
-def make_warehouse(config: AppConfig):
- if config.warehouse_type == "metrix":
- return MetrixWarehouse(config)
+def make_warehouse(config: AppConfig) -> DatabaseManager:
return DatabaseManager(config)
-def make_cell_data_warehouse(config: AppConfig):
+def make_cell_data_warehouse(config: AppConfig) -> DatabaseManager:
return DatabaseManager(config, config.cell_data.normalized().mysql)
-
-
-def _quote_ident(name: str) -> str:
- return "`" + str(name).replace("`", "``") + "`"
-
-
-def _quote_value(value: str) -> str:
- return "'" + str(value).replace("\\", "\\\\").replace("'", "''") + "'"
-
-
-def _sql_literal(value: Any) -> str:
- return "NULL" if value is None else _quote_value(str(value))
-
-
-class MetrixWarehouse:
- """用 Metrix 数据库 API 实现 DatabaseManager 的只读/管理子集。"""
-
- def __init__(self, config: AppConfig):
- self.metrix = config.metrix.normalized()
- self.conn_id = self.metrix.database_conn_id
- self.database = self.metrix.target_database
- self.client = make_client(self.metrix)
-
- # --- 连接 / 诊断 -----------------------------------------------------
- def test_connection(self) -> Tuple[bool, str]:
- try:
- self.client.list_tables(self.conn_id, self.database)
- return True, "连接成功"
- except Exception as exc: # noqa: BLE001
- return False, str(exc)
-
- def get_server_info(self) -> Dict[str, Any]:
- version = "Metrix"
- try:
- res = self.client.run_script(self.conn_id, content="SELECT VERSION() AS v", database=self.database, run_timeout=30)
- rows = (res.get("results") or [{}])[0].get("rows") or []
- if rows:
- version = str(list(rows[0].values())[0])
- except Exception: # noqa: BLE001
- pass
- return {"version": version, "load_data_infile": True, "load_data_message": "Metrix 平台导入"}
-
- # --- 表 / 数据 -------------------------------------------------------
- def get_tables(self) -> List[str]:
- return self.client.list_tables(self.conn_id, self.database)
-
- def get_table_info(self, table_name: str) -> Dict[str, Any]:
- columns = self.client.table_columns(self.conn_id, table_name, self.database)
- # Map Metrix column shape -> original DESCRIBE-like shape used by the frontend.
- mapped = [
- {
- "Field": col.get("name"),
- "Type": col.get("type", ""),
- "Null": "YES" if col.get("nullable", True) else "NO",
- "Key": "PRI" if col.get("primary_key") else "",
- "Default": col.get("default"),
- "Extra": "auto_increment" if col.get("autoincrement") else "",
- }
- for col in columns
- ]
- data = self.client.table_data(self.conn_id, table_name, self.database, page=1, page_size=1)
- return {"name": table_name, "columns": mapped, "row_count": int(data.get("total") or 0)}
-
- def query_table(
- self,
- table_name: str,
- page: int = 1,
- page_size: int = 50,
- filters: Optional[Dict[str, str]] = None,
- order_by: Optional[str] = None,
- order_dir: str = "ASC",
- ) -> Dict[str, Any]:
- active_filters = {k: v for k, v in (filters or {}).items() if v}
- if active_filters:
- return self._query_with_filters(table_name, page, page_size, active_filters, order_by, order_dir)
- data = self.client.table_data(
- self.conn_id, table_name, self.database, page=page, page_size=page_size,
- order_by=order_by or "", order_dir=order_dir,
- )
- total = int(data.get("total") or 0)
- return {
- "data": data.get("rows", []),
- "total": total,
- "page": page,
- "page_size": page_size,
- "total_pages": (total + page_size - 1) // page_size if page_size else 0,
- }
-
- def _query_with_filters(self, table_name, page, page_size, filters, order_by, order_dir) -> Dict[str, Any]:
- where = " AND ".join(f"{_quote_ident(col)} LIKE {_quote_value('%' + str(val) + '%')}" for col, val in filters.items())
- where_sql = f" WHERE {where}" if where else ""
- table_sql = _quote_ident(table_name)
- total_res = self.client.run_script(
- self.conn_id, content=f"SELECT COUNT(*) AS n FROM {table_sql}{where_sql}",
- database=self.database, run_timeout=120,
- )
- total = int(((total_res.get("results") or [{}])[0].get("rows") or [{}])[0].get("n") or 0)
- order_sql = ""
- if order_by:
- direction = "DESC" if str(order_dir).upper() == "DESC" else "ASC"
- order_sql = f" ORDER BY {_quote_ident(order_by)} {direction}"
- offset = max(page - 1, 0) * page_size
- data_res = self.client.run_script(
- self.conn_id,
- content=f"SELECT * FROM {table_sql}{where_sql}{order_sql} LIMIT {int(page_size)} OFFSET {int(offset)}",
- database=self.database, run_timeout=300,
- )
- rows = (data_res.get("results") or [{}])[0].get("rows") or []
- return {
- "data": rows,
- "total": total,
- "page": page,
- "page_size": page_size,
- "total_pages": (total + page_size - 1) // page_size if page_size else 0,
- }
-
- # --- 管理操作 --------------------------------------------------------
- def truncate_table(self, table_name: str) -> bool:
- self._run(f"TRUNCATE TABLE {_quote_ident(table_name)}")
- return True
-
- def drop_table(self, table_name: str) -> bool:
- self._run(f"DROP TABLE IF EXISTS {_quote_ident(table_name)}")
- return True
-
- def drop_all_tables(self) -> Dict[str, Any]:
- tables = self.get_tables()
- if not tables:
- return {"success": True, "dropped_count": 0, "tables": []}
- drop_sql = "".join(f"DROP TABLE IF EXISTS {_quote_ident(t)};\n" for t in tables)
- self._run(drop_sql)
- return {"success": True, "dropped_count": len(tables), "tables": tables}
-
- def _row_where(self, identifier: Dict[str, Any]) -> str:
- parts = [
- f"{_quote_ident(col)} IS NULL" if val is None else f"{_quote_ident(col)} = {_sql_literal(val)}"
- for col, val in identifier.items()
- ]
- return " AND ".join(parts) if parts else "1 = 0"
-
- def update_row(self, table_name: str, identifier: Dict[str, Any], values: Dict[str, Any]) -> int:
- if not values:
- return 0
- set_clause = ", ".join(f"{_quote_ident(col)} = {_sql_literal(val)}" for col, val in values.items())
- sql = f"UPDATE {_quote_ident(table_name)} SET {set_clause} WHERE {self._row_where(identifier)} LIMIT 1"
- ok, result = self.execute_sql(sql)
- if not ok:
- raise RuntimeError(str(result))
- return int(result.get("affected_rows", 0)) if isinstance(result, dict) else 0
-
- def delete_row(self, table_name: str, identifier: Dict[str, Any]) -> int:
- sql = f"DELETE FROM {_quote_ident(table_name)} WHERE {self._row_where(identifier)} LIMIT 1"
- ok, result = self.execute_sql(sql)
- if not ok:
- raise RuntimeError(str(result))
- return int(result.get("affected_rows", 0)) if isinstance(result, dict) else 0
-
- def import_csv(self, file_path: str, table_name: str, encoding: str | None = None) -> int:
- """走 Metrix 平台导入 API 追加导入到已存在的表(字段映射由平台按列名处理)。"""
- source_path = Path(file_path)
- upload_path = source_path
- converted_path: Path | None = None
- if encoding and encoding.lower() not in {"utf-8", "utf-8-sig"}:
- converted_path = source_path.with_name(f"{source_path.stem}_utf8{source_path.suffix}")
- with source_path.open("r", encoding=encoding, newline="") as source:
- with converted_path.open("w", encoding="utf-8-sig", newline="") as target:
- while chunk := source.read(1024 * 1024):
- target.write(chunk)
- upload_path = converted_path
-
- try:
- job_id = self.client.import_csv(
- self.conn_id, table_name, upload_path, mode="append",
- database=self.database, create_table=False,
- )
- job = self.client.wait_job(job_id)
- if job.get("status") != "success":
- raise RuntimeError(job.get("error_code") or job.get("status") or "导入失败")
- return int(job.get("row_count") or 0)
- finally:
- if converted_path is not None:
- converted_path.unlink(missing_ok=True)
-
- def execute_sql(self, sql: str) -> Tuple[bool, Any]:
- try:
- res = self.client.run_script(self.conn_id, content=sql, database=self.database, run_timeout=600)
- except Exception as exc: # noqa: BLE001
- return False, str(exc)
- if res.get("stopped"):
- failed = [r for r in res.get("results", []) if not r.get("ok")]
- return False, (failed[0].get("message") if failed else "SQL 执行失败")
- results = res.get("results", [])
- last = results[-1] if results else {}
- if last.get("rows"):
- return True, last["rows"]
- return True, {"affected_rows": sum(int(r.get("affected_rows") or 0) for r in results)}
-
- def _run(self, content: str) -> None:
- res = self.client.run_script(self.conn_id, content=content, database=self.database, run_timeout=600)
- if res.get("stopped"):
- failed = [r for r in res.get("results", []) if not r.get("ok")]
- raise RuntimeError(failed[0].get("message") if failed else "SQL 执行失败")
diff --git a/db_init/README.md b/db_init/README.md
index c8663a2..e0a26a5 100644
--- a/db_init/README.md
+++ b/db_init/README.md
@@ -14,8 +14,8 @@ CellData 脚本前,会由 `app/db_init.py` 的 `ensure_required_tables()` 自
- `<库标识>` 决定连到哪个库(**实际库名以用户在「系统设置」里配置的为准,不写死**):
| 库标识 | 对应配置 | 说明 |
|---|---|---|
- | `celldata` | `CellData.MySQL_DBInfo` | CellData 库,始终直连 MySQL |
- | `capacityreport` | `MySQL_DBInfo`(主仓库) | 仅当仓库为「直连 MySQL」时检查;Metrix 模式跳过 |
+ | `celldata` | `CellData.MySQL_DBInfo` | CellData 库 |
+ | `capacityreport` | `MySQL_DBInfo`(主仓库) | 容量主库 |
- `<表名>` 为要检查/创建的表名(区分库标识后剩余部分,表名本身不含 `.`)。
例:`celldata.sector.sql` = 在 CellData 库里确保 `sector` 表存在。
@@ -28,7 +28,7 @@ CellData 脚本前,会由 `app/db_init.py` 的 `ensure_required_tables()` 自
对它的任何增改都会被保留,不会被覆盖或重置。
- 全过程 best-effort:单库连不上 / 单表初始化失败只记日志,不会中断启动或数据处理。
- **建库**:连接前先用不带 database 的连接执行 `CREATE DATABASE IF NOT EXISTS`,故库不存在也能自愈;
- 前提是 MySQL 账号有建库权限(root 默认有)。Metrix 模式下主库走平台 API,不在此建库。
+ 前提是 MySQL 账号有建库权限(root 默认有)。
## 当前清单
diff --git a/docs/project_context.md b/docs/project_context.md
index 4c64db7..187b5a4 100644
--- a/docs/project_context.md
+++ b/docs/project_context.md
@@ -1,5 +1,15 @@
# 项目上下文记录
+## 2026-11-06:托管到 Metrix 应用包,去掉授权与 Metrix 平台模式(分支 feat/metrix-hosting)
+
+- 应用包:新增 `scripts/package_metrix.py`,构建前端与镜像后生成 `dist/metrix/capacityreport--<短哈希>.zip`(`metrix-app.json` + `icon.svg` + `image.tar`)。清单 `slug=capacityreport`、`user_auth=metrix`、`admin_auth=none`、`data_dir=/data`,单个 `web` 服务端口 9081。图标为 `frontend/public/favicon.svg`,同时作为网页 favicon。
+- 托管身份:设置了 `METRIX_APP_PROXY_TOKEN` 即进入托管模式,`app/auth.py::resolve_platform_context` 用 `hmac.compare_digest` 校验 `X-Metrix-Proxy-Token`,再读取 URL 编码的 `X-Metrix-User-Id/Username/Display-Name/App-Role`(角色只认 admin/user)。托管模式下中间件只认平台身份,应用 JWT 无效,`/api/login`、`/api/change-password` 返回 404。新增开放接口 `GET /api/session` 返回 `{hosted, user}`。未设置该变量时鉴权行为不变。
+- 托管路径:`main.py::_render_index` 按 `X-Forwarded-Prefix`(仅 `^/apps/[a-z0-9-]+$`)改写 `index.html` 的 ``,响应带 `Cache-Control: no-store` 和 `Vary: X-Forwarded-Prefix`;`assets/` 下缺失文件直接 404。前端 `vite base: './'`,`src/base.ts` 由 `document.baseURI` 得出 `basePath`,`api/client.ts::apiUrl` 与 `router.ts` 都基于它;`index.html` 自带 `` 供直接访问、开发模式和桌面端使用。
+- 托管界面:`composables/session.ts` 启动时读 `/api/session`,托管时不显示登录页、退出按钮和「修改密码」页,顶栏显示 Metrix 用户名;401 提示改为「访问已失效,请刷新页面后重试」。
+- 去掉授权:删除 `app/services/license.py`、`app/api/routers/license.py`、`scripts/gen_license_code.py`、`LicenseActivationModal.vue` 和连点品牌图标 8 次的入口;处理流程不再有「授权校验」阶段,任务状态不再返回 `error_detail`。品牌图标改为纯展示。
+- 去掉 Metrix 平台数据源/仓库模式:删除 `app/services/platform.py`、`pipeline.py`、`csv_processor.py`、`composables/metrixEnabled.ts`;`warehouse.py` 只剩直连 MySQL;`AppConfig` 删除 `metrix_enabled/source_type/warehouse_type/metrix`,旧 Configure.json 中的 `MetrixEnabled/SourceType/WarehouseType/Metrix` 读取时忽略、下次保存时去掉;删除 `/api/config/metrix-enabled`、`/api/config/backend`、`/api/config/metrix` 和设置页「数据源 / 仓库」标签;`requirements.txt` 去掉 `requests`。
+- 验证:新增 `tests/test_hosted_auth.py`(托管/独立两种鉴权、会话接口、`` 注入),`unittest discover` 19 项通过(3 项真实 MySQL 用例按配置跳过);`npm run build`(含 vue-tsc)通过。
+
## 2026-06-26:新增工具发布平台投稿文档(docs/upload)
- 按工具平台投稿模板新增 `docs/upload/` 三份文档:`工具说明书.docx`、`测试报告.docx`、`工具详细介绍.md`。
diff --git a/frontend/index.html b/frontend/index.html
index f217369..d9545c1 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,8 +1,10 @@
+
+
CapacityReport
@@ -10,4 +12,3 @@
-
diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg
new file mode 100644
index 0000000..8ef9240
--- /dev/null
+++ b/frontend/public/favicon.svg
@@ -0,0 +1,12 @@
+
diff --git a/frontend/src/AppShell.vue b/frontend/src/AppShell.vue
index aec5fb7..043c2ca 100644
--- a/frontend/src/AppShell.vue
+++ b/frontend/src/AppShell.vue
@@ -1,6 +1,6 @@
-
-
+
+
-
- 📊
-
+
📊
CapacityReport
-
+
+
@@ -111,8 +105,6 @@
-
-
-
-
diff --git a/frontend/src/components/SettingsPanel.vue b/frontend/src/components/SettingsPanel.vue
index 179d454..66707fb 100644
--- a/frontend/src/components/SettingsPanel.vue
+++ b/frontend/src/components/SettingsPanel.vue
@@ -4,77 +4,6 @@
-
-
-
-
-
-
-
- 外部储存
- Metrix 储存平台
-
-
-
-
- MySQL
- Metrix 数据库平台
-
-
- 数据源和数据仓库可独立选择;CellData 单独配置。
-
-
-
- 保存类型
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 填写 Metrix 平台连接信息。
-
-
-
- 保存连接
- 测试储存
-
-
-
-
-
-
-
@@ -608,7 +537,7 @@
-
+
@@ -813,14 +742,13 @@ import type {
DataDirectoryMapping,
DataMappingsConfig,
HistoryRetentionConfig,
- MetrixConfig,
RemoteAutoSchedulerConfig,
RemoteDataConfig,
RemoteSchedulerStatus
} from '../types';
import { showDownloadCompleteDialog } from '../composables/downloadFeedback';
-import { metrixEnabled as metrixEnabledRef } from '../composables/metrixEnabled';
import { resetPageHeader, setPageHeader } from '../composables/pageHeader';
+import { session } from '../composables/session';
interface ExtractFieldConfig {
Field: string;
@@ -881,10 +809,6 @@ const savingCellDataMysql = ref(false);
const savingCellDataRemote = ref(false);
const savingCellDataSettings = ref(false);
const validatingCellDataSettings = ref(false);
-const savingBackend = ref(false);
-const savingMetrix = ref(false);
-const sourceType = ref<'external' | 'metrix'>('external');
-const warehouseType = ref<'mysql' | 'metrix'>('mysql');
const savingDirectoryMappings = ref(false);
const savingHistoryRetention = ref(false);
const savingSheetFilter = ref(false);
@@ -969,15 +893,6 @@ const cellDataRegexForm = reactive({
file_time_regex: '(?P\\\\d{14})(?=\\\\.zip$)'
});
-const metrixForm = reactive({
- base_url: 'http://host.docker.internal:8000',
- token: '',
- storage_id: '',
- database_conn_id: '',
- target_database: '',
- recent_days: 7
-});
-
const dataMappingsForm = reactive({
directories: [
{ path: '4G', table: '4G_UD', ready_rule: 'daily' },
@@ -1121,16 +1036,6 @@ async function loadConfig() {
try {
const config = await apiGet('/api/config/full');
configUpdate.value = config.update;
- sourceType.value = (config.source_type === 'metrix' ? 'metrix' : 'external') as 'external' | 'metrix';
- warehouseType.value = config.warehouse_type || 'mysql';
- if (config.metrix) {
- metrixForm.base_url = config.metrix.base_url || '';
- metrixForm.token = config.metrix.token || '';
- metrixForm.storage_id = config.metrix.storage_id || '';
- metrixForm.database_conn_id = config.metrix.database_conn_id || '';
- metrixForm.target_database = config.metrix.target_database || '';
- metrixForm.recent_days = Number(config.metrix.recent_days) || 7;
- }
Object.assign(dataMappingsForm, normalizeDataMappingsConfig(config.data_mappings));
mysqlForm.host = config.mysql.host;
mysqlForm.port = config.mysql.port;
@@ -1178,42 +1083,6 @@ function updateCellDataRemoteProtocol(value: string) {
}
}
-async function saveBackend() {
- savingBackend.value = true;
- try {
- const result = await apiPost('/api/config/backend', {
- source_type: sourceType.value,
- warehouse_type: warehouseType.value
- });
- configUpdate.value = result.update || configUpdate.value;
- message.success(result.message || '后端类型已保存');
- } catch (error) {
- message.error(error instanceof Error ? error.message : '保存后端类型失败');
- } finally {
- savingBackend.value = false;
- }
-}
-
-async function saveMetrix() {
- if (!metrixForm.base_url) {
- message.warning('请填写平台地址');
- return;
- }
- savingMetrix.value = true;
- try {
- const result = await apiPost('/api/config/metrix', {
- ...metrixForm,
- recent_days: Math.max(Number(metrixForm.recent_days) || 7, 1)
- });
- configUpdate.value = result.update || configUpdate.value;
- message.success(result.message || 'Metrix 连接已保存');
- } catch (error) {
- message.error(error instanceof Error ? error.message : '保存 Metrix 连接失败');
- } finally {
- savingMetrix.value = false;
- }
-}
-
async function saveMysql() {
if (!mysqlForm.host || !mysqlForm.user || !mysqlForm.dbname) {
message.warning('请填写完整数据库配置');
diff --git a/frontend/src/composables/metrixEnabled.ts b/frontend/src/composables/metrixEnabled.ts
deleted file mode 100644
index 9934892..0000000
--- a/frontend/src/composables/metrixEnabled.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { ref } from 'vue';
-
-export const metrixEnabled = ref(false);
diff --git a/frontend/src/composables/session.ts b/frontend/src/composables/session.ts
new file mode 100644
index 0000000..190f36e
--- /dev/null
+++ b/frontend/src/composables/session.ts
@@ -0,0 +1,24 @@
+import { reactive } from 'vue';
+
+import { apiGet, setHostedMode } from '../api/client';
+import type { SessionInfo } from '../types';
+
+export const session = reactive({
+ ready: false,
+ hosted: false,
+ userName: ''
+});
+
+export async function loadSession(): Promise {
+ try {
+ const info = await apiGet('/api/session');
+ session.hosted = Boolean(info.hosted);
+ session.userName = info.user?.name || '';
+ } catch {
+ session.hosted = false;
+ session.userName = '';
+ } finally {
+ setHostedMode(session.hosted);
+ session.ready = true;
+ }
+}
diff --git a/frontend/src/router.ts b/frontend/src/router.ts
index 0ba6146..3664127 100644
--- a/frontend/src/router.ts
+++ b/frontend/src/router.ts
@@ -1,5 +1,7 @@
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
+import { basePath } from './base';
+
const FileWorkflow = () => import('./components/FileWorkflow.vue');
const CapacityDashboard = () => import('./components/CapacityDashboard.vue');
const HistoryPanel = () => import('./components/HistoryPanel.vue');
@@ -19,6 +21,6 @@ export const routes: RouteRecordRaw[] = [
];
export const router = createRouter({
- history: createWebHistory(import.meta.env.BASE_URL),
+ history: createWebHistory(basePath),
routes
});
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index d163dc9..fe9b0b9 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -388,6 +388,26 @@ select {
flex-shrink: 0;
}
+.header-user {
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ gap: 6px;
+ max-width: 180px;
+ height: 32px;
+ padding: 0 10px;
+ color: var(--td-text-color-secondary);
+ font-size: 13px;
+ border: 1px solid var(--td-border-color);
+ border-radius: var(--td-radius-default);
+}
+
+.header-user span {
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
.content {
height: calc(100vh - 64px);
min-width: 0;
@@ -653,35 +673,6 @@ select {
border-radius: var(--td-radius-small);
}
-.license-dialog-body {
- display: flex;
- flex-direction: column;
- gap: 12px;
-}
-
-.license-dialog-text {
- margin: 0;
- color: var(--td-text-color-secondary);
- font-size: 13px;
- line-height: 1.6;
-}
-
-.license-key-label {
- padding: 8px 10px;
- color: var(--td-brand-color);
- font-family: Consolas, "Courier New", monospace;
- font-size: 13px;
- background: var(--td-brand-color-light);
- border: 1px solid var(--td-brand-color-focus);
- border-radius: var(--td-radius-default);
-}
-
-.license-dialog-footer {
- display: flex;
- justify-content: flex-end;
- gap: 8px;
-}
-
.file-list {
margin-top: 20px;
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0879af7..fa83252 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -13,18 +13,15 @@ export interface ApiError {
export interface ApiErrorDetail {
code?: string;
message?: string;
- expires_on?: string;
- current_date?: string;
- key_label?: string;
[key: string]: unknown;
}
-export interface LicenseStatus {
- success: boolean;
- expires_on: string;
- key_label: string;
- current_date?: string | null;
- zip_count?: number;
+export interface SessionInfo {
+ hosted: boolean;
+ user?: {
+ name: string;
+ role: 'admin' | 'user';
+ } | null;
}
export interface CellDataResult {
@@ -41,7 +38,6 @@ export interface TaskStatus {
logs: string[];
elapsed_time?: number;
error?: string;
- error_detail?: ApiErrorDetail;
result?: CellDataResult;
}
@@ -96,9 +92,6 @@ export interface CacheSize {
export interface AppConfig {
update: string;
- metrix_enabled: boolean;
- source_type: 'external' | 'metrix';
- warehouse_type: 'mysql' | 'metrix';
mysql: {
host: string;
port: number;
@@ -106,7 +99,6 @@ export interface AppConfig {
passwd?: string;
dbname: string;
};
- metrix: MetrixConfig;
data_mappings: DataMappingsConfig;
remote_data: RemoteDataConfig;
cell_data: CellDataConfig;
@@ -115,15 +107,6 @@ export interface AppConfig {
extract_fields: Array>;
}
-export interface MetrixConfig {
- base_url: string;
- token?: string;
- storage_id: string;
- database_conn_id: string;
- target_database: string;
- recent_days: number;
-}
-
export interface DataDirectoryMapping {
path: string;
table: string;
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 19e2be7..fe9b71a 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -5,6 +5,8 @@ import Components from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
export default defineConfig({
+ // 相对路径资源:托管到 Metrix 时由后端注入 。
+ base: './',
plugins: [
vue(),
AutoImport({
diff --git a/requirements.txt b/requirements.txt
index ce718f0..2f31209 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,10 +3,7 @@ fastapi
uvicorn[standard]
python-multipart
-# Metrix 平台 API 客户端(Metrix 源/仓库模式)
-requests
-
-# 直连数据库 / 授权(直连 MySQL 模式 + 本地授权)
+# 直连 MySQL(cryptography 供 MySQL 8 caching_sha2_password 认证)
pymysql
cryptography
diff --git a/scripts/clean.py b/scripts/clean.py
index e08efc0..9bcbda0 100644
--- a/scripts/clean.py
+++ b/scripts/clean.py
@@ -4,7 +4,7 @@
python scripts/clean.py # 清理缓存 / 编译产物 / 运行时临时数据(保留 .venv 与前端依赖)
python scripts/clean.py --deep # 额外清理 .venv 与 frontend/node_modules(下次运行会重装)
-默认不会删除源码、配置(Configure.json/*.sql)、授权文件或 .git。
+默认不会删除源码、配置(Configure.json/*.sql)、账号文件或 .git。
"""
from __future__ import annotations
diff --git a/scripts/gen_license_code.py b/scripts/gen_license_code.py
deleted file mode 100644
index 37615c9..0000000
--- a/scripts/gen_license_code.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python3
-"""根据授权 key 生成激活码(与 app/services/license.py 算法一致)。"""
-
-from __future__ import annotations
-
-import argparse
-import sys
-from datetime import date, datetime
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from app.services.license import activation_hash, format_key_label
-
-
-def parse_key(raw: str) -> date:
- text = raw.strip()
- for fmt in ("%Y/%m/%d", "%Y-%m-%d"):
- try:
- return datetime.strptime(text, fmt).date()
- except ValueError:
- continue
- raise ValueError("无法解析 key,请使用 YYYY/MM/DD 格式,例如 2026/06/20")
-
-
-def generate_code(key: str) -> tuple[str, str]:
- expires_on = parse_key(key)
- key_label = format_key_label(expires_on)
- return key_label, activation_hash(expires_on)
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- description="输入授权 key(到期日期),输出对应激活码。",
- )
- parser.add_argument(
- "key",
- nargs="?",
- help="授权 key,格式 YYYY/MM/DD 或 YYYY-MM-DD,例如 2026/06/20",
- )
- return parser
-
-
-def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- key_input = args.key
- if not key_input:
- try:
- key_input = input("请输入 key (YYYY/MM/DD): ").strip()
- except EOFError:
- print("未输入 key。", file=sys.stderr)
- return 1
-
- if not key_input:
- print("key 不能为空。", file=sys.stderr)
- return 1
-
- try:
- key_label, code = generate_code(key_input)
- except ValueError as exc:
- print(str(exc), file=sys.stderr)
- return 1
-
- print(f"key: {key_label}")
- print(f"激活码: {code}")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/package_metrix.py b/scripts/package_metrix.py
new file mode 100644
index 0000000..50f7530
--- /dev/null
+++ b/scripts/package_metrix.py
@@ -0,0 +1,118 @@
+"""把 CapacityReport 打成 Metrix 应用包:dist/metrix/capacityreport-<版本>.zip。
+
+包里有 metrix-app.json、图标 icon.svg 和镜像文件 image.tar。版本取 app/main.py 的 APP_VERSION
+加 git 短哈希,工作区有未提交的改动时再加 -dirty。需要本机可用的 node 和 docker。
+
+用法:
+ python scripts/package_metrix.py # 构建前端和镜像后打包
+ python scripts/package_metrix.py --skip-build # 直接打包本机已有的同版本镜像
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import zipfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import _env # noqa: E402
+
+SLUG = "capacityreport"
+NAME = "CapacityReport"
+WEB_PORT = 9081
+DATA_DIR = "/data"
+ICON = _env.FRONTEND_DIR / "public" / "favicon.svg"
+
+
+def _git(*args: str) -> str:
+ completed = subprocess.run(
+ ["git", "-c", f"safe.directory={_env.ROOT.as_posix()}", *args],
+ cwd=_env.ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ return completed.stdout.strip()
+
+
+def version() -> str:
+ source = (_env.ROOT / "app" / "main.py").read_text(encoding="utf-8")
+ match = re.search(r'^APP_VERSION\s*=\s*"([^"]+)"', source, re.MULTILINE)
+ if not match:
+ _env.die("没有在 app/main.py 找到 APP_VERSION")
+ base = match.group(1)
+ try:
+ commit = _git("rev-parse", "--short", "HEAD")
+ dirty = bool(_git("status", "--porcelain", "--untracked-files=no"))
+ except (OSError, subprocess.CalledProcessError):
+ return base
+ return f"{base}-{commit}-dirty" if dirty else f"{base}-{commit}"
+
+
+def manifest(image: str, release: str) -> dict:
+ return {
+ "schema": 2,
+ "slug": SLUG,
+ "name": NAME,
+ "version": release,
+ "user_auth": "metrix",
+ "admin_auth": "none",
+ "icon": "icon.svg",
+ "services": [
+ {"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT},
+ ],
+ "data_dir": DATA_DIR,
+ "env": {"CAPAREPORT_BASE_DIR": DATA_DIR},
+ }
+
+
+def build_image(image: str) -> None:
+ _env.ensure_docker()
+ _env.build_frontend()
+ _env.step(f"构建镜像 {image}")
+ _env.run(["docker", "build", "--progress=plain", "-t", image, "."], cwd=_env.ROOT)
+
+
+def write_bundle(image: str, release: str, target: Path) -> None:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ partial = target.with_name(target.name + ".partial")
+ with tempfile.TemporaryDirectory(prefix=f"{SLUG}-pack-", dir=target.parent) as work:
+ tar = Path(work) / "image.tar"
+ _env.step("导出镜像")
+ _env.run(["docker", "save", "-o", str(tar), image])
+ _env.step("写入应用包")
+ with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle:
+ bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n")
+ bundle.write(ICON, "icon.svg")
+ bundle.write(tar, "image.tar")
+ os.replace(partial, target)
+
+
+def main() -> int:
+ _env.setup_console()
+ parser = argparse.ArgumentParser(description="打包 CapacityReport 为 Metrix 应用包")
+ parser.add_argument("--skip-build", action="store_true", help="不重新构建,直接打包本机已有的同版本镜像")
+ parser.add_argument("--output", default=str(_env.DIST_DIR / "metrix"), help="输出目录")
+ args = parser.parse_args()
+
+ current = version()
+ image = f"{SLUG}:{current}"
+ if not args.skip_build:
+ build_image(image)
+ target = Path(args.output).resolve() / f"{SLUG}-{current}.zip"
+ write_bundle(image, current, target)
+ size = target.stat().st_size
+ _env.step(f"应用包:{target}")
+ _env.info(f"大小:{size / 1024 / 1024:.1f} MB({size} 字节)")
+ _env.info(f"镜像:{image}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_hosted_auth.py b/tests/test_hosted_auth.py
new file mode 100644
index 0000000..1eef45f
--- /dev/null
+++ b/tests/test_hosted_auth.py
@@ -0,0 +1,119 @@
+import asyncio
+import os
+import unittest
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest import mock
+
+from starlette.requests import Request
+from starlette.responses import Response
+
+from app import main
+from app.api.routers import auth as auth_router
+from app.auth import create_jwt_token
+
+
+PROXY_HEADERS = {
+ "x-metrix-proxy-token": "proxy-secret",
+ "x-metrix-user-id": "7",
+ "x-metrix-username": "alice",
+ "x-metrix-display-name": "%E5%BC%A0%E4%B8%89",
+ "x-metrix-app-role": "user",
+}
+
+
+def make_request(path: str, headers: dict[str, str] | None = None) -> Request:
+ raw = [(key.lower().encode("latin-1"), value.encode("latin-1")) for key, value in (headers or {}).items()]
+ return Request({"type": "http", "method": "GET", "path": path, "headers": raw, "query_string": b""})
+
+
+async def passthrough(_request: Request) -> Response:
+ return Response("ok")
+
+
+def run_middleware(request: Request) -> Response:
+ return asyncio.run(main.auth_middleware(request, passthrough))
+
+
+class HostedAuthTests(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "proxy-secret"})
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_platform_identity_is_accepted(self):
+ request = make_request("/api/config", PROXY_HEADERS)
+ response = run_middleware(request)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(request.state.auth_context.kind, "platform")
+ self.assertEqual(request.state.auth_context.payload["name"], "张三")
+
+ def test_wrong_proxy_token_is_rejected(self):
+ headers = {**PROXY_HEADERS, "x-metrix-proxy-token": "forged"}
+ self.assertEqual(run_middleware(make_request("/api/database/tables", headers)).status_code, 401)
+
+ def test_unknown_role_is_rejected(self):
+ headers = {**PROXY_HEADERS, "x-metrix-app-role": "guest"}
+ self.assertEqual(run_middleware(make_request("/api/history", headers)).status_code, 401)
+
+ def test_app_jwt_is_not_accepted(self):
+ token = create_jwt_token({"user": "root"})
+ request = make_request("/api/config", {"authorization": f"Bearer {token}"})
+ self.assertEqual(run_middleware(request).status_code, 401)
+
+ def test_login_and_change_password_are_disabled(self):
+ for path in ("/api/login", "/api/change-password"):
+ self.assertEqual(run_middleware(make_request(path, PROXY_HEADERS)).status_code, 404)
+
+ def test_frontend_and_session_pass_through(self):
+ for path in ("/", "/upload", "/assets/index.js", "/api/session"):
+ self.assertEqual(run_middleware(make_request(path)).status_code, 200)
+
+ def test_session_reports_platform_user(self):
+ result = asyncio.run(auth_router.get_session(make_request("/api/session", PROXY_HEADERS)))
+ self.assertEqual(result, {"hosted": True, "user": {"name": "张三", "role": "user"}})
+
+
+class StandaloneAuthTests(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": ""})
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_proxy_headers_are_ignored(self):
+ self.assertEqual(run_middleware(make_request("/api/config", PROXY_HEADERS)).status_code, 401)
+
+ def test_app_jwt_is_accepted(self):
+ token = create_jwt_token({"user": "root"})
+ request = make_request("/api/history", {"authorization": f"Bearer {token}"})
+ self.assertEqual(run_middleware(request).status_code, 200)
+
+ def test_login_and_session_are_open(self):
+ for path in ("/api/login", "/api/session"):
+ self.assertEqual(run_middleware(make_request(path)).status_code, 200)
+
+ def test_session_reports_standalone(self):
+ result = asyncio.run(auth_router.get_session(make_request("/api/session", PROXY_HEADERS)))
+ self.assertEqual(result, {"hosted": False, "user": None})
+
+
+class RenderIndexTests(unittest.TestCase):
+ def render(self, html: str, prefix: str):
+ with TemporaryDirectory() as folder:
+ index = Path(folder) / "index.html"
+ index.write_text(html, encoding="utf-8")
+ return main._render_index(index, prefix)
+
+ def test_hosted_prefix_replaces_base_tag(self):
+ response = self.render('', "/apps/capacityreport")
+ self.assertIn('', response.body.decode())
+ self.assertEqual(response.headers["cache-control"], "no-store")
+ self.assertEqual(response.headers["vary"], "X-Forwarded-Prefix")
+
+ def test_invalid_prefix_falls_back_to_root(self):
+ response = self.render("", '/apps/x">