Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c18f039a15 | ||
|
|
22fbf47577 |
@@ -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": [
|
||||
{
|
||||
|
||||
+21
-14
@@ -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 # 入口:创建应用、鉴权中间件、注册路由、托管前端(注入 <base href>)
|
||||
│ ├─ 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` 里的 `<base href>`。前端用相对路径构建(`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 平台代理身份 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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` 端口,若被占用可在运行时指定其他端口 |
|
||||
|
||||
+17
-3
@@ -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": "密码修改成功"}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""容量看板分析接口。
|
||||
|
||||
基于 4G/5G 结果表(含富集 + 高负荷判定 + 优化建议列)做聚合分析,供前端容量看板展示。
|
||||
读经 `make_warehouse`(直连 MySQL 或 Metrix 平台),分析对象为“主仓库”里的结果表。
|
||||
读经 `make_warehouse`(直连 MySQL),分析对象为“主仓库”里的结果表。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
+13
-35
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
+42
@@ -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("=")
|
||||
|
||||
@@ -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),
|
||||
|
||||
+4
-6
@@ -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
|
||||
|
||||
|
||||
+55
-19
@@ -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"<base\b[^>]*>", 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'<base href="{href}" />'
|
||||
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("<head>", f"<head>\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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
@@ -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"(?<!\d)(20\d{10}(?:\d{2})?)(?!\d)")
|
||||
|
||||
|
||||
class LicenseError(Exception):
|
||||
"""授权校验错误。"""
|
||||
|
||||
code = "LICENSE_ERROR"
|
||||
|
||||
def to_detail(self) -> 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))
|
||||
@@ -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)}
|
||||
@@ -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,
|
||||
)
|
||||
+3
-219
@@ -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 执行失败")
|
||||
|
||||
+3
-3
@@ -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 默认有)。
|
||||
|
||||
## 当前清单
|
||||
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# 项目上下文记录
|
||||
|
||||
## 2026-11-06:托管到 Metrix 应用包,去掉授权与 Metrix 平台模式(分支 feat/metrix-hosting)
|
||||
|
||||
- 应用包:新增 `scripts/package_metrix.py`,构建前端与镜像后生成 `dist/metrix/capacityreport-<APP_VERSION>-<短哈希>.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` 的 `<base href>`,响应带 `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` 自带 `<base href="/" />` 供直接访问、开发模式和桌面端使用。
|
||||
- 托管界面:`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`(托管/独立两种鉴权、会话接口、`<base href>` 注入),`unittest discover` 19 项通过(3 项真实 MySQL 用例按配置跳过);`npm run build`(含 vue-tsc)通过。
|
||||
|
||||
## 2026-06-26:新增工具发布平台投稿文档(docs/upload)
|
||||
|
||||
- 按工具平台投稿模板新增 `docs/upload/` 三份文档:`工具说明书.docx`、`测试报告.docx`、`工具详细介绍.md`。
|
||||
|
||||
+2
-1
@@ -1,8 +1,10 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<base href="/" />
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<title>CapacityReport</title>
|
||||
</head>
|
||||
<body>
|
||||
@@ -10,4 +12,3 @@
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#0052D9"/>
|
||||
<stop offset="1" stop-color="#618DFF"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="32" height="32" rx="7" fill="url(#g)"/>
|
||||
<rect x="7.5" y="17" width="4" height="7.5" rx="1.2" fill="#fff" fill-opacity=".72"/>
|
||||
<rect x="14" y="12" width="4" height="12.5" rx="1.2" fill="#fff" fill-opacity=".86"/>
|
||||
<rect x="20.5" y="7.5" width="4" height="17" rx="1.2" fill="#fff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 558 B |
+13
-60
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<LoginView v-if="!token" :loading="loginLoading" @login="handleLogin" />
|
||||
<n-layout v-else has-sider class="app-layout">
|
||||
<LoginView v-if="session.ready && !session.hosted && !token" :loading="loginLoading" @login="handleLogin" />
|
||||
<n-layout v-else-if="session.ready" has-sider class="app-layout">
|
||||
<n-layout-sider
|
||||
class="app-sider"
|
||||
collapse-mode="width"
|
||||
@@ -11,17 +11,7 @@
|
||||
@update:collapsed="handleSidebarCollapsed"
|
||||
>
|
||||
<div class="brand">
|
||||
<div
|
||||
class="brand-mark"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
title="CapacityReport"
|
||||
@click="handleBrandMarkClick"
|
||||
@keydown.enter.prevent="handleBrandMarkClick"
|
||||
@keydown.space.prevent="handleBrandMarkClick"
|
||||
>
|
||||
📊
|
||||
</div>
|
||||
<div class="brand-mark" aria-hidden="true">📊</div>
|
||||
<div class="brand-text">CapacityReport</div>
|
||||
</div>
|
||||
<n-menu
|
||||
@@ -98,7 +88,11 @@
|
||||
<button class="theme-toggle" type="button" :title="themeToggleTitle" @click="toggleTheme">
|
||||
<n-icon><component :is="themeToggleIcon" /></n-icon>
|
||||
</button>
|
||||
<n-button tertiary circle title="退出登录" class="logout-button" @click="logout">
|
||||
<span v-if="session.hosted" class="header-user" :title="session.userName">
|
||||
<n-icon><PersonCircleOutline /></n-icon>
|
||||
<span>{{ session.userName }}</span>
|
||||
</span>
|
||||
<n-button v-else tertiary circle title="退出登录" class="logout-button" @click="logout">
|
||||
<template #icon>
|
||||
<n-icon><LogOutOutline /></n-icon>
|
||||
</template>
|
||||
@@ -111,8 +105,6 @@
|
||||
</n-layout-content>
|
||||
</n-layout>
|
||||
</n-layout>
|
||||
|
||||
<LicenseActivationModal v-if="licenseModalVisible" v-model:show="licenseModalVisible" @metrix-changed="onMetrixChanged" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
@@ -126,31 +118,28 @@ import {
|
||||
FileTrayFullOutline,
|
||||
LogOutOutline,
|
||||
MoonOutline,
|
||||
PersonCircleOutline,
|
||||
ServerOutline,
|
||||
SettingsOutline,
|
||||
StatsChartOutline,
|
||||
SunnyOutline
|
||||
} from '@vicons/ionicons5';
|
||||
|
||||
import { apiGet, apiPost, clearToken, getToken, setToken, setUnauthorizedHandler } from './api/client';
|
||||
import type { AppConfig, LoginResponse } from './types';
|
||||
import { apiPost, clearToken, getToken, setToken, setUnauthorizedHandler } from './api/client';
|
||||
import type { LoginResponse } from './types';
|
||||
import { pageHeader, resetPageHeader, resolveHeaderValue, type PageHeaderAction } from './composables/pageHeader';
|
||||
import { metrixEnabled } from './composables/metrixEnabled';
|
||||
import { loadSession, session } from './composables/session';
|
||||
import { themeName, toggleAppTheme } from './composables/theme';
|
||||
|
||||
const LoginView = defineAsyncComponent(() => import('./components/LoginView.vue'));
|
||||
const LicenseActivationModal = defineAsyncComponent(() => import('./components/LicenseActivationModal.vue'));
|
||||
const message = useMessage();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const token = ref(getToken());
|
||||
const loginLoading = ref(false);
|
||||
const sidebarCollapsed = ref(localStorage.getItem('sidebarCollapsed') === 'true');
|
||||
const licenseModalVisible = ref(false);
|
||||
const brandClickCount = ref(0);
|
||||
const menuKeys = ['workflow', 'dashboard', 'history', 'database', 'script', 'settings'] as const;
|
||||
type MenuKey = (typeof menuKeys)[number];
|
||||
let brandClickResetTimer: number | undefined;
|
||||
|
||||
const menuOptions: MenuOption[] = [
|
||||
{ label: '数据处理', key: 'workflow', icon: renderIcon(CloudUploadOutline) },
|
||||
@@ -175,17 +164,12 @@ const themeToggleTitle = computed(() => (themeName.value === 'dark' ? '切换到
|
||||
onMounted(() => {
|
||||
window.addEventListener('dragover', preventWindowFileDrop, { capture: true });
|
||||
window.addEventListener('drop', preventWindowFileDrop, { capture: true });
|
||||
if (token.value) {
|
||||
void loadMetrixEnabled();
|
||||
}
|
||||
void loadSession();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('dragover', preventWindowFileDrop, { capture: true });
|
||||
window.removeEventListener('drop', preventWindowFileDrop, { capture: true });
|
||||
if (brandClickResetTimer !== undefined) {
|
||||
window.clearTimeout(brandClickResetTimer);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -204,7 +188,6 @@ async function handleLogin(payload: { username: string; password: string }) {
|
||||
setToken(result.token);
|
||||
token.value = result.token;
|
||||
message.success('登录成功');
|
||||
void loadMetrixEnabled();
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '登录失败');
|
||||
} finally {
|
||||
@@ -233,36 +216,6 @@ function handleMenuChange(key: string | number) {
|
||||
void router.push({ name: key });
|
||||
}
|
||||
|
||||
function onMetrixChanged(enabled: boolean) {
|
||||
metrixEnabled.value = enabled;
|
||||
}
|
||||
|
||||
async function loadMetrixEnabled() {
|
||||
try {
|
||||
const config = await apiGet<AppConfig>('/api/config/full');
|
||||
metrixEnabled.value = config.metrix_enabled ?? false;
|
||||
} catch {
|
||||
metrixEnabled.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleBrandMarkClick() {
|
||||
brandClickCount.value += 1;
|
||||
if (brandClickResetTimer !== undefined) {
|
||||
window.clearTimeout(brandClickResetTimer);
|
||||
}
|
||||
|
||||
if (brandClickCount.value >= 8) {
|
||||
brandClickCount.value = 0;
|
||||
licenseModalVisible.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
brandClickResetTimer = window.setTimeout(() => {
|
||||
brandClickCount.value = 0;
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function isMenuKey(value: unknown): value is MenuKey {
|
||||
return typeof value === 'string' && menuKeys.includes(value as MenuKey);
|
||||
}
|
||||
|
||||
+22
-25
@@ -1,3 +1,4 @@
|
||||
import { appUrl } from '../base';
|
||||
import type { ApiError, ApiErrorDetail } from '../types';
|
||||
|
||||
const TOKEN_KEY = 'capacity_report_token';
|
||||
@@ -7,6 +8,7 @@ const API_FETCH_RETRIES = 8;
|
||||
const API_FETCH_RETRY_DELAY_MS = 500;
|
||||
const TAURI_HTTP_ERROR_PREFIX = 'CAPAREPORT_HTTP_ERROR:';
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
let hostedMode = false;
|
||||
let cachedTauriInvoke: TauriInvoke | null = null;
|
||||
|
||||
type TauriInvoke = <T>(command: string, args?: Record<string, unknown>) => Promise<T>;
|
||||
@@ -66,6 +68,19 @@ export function setUnauthorizedHandler(handler: () => void): void {
|
||||
onUnauthorized = handler;
|
||||
}
|
||||
|
||||
export function setHostedMode(value: boolean): void {
|
||||
hostedMode = value;
|
||||
}
|
||||
|
||||
function unauthorizedError(status: number): ApiRequestError {
|
||||
if (!hostedMode) {
|
||||
clearToken();
|
||||
}
|
||||
onUnauthorized?.();
|
||||
const text = hostedMode ? '访问已失效,请刷新页面后重试' : '登录已过期,请重新登录';
|
||||
return new ApiRequestError(text, status, { code: 'UNAUTHORIZED', message: text });
|
||||
}
|
||||
|
||||
export async function apiGet<T>(url: string): Promise<T> {
|
||||
return request<T>(url, { method: 'GET' });
|
||||
}
|
||||
@@ -92,12 +107,7 @@ export async function request<T>(url: string, init: RequestInit = {}): Promise<T
|
||||
throw new ApiRequestError(error.message, response.status, error.detail);
|
||||
}
|
||||
|
||||
clearToken();
|
||||
onUnauthorized?.();
|
||||
throw new ApiRequestError('登录已过期,请重新登录', response.status, {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '登录已过期,请重新登录'
|
||||
});
|
||||
throw unauthorizedError(response.status);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -130,14 +140,7 @@ export function upload<T>(
|
||||
|
||||
xhr.addEventListener('load', () => {
|
||||
if (xhr.status === 401) {
|
||||
clearToken();
|
||||
onUnauthorized?.();
|
||||
reject(
|
||||
new ApiRequestError('登录已过期,请重新登录', xhr.status, {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '登录已过期,请重新登录'
|
||||
})
|
||||
);
|
||||
reject(unauthorizedError(xhr.status));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -203,12 +206,7 @@ export async function downloadGet(url: string, fallbackFilename: string): Promis
|
||||
|
||||
const response = await fetchWithRetry(apiUrl(url), { headers });
|
||||
if (response.status === 401) {
|
||||
clearToken();
|
||||
onUnauthorized?.();
|
||||
throw new ApiRequestError('登录已过期,请重新登录', response.status, {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '登录已过期,请重新登录'
|
||||
});
|
||||
throw unauthorizedError(response.status);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -358,16 +356,15 @@ function parseFilename(disposition: string | null): string {
|
||||
}
|
||||
|
||||
export function apiUrl(url: string): string {
|
||||
if (!API_BASE || /^https?:\/\//i.test(url)) {
|
||||
if (/^https?:\/\//i.test(url)) {
|
||||
return url;
|
||||
}
|
||||
if (!API_BASE) {
|
||||
return appUrl(url);
|
||||
}
|
||||
return `${API_BASE}${url.startsWith('/') ? url : `/${url}`}`;
|
||||
}
|
||||
|
||||
export function getApiBaseUrl(): string {
|
||||
return API_BASE || window.location.origin;
|
||||
}
|
||||
|
||||
function resolveApiBase(): string {
|
||||
const configured = (import.meta.env.VITE_API_BASE || '').replace(/\/$/, '');
|
||||
if (configured) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
function computeBasePath(): string {
|
||||
const path = new URL(document.baseURI).pathname;
|
||||
return path.endsWith('/') ? path : path.slice(0, path.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
/** 站点所在路径:直接访问时是 "/",托管到 Metrix 时类似 "/apps/capacityreport/"。 */
|
||||
export const basePath = computeBasePath();
|
||||
|
||||
export function appUrl(path: string): string {
|
||||
return basePath + path.replace(/^\/+/, '');
|
||||
}
|
||||
@@ -528,9 +528,7 @@ async function testConnection() {
|
||||
async function loadDatabaseSourceOptions() {
|
||||
try {
|
||||
const config = await apiGet<AppConfig>('/api/config');
|
||||
const mainName = config.warehouse_type === 'metrix'
|
||||
? (config.metrix.target_database || 'Metrix')
|
||||
: (config.mysql.dbname || '主数据库');
|
||||
const mainName = config.mysql.dbname || '主数据库';
|
||||
const cellName = config.cell_data?.mysql?.dbname || 'CellData';
|
||||
databaseSourceOptions.value = [
|
||||
{ label: `主数据库:${mainName}`, value: 'main', title: '主数据库', databaseName: mainName },
|
||||
|
||||
@@ -231,32 +231,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-modal
|
||||
v-model:show="licenseModalVisible"
|
||||
preset="card"
|
||||
title="授权已过期"
|
||||
:mask-closable="!activationLoading"
|
||||
:style="{ width: '420px', maxWidth: 'calc(100vw - 32px)' }"
|
||||
>
|
||||
<div class="license-dialog-body">
|
||||
<p class="license-dialog-text">{{ licenseErrorMessage }}</p>
|
||||
<div class="license-key-label">key: {{ activationKeyLabel }}</div>
|
||||
<n-input
|
||||
v-model:value="activationCode"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 3, maxRows: 5 }"
|
||||
placeholder="请输入激活码"
|
||||
:disabled="activationLoading"
|
||||
/>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="license-dialog-footer">
|
||||
<n-button :disabled="activationLoading" @click="licenseModalVisible = false">取消</n-button>
|
||||
<n-button type="primary" :loading="activationLoading" @click="submitActivation">激活</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
|
||||
<n-modal
|
||||
v-model:show="capacityHelpVisible"
|
||||
preset="card"
|
||||
@@ -328,8 +302,8 @@ import {
|
||||
TrashOutline
|
||||
} from '@vicons/ionicons5';
|
||||
|
||||
import { ApiRequestError, apiGet, apiPost, upload } from '../api/client';
|
||||
import type { ActiveTask, ApiErrorDetail, CellDataResult, LicenseStatus, TaskStatus } from '../types';
|
||||
import { apiGet, apiPost, upload } from '../api/client';
|
||||
import type { ActiveTask, CellDataResult, TaskStatus } from '../types';
|
||||
import { toColoredLogLines } from '../composables/logLines';
|
||||
|
||||
type FileStatus = 'pending' | 'uploading' | 'uploaded' | 'error';
|
||||
@@ -372,17 +346,10 @@ const taskStatus = ref<TaskStatus | null>(null);
|
||||
const activeTask = ref<ActiveTask | null>(null);
|
||||
const keepLatestLog = ref(true);
|
||||
const logContainer = ref<HTMLElement | null>(null);
|
||||
const licenseModalVisible = ref(false);
|
||||
const activationCode = ref('');
|
||||
const activationLoading = ref(false);
|
||||
const activationKeyLabel = ref('2026/12/30');
|
||||
const licenseErrorMessage = ref('当前数据日期已超过授权到期日期,请输入激活码延长 30 天。');
|
||||
const taskMode = ref<'local' | 'remote' | 'cell_data' | 'unknown'>('unknown');
|
||||
let activationRetry: (() => Promise<void>) | null = null;
|
||||
let timer: number | undefined;
|
||||
|
||||
const stageLabels: Record<string, string> = {
|
||||
license: '授权校验中...',
|
||||
cell_data: '更新 CellData...',
|
||||
locating: '定位数据中...',
|
||||
downloading: '远程下载中...',
|
||||
@@ -711,9 +678,7 @@ async function uploadAndStart() {
|
||||
item.status = 'error';
|
||||
}
|
||||
});
|
||||
if (!handleApiLicenseError(error)) {
|
||||
message.error(error instanceof Error ? error.message : '上传或启动任务失败');
|
||||
}
|
||||
message.error(error instanceof Error ? error.message : '上传或启动任务失败');
|
||||
} finally {
|
||||
working.value = false;
|
||||
}
|
||||
@@ -743,9 +708,7 @@ async function startRemoteProcessing() {
|
||||
taskMode.value = 'remote';
|
||||
startPolling(result.task_id);
|
||||
} catch (error) {
|
||||
if (!handleApiLicenseError(error)) {
|
||||
message.error(error instanceof Error ? error.message : '启动远程自动化任务失败');
|
||||
}
|
||||
message.error(error instanceof Error ? error.message : '启动远程自动化任务失败');
|
||||
} finally {
|
||||
remoteStarting.value = false;
|
||||
}
|
||||
@@ -825,7 +788,7 @@ async function startUploadedTask(taskId: string) {
|
||||
taskStatus.value = {
|
||||
task_id: taskId,
|
||||
status: 'processing',
|
||||
stage: 'license',
|
||||
stage: 'processing',
|
||||
logs: ['任务已提交,等待处理日志...']
|
||||
};
|
||||
startPolling(taskId);
|
||||
@@ -876,9 +839,6 @@ async function poll(taskId: string) {
|
||||
if (['completed', 'failed'].includes(taskStatus.value.status)) {
|
||||
stopPolling();
|
||||
await checkActiveTask();
|
||||
if (taskStatus.value.status === 'failed') {
|
||||
handleTaskLicenseError(taskStatus.value);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
stopPolling();
|
||||
@@ -886,86 +846,6 @@ async function poll(taskId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function handleTaskLicenseError(status: TaskStatus): boolean {
|
||||
const detail = status.error_detail || parseLicenseDetail(status.error || '');
|
||||
if (detail?.code !== 'LICENSE_EXPIRED') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const taskId = status.task_id;
|
||||
const retry =
|
||||
taskMode.value === 'local'
|
||||
? () => startUploadedTask(taskId)
|
||||
: taskMode.value === 'remote'
|
||||
? () => startRemoteProcessing()
|
||||
: null;
|
||||
openLicenseModal(detail, retry);
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleApiLicenseError(error: unknown): boolean {
|
||||
if (!(error instanceof ApiRequestError) || error.code !== 'LICENSE_EXPIRED') {
|
||||
return false;
|
||||
}
|
||||
|
||||
openLicenseModal(error.detail);
|
||||
return true;
|
||||
}
|
||||
|
||||
function openLicenseModal(detail?: ApiErrorDetail, retry?: (() => Promise<void>) | null) {
|
||||
activationKeyLabel.value = detail?.key_label || activationKeyLabel.value;
|
||||
licenseErrorMessage.value =
|
||||
detail?.message || '当前数据日期已超过授权到期日期,请输入激活码延长 30 天。';
|
||||
activationCode.value = '';
|
||||
activationRetry = retry || null;
|
||||
licenseModalVisible.value = true;
|
||||
}
|
||||
|
||||
async function submitActivation() {
|
||||
const code = activationCode.value.trim();
|
||||
if (!code) {
|
||||
message.warning('请输入激活码');
|
||||
return;
|
||||
}
|
||||
|
||||
activationLoading.value = true;
|
||||
try {
|
||||
const result = await apiPost<LicenseStatus>('/api/license/activate', { code });
|
||||
activationKeyLabel.value = result.key_label;
|
||||
licenseModalVisible.value = false;
|
||||
message.success(`激活成功,到期日期: ${result.expires_on}`);
|
||||
if (activationRetry) {
|
||||
const retry = activationRetry;
|
||||
activationRetry = null;
|
||||
await retry();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError && error.detail?.key_label) {
|
||||
activationKeyLabel.value = error.detail.key_label;
|
||||
}
|
||||
message.error(error instanceof Error ? error.message : '激活失败');
|
||||
} finally {
|
||||
activationLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function parseLicenseDetail(text: string): ApiErrorDetail | null {
|
||||
if (!text.includes('授权已过期')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const expiresMatch = text.match(/到期日期\s+(\d{4}-\d{2}-\d{2})/);
|
||||
const currentMatch = text.match(/数据日期\s+(\d{4}-\d{2}-\d{2})/);
|
||||
const expiresOn = expiresMatch?.[1];
|
||||
return {
|
||||
code: 'LICENSE_EXPIRED',
|
||||
message: text,
|
||||
expires_on: expiresOn,
|
||||
current_date: currentMatch?.[1],
|
||||
key_label: expiresOn ? expiresOn.replace(/-/g, '/') : activationKeyLabel.value
|
||||
};
|
||||
}
|
||||
|
||||
function stageText(stage?: string | null): string {
|
||||
if (!stage) return '处理中...';
|
||||
return stageLabels[stage] || '处理中...';
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
<template>
|
||||
<n-modal
|
||||
v-model:show="visible"
|
||||
preset="card"
|
||||
title="授权延期"
|
||||
:mask-closable="!activationLoading"
|
||||
:style="{ width: '420px', maxWidth: 'calc(100vw - 32px)' }"
|
||||
>
|
||||
<div class="license-dialog-body">
|
||||
<p class="license-dialog-text">{{ licenseMessage }}</p>
|
||||
<div class="license-key-label">key: {{ activationKeyLabel }}</div>
|
||||
<n-input
|
||||
v-model:value="activationCode"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 3, maxRows: 5 }"
|
||||
placeholder="请输入激活码"
|
||||
:disabled="activationLoading"
|
||||
/>
|
||||
<div class="license-metrix-toggle">
|
||||
<n-switch :value="metrixEnabled" :loading="savingMetrix" size="small" @update:value="toggleMetrix" />
|
||||
<span class="license-metrix-label">启用 Metrix 平台</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="license-dialog-footer">
|
||||
<n-button :disabled="activationLoading" @click="visible = false">取消</n-button>
|
||||
<n-button type="primary" :loading="activationLoading" @click="submitActivation">激活</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useMessage } from 'naive-ui';
|
||||
|
||||
import { apiGet, apiPost } from '../api/client';
|
||||
import type { AppConfig, LicenseStatus } from '../types';
|
||||
|
||||
const visible = defineModel<boolean>('show', { required: true });
|
||||
const emit = defineEmits<{ metrixChanged: [enabled: boolean] }>();
|
||||
const message = useMessage();
|
||||
const activationCode = ref('');
|
||||
const activationLoading = ref(false);
|
||||
const activationKeyLabel = ref('2026/12/30');
|
||||
const licenseMessage = ref('输入激活码可将授权到期日期延长 30 天。');
|
||||
const metrixEnabled = ref(false);
|
||||
const savingMetrix = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
void loadLicenseStatus();
|
||||
void loadMetrixEnabled();
|
||||
});
|
||||
|
||||
async function loadLicenseStatus() {
|
||||
try {
|
||||
const status = await apiGet<LicenseStatus>('/api/license/status');
|
||||
activationKeyLabel.value = status.key_label;
|
||||
licenseMessage.value = `当前授权到期日期:${status.expires_on}。输入激活码可延长 30 天。`;
|
||||
activationCode.value = '';
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '获取授权状态失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMetrixEnabled() {
|
||||
try {
|
||||
const config = await apiGet<AppConfig>('/api/config/full');
|
||||
metrixEnabled.value = config.metrix_enabled ?? false;
|
||||
} catch {
|
||||
metrixEnabled.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleMetrix(target: boolean) {
|
||||
if (target === metrixEnabled.value) return;
|
||||
savingMetrix.value = true;
|
||||
try {
|
||||
await apiPost('/api/config/metrix-enabled', { enabled: target });
|
||||
metrixEnabled.value = target;
|
||||
emit('metrixChanged', target);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '保存失败');
|
||||
} finally {
|
||||
savingMetrix.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitActivation() {
|
||||
const code = activationCode.value.trim();
|
||||
if (!code) {
|
||||
message.warning('请输入激活码');
|
||||
return;
|
||||
}
|
||||
|
||||
activationLoading.value = true;
|
||||
try {
|
||||
const result = await apiPost<LicenseStatus>('/api/license/activate', { code });
|
||||
activationKeyLabel.value = result.key_label;
|
||||
licenseMessage.value = `当前授权到期日期:${result.expires_on}。输入激活码可继续延长 30 天。`;
|
||||
activationCode.value = '';
|
||||
message.success(`激活成功,到期日期: ${result.expires_on}`);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '激活失败');
|
||||
} finally {
|
||||
activationLoading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.license-metrix-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--n-border-color, #e0e0e6);
|
||||
}
|
||||
.license-metrix-label {
|
||||
font-size: 13px;
|
||||
color: var(--n-text-color-3, #999);
|
||||
}
|
||||
</style>
|
||||
@@ -4,77 +4,6 @@
|
||||
|
||||
<n-card size="small" class="work-card settings-tabs-card">
|
||||
<n-tabs type="line" animated class="settings-tabs">
|
||||
<n-tab-pane v-if="metrixEnabledRef" name="backend" tab="数据源 / 仓库">
|
||||
<div class="settings-database-panel">
|
||||
<div class="settings-database-stack">
|
||||
<n-card title="后端类型" size="small" class="work-card">
|
||||
<n-form label-placement="top">
|
||||
<n-form-item label="数据源">
|
||||
<n-radio-group v-model:value="sourceType">
|
||||
<n-radio-button value="external">外部储存</n-radio-button>
|
||||
<n-radio-button value="metrix">Metrix 储存平台</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<n-form-item label="数据仓库">
|
||||
<n-radio-group v-model:value="warehouseType">
|
||||
<n-radio-button value="mysql">MySQL</n-radio-button>
|
||||
<n-radio-button value="metrix">Metrix 数据库平台</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<p class="form-hint">数据源和数据仓库可独立选择;CellData 单独配置。</p>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button type="primary" :loading="savingBackend" @click="saveBackend">保存类型</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-card>
|
||||
|
||||
<n-card title="Metrix 连接(存储平台 / 数据库平台)" size="small" class="work-card">
|
||||
<n-form label-placement="top">
|
||||
<n-form-item label="平台地址 (api_base)">
|
||||
<n-input v-model:value="metrixForm.base_url" placeholder="http://host.docker.internal:8000" />
|
||||
</n-form-item>
|
||||
<n-form-item label="API Token">
|
||||
<n-input v-model:value="metrixForm.token" type="password" show-password-on="click" placeholder="mtx_..." />
|
||||
</n-form-item>
|
||||
<n-grid :cols="12" :x-gap="12">
|
||||
<n-gi :span="6">
|
||||
<n-form-item label="储存连接 ID">
|
||||
<n-input v-model:value="metrixForm.storage_id" placeholder="stg_..." />
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
<n-gi :span="6">
|
||||
<n-form-item label="数据库连接 ID">
|
||||
<n-input v-model:value="metrixForm.database_conn_id" placeholder="db_..." />
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
<n-grid :cols="12" :x-gap="12">
|
||||
<n-gi :span="8">
|
||||
<n-form-item label="目标库/Schema">
|
||||
<n-input v-model:value="metrixForm.target_database" placeholder="连接已指定库时可空" />
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
<n-gi :span="4">
|
||||
<n-form-item label="最近 N 天回退">
|
||||
<n-input-number v-model:value="metrixForm.recent_days" class="full-width" :min="1" :precision="0" />
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
<p class="form-hint">填写 Metrix 平台连接信息。</p>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button type="primary" :loading="savingMetrix" @click="saveMetrix">保存连接</n-button>
|
||||
<n-button :loading="testingRemote" @click="testRemote">测试储存</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-card>
|
||||
</div>
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
|
||||
<n-tab-pane name="database" tab="数据库">
|
||||
<div class="settings-database-panel">
|
||||
<div class="settings-database-stack">
|
||||
@@ -608,7 +537,7 @@
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
|
||||
<n-tab-pane name="security" tab="修改密码">
|
||||
<n-tab-pane v-if="!session.hosted" name="security" tab="修改密码">
|
||||
<div class="settings-security-panel">
|
||||
<n-card title="修改登录密码" size="small" class="work-card">
|
||||
<n-form label-placement="top">
|
||||
@@ -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<timestamp>\\\\d{14})(?=\\\\.zip$)'
|
||||
});
|
||||
|
||||
const metrixForm = reactive<MetrixConfig>({
|
||||
base_url: 'http://host.docker.internal:8000',
|
||||
token: '',
|
||||
storage_id: '',
|
||||
database_conn_id: '',
|
||||
target_database: '',
|
||||
recent_days: 7
|
||||
});
|
||||
|
||||
const dataMappingsForm = reactive<DataMappingsConfig>({
|
||||
directories: [
|
||||
{ path: '4G', table: '4G_UD', ready_rule: 'daily' },
|
||||
@@ -1121,16 +1036,6 @@ async function loadConfig() {
|
||||
try {
|
||||
const config = await apiGet<AppConfig>('/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<ApiMessage>('/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<ApiMessage>('/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('请填写完整数据库配置');
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
export const metrixEnabled = ref(false);
|
||||
@@ -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<void> {
|
||||
try {
|
||||
const info = await apiGet<SessionInfo>('/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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
});
|
||||
|
||||
+20
-29
@@ -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;
|
||||
}
|
||||
|
||||
+6
-23
@@ -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<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -5,6 +5,8 @@ import Components from 'unplugin-vue-components/vite';
|
||||
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
|
||||
|
||||
export default defineConfig({
|
||||
// 相对路径资源:托管到 Metrix 时由后端注入 <base href="/apps/<slug>/">。
|
||||
base: './',
|
||||
plugins: [
|
||||
vue(),
|
||||
AutoImport({
|
||||
|
||||
+1
-4
@@ -3,10 +3,7 @@ fastapi
|
||||
uvicorn[standard]
|
||||
python-multipart
|
||||
|
||||
# Metrix 平台 API 客户端(Metrix 源/仓库模式)
|
||||
requests
|
||||
|
||||
# 直连数据库 / 授权(直连 MySQL 模式 + 本地授权)
|
||||
# 直连 MySQL(cryptography 供 MySQL 8 caching_sha2_password 认证)
|
||||
pymysql
|
||||
cryptography
|
||||
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -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())
|
||||
@@ -0,0 +1,122 @@
|
||||
"""把 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,
|
||||
"description": {
|
||||
"zh-CN": "处理每周容量报表,生成 4G 和 5G 容量结果,并查看高负荷小区。",
|
||||
"en-US": "Processes weekly capacity reports, builds 4G and 5G capacity results, and reviews high-load cells.",
|
||||
},
|
||||
"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())
|
||||
@@ -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('<html><head><base href="/" /></head></html>', "/apps/capacityreport")
|
||||
self.assertIn('<base href="/apps/capacityreport/" />', 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("<html><head></head></html>", '/apps/x"><script>')
|
||||
self.assertIn('<base href="/" />', response.body.decode())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user