feat: 定时任务编辑入口全栈打通 + 修复ApprovalFlow编译错误 + 完成大文件拆分重构
- CronJobManager: 编辑按钮接通 onClick → openEdit(job),弹出编辑对话框预填数据,
复用新建/编辑共用 Dialog(editingId 区分模式),标题/按钮文案动态切换,
保存时根据 editingId 调用 createJob 或 updateJob — 消除占位按钮
- ApprovalFlow: 修复 API 方法名不匹配导致 tsc -b 编译失败
(getInstances→getProcesses, getMyApprovals→getProcesses({status:'pending'}),
approveInstance→approveProcess, rejectInstance→rejectProcess)
+ 添加 ApprovalFlowManager 导出别名兼容 App.tsx 导入
- 合并已完成的大文件拆分重构: automation.go→automation_cron/script/playbook,
ldap.go→ldap_ou/ldap_users, server.go→cloud_accounts/domain/platform/region,
user.go→user_admin; 前端 Dashboard/K8s/Server/Approval/Monitor 子组件拆分
// Logan.Li
This commit is contained in:
1 parent
8be63ac168
commit
a7e2351ad2
37 files changed
+7364
-4881
No files matched your search
@@ -0,0 +1,172 @@
|
|||||||
|
# EZOps AIOps — AI 开发全局规范
|
||||||
|
|
||||||
|
> 本文件供 AI 编程助手(Claude/Cursor/Copilot/Hermes)自动读取并遵循。
|
||||||
|
> 定义项目架构约束、代码规范、拆分策略和开发流程。
|
||||||
|
> 作者: Logan.Li · 语言: 中文(代码注释中文 + 署名 `// Logan.Li`)
|
||||||
|
|
||||||
|
## 项目概述
|
||||||
|
|
||||||
|
**EZOps AIOps** — AI 智能运维平台,涵盖 13 大模块:
|
||||||
|
服务器管理 · 云资源(账号/域名/账单) · K8s 集群 · 监控告警(Agent) · CI/CD 流水线 ·
|
||||||
|
自动化运维(CronJob/Script/Ansible) · 审批流程 · AI 智能运维(告警分析/故障诊断/预测/脚本生成) ·
|
||||||
|
导航收藏 · 审计日志 · 系统管理(用户/LDAP) · 监控 Agent(双通道: 指标采集+远程命令)
|
||||||
|
|
||||||
|
- **远程仓库**: https://gitee.com/attacker/aiops.git
|
||||||
|
- **Git 用户**: attacker / attacker@gitee.com
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
| 层 | 技术 | 端口 |
|
||||||
|
|---|---|---|
|
||||||
|
| 后端 | Go 1.21 + Gin + GORM + SQLite (+ MySQL/PG 可选) + JWT + Zap | 8080 |
|
||||||
|
| 前端 | React 19 + TypeScript + Vite + Tailwind + shadcn/ui + Zustand + TanStack Query | 5173 |
|
||||||
|
| Agent | Go 1.24 (CGO_ENABLED=0 静态二进制, amd64+arm64) | — |
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
### ⛔ 文件大小红线
|
||||||
|
|
||||||
|
| 类型 | 上限 | 超出处理 |
|
||||||
|
|------|------|----------|
|
||||||
|
| Go handler | **400 行** | 按 sub-domain 拆分到独立文件(同一 package) |
|
||||||
|
| Go model | **300 行** | 按模块拆分 |
|
||||||
|
| React 组件 (.tsx) | **700 行** | 提取子组件到同目录,主组件负责编排 |
|
||||||
|
| TypeScript 工具/服务 | **500 行** | 按功能域拆分 |
|
||||||
|
| 任何文件 | **700 行(硬上限)** | 必须拆分,无例外 |
|
||||||
|
|
||||||
|
**拆分策略**:
|
||||||
|
- **Go**: 同 package 下按职责拆文件(如 `automation.go` → `automation_cron.go` + `automation_script.go` + `automation_playbook.go`),共享 struct 放原文件或新建 `automation_types.go`
|
||||||
|
- **React**: 子组件提取到同目录独立 `.tsx` 文件(如 `SystemManager.tsx` → `SystemManager.tsx` + `SystemUserTab.tsx` + `SystemLdapTab.tsx`),通过 props 传递数据和回调
|
||||||
|
- **Mock 数据**: 按模块拆分(如 `data.ts` → `data/servers.ts` + `data/cloud.ts` + `data/k8s.ts` + `index.ts` 汇总导出)
|
||||||
|
|
||||||
|
### ⛔ Go 代码规范
|
||||||
|
|
||||||
|
1. **所有 handler 返回必须用 `models.Response{Code:200, Data:...}` 包裹** — 前端 `http.ts` 从 `json.data` 取值,裸 `gin.H{}` 会导致前端拿到 undefined 静默失败
|
||||||
|
2. **Go 编译命令**(每次必须):
|
||||||
|
```bash
|
||||||
|
cd ~/devops/aiops/backend && unset http_proxy https_proxy && export GOPROXY=https://goproxy.cn,direct && GOTOOLCHAIN=local CGO_ENABLED=1 go build -o aiops-server ./cmd/
|
||||||
|
```
|
||||||
|
3. **新增 handler 不绑 model** — 用独立 request struct 接收 `ShouldBindJSON`,再映射到 GORM model
|
||||||
|
4. **GORM 指针字段必须解引用** — model 中 `*int`/`*string` 字段传给 `fmt.Sprintf` 时先 `*field`
|
||||||
|
5. **SQLite 必须 CGO_ENABLED=1**(macOS 默认开)
|
||||||
|
6. **新模块 4 步**: Model → Handler → Routes(routes.go 注册) → AutoMigrate(database.go 添加)
|
||||||
|
|
||||||
|
### ⛔ React 前端规范
|
||||||
|
|
||||||
|
1. **API 列表响应解包** — 后端返回 `{code, data: {list: T[], total: N}}`,http.ts 提取 `.data` 后仍是 `{list, total}` 对象,组件中必须 `.list` 提取数组
|
||||||
|
2. **禁止 `window.confirm()`/`alert()`** — 用 `ConfirmProvider`(`useConfirm()` hook)替代 confirm,用 `toast.error()`/`toast.success()` 替代 alert
|
||||||
|
3. **Radix Dialog 必须有 `<DialogDescription>`** — 至少加 `<DialogDescription className="sr-only">`
|
||||||
|
4. **Token 不在 localStorage** — 用 `useUserStore.getState().token`(Zustand persist)
|
||||||
|
5. **新增组件 2 步**: API 层(`services/api.ts` 添加) → 组件+路由(`App.tsx` 加 Route,`Sidebar.tsx` 加菜单)
|
||||||
|
|
||||||
|
### ⛔ UI 设计原则
|
||||||
|
|
||||||
|
- **能去掉的都去掉** — 不要多余边框、高亮框、装饰性分隔线
|
||||||
|
- **按钮文案 2-4 字** — "批量导入" 而非 "批量导入用户"
|
||||||
|
- **不留占位按钮** — 功能没做好就不放按钮,不要 `toast.info('开发中')`
|
||||||
|
- **页面打开即用** — 不需要额外"新建"按钮跳转
|
||||||
|
- **主题感知** — 用 CSS 变量 `bg-[var(--dg-bg-secondary)]`,不用硬编码颜色
|
||||||
|
- **表单操作按钮在字段下方** — 用 `mt-4 pt-4 border-t` 分隔,不放 Card 标题右侧
|
||||||
|
- **主动排查同类问题** — 用户报一个 UI 问题,全局搜索同类一次性修复
|
||||||
|
|
||||||
|
### ⛔ 通用开发流程
|
||||||
|
|
||||||
|
```
|
||||||
|
分析需求 → 写代码 → go build + tsc --noEmit → ./run.sh restart → 浏览器验证 → git commit + push
|
||||||
|
```
|
||||||
|
|
||||||
|
- **修改前端后必须在浏览器实际测试**,不能只说"刷新试试"
|
||||||
|
- **提交前编译验证**:后端 `go build ./...`,前端 `npx tsc --noEmit && npm run build`
|
||||||
|
- **Git 提交**: `git add -A && git commit -m "feat: 描述" && git push origin master`
|
||||||
|
- **开发日志**: 每次开发后更新 `docs/dev-log.md`
|
||||||
|
|
||||||
|
## 架构约束
|
||||||
|
|
||||||
|
### 目录结构(核心部分)
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── cmd/main.go + seed.go # 入口 + 种子数据
|
||||||
|
├── internal/
|
||||||
|
│ ├── config/config.go # Viper 配置
|
||||||
|
│ ├── models/ # GORM 模型(每模块独立文件)
|
||||||
|
│ └── api/
|
||||||
|
│ ├── handlers/ # HTTP handler(按模块拆分,每文件 <400 行)
|
||||||
|
│ ├── middleware/auth.go # JWT + Admin 中间件
|
||||||
|
│ └── routes/routes.go # 路由注册
|
||||||
|
├── pkg/database/database.go # DB 连接 + AutoMigrate
|
||||||
|
└── scripts/mock.go # Mock 种子
|
||||||
|
|
||||||
|
frontend/
|
||||||
|
├── src/
|
||||||
|
│ ├── components/{模块}/ # 页面组件(每文件 <700 行,超出拆子组件)
|
||||||
|
│ ├── services/{api.ts, http.ts} # API 服务层
|
||||||
|
│ ├── store/ # Zustand 状态管理
|
||||||
|
│ ├── hooks/ # React hooks
|
||||||
|
│ └── types/index.ts # 全局类型定义
|
||||||
|
├── App.tsx # 路由 + 顶层 Provider
|
||||||
|
|
||||||
|
agent/ # 监控 Agent(独立 Go module)
|
||||||
|
├── main.go # CLI 入口
|
||||||
|
├── collector/ # /proc 采集器
|
||||||
|
├── task/ # 远程任务执行器
|
||||||
|
└── reporter/http.go # HTTP 上报
|
||||||
|
```
|
||||||
|
|
||||||
|
### API 响应格式
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 统一响应(所有 handler 必须遵循)
|
||||||
|
type Response struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 列表响应(Data 内层)
|
||||||
|
type ListResponse struct {
|
||||||
|
List interface{} `json:"list"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 认证流程
|
||||||
|
|
||||||
|
```
|
||||||
|
Login(本地/LDAP fallback) → JWT Token → 前端 Zustand persist 存储 → http.ts 自动注入 Bearer
|
||||||
|
→ JWTAuth 中间件验证 → 需 admin 权限的路由额外 AdminAuth 中间件
|
||||||
|
```
|
||||||
|
|
||||||
|
### Agent 双通道架构
|
||||||
|
|
||||||
|
```
|
||||||
|
指标通道: ticker(10s) → collect(/proc) → POST /agent/report
|
||||||
|
任务通道: ticker(5s) → GET /agent/tasks/poll → execute → POST /agent/tasks/:id/result
|
||||||
|
```
|
||||||
|
|
||||||
|
### 主题系统
|
||||||
|
|
||||||
|
5 套主题(CSS 变量驱动): `ocean-deep`(默认暗色) · `light-professional`(亮色) · `midnight-purple` · `forest-green` · `dark-rose`
|
||||||
|
所有组件必须用 `var(--dg-xxx)` 变量,禁止硬编码颜色值。
|
||||||
|
|
||||||
|
## 常见陷阱速查
|
||||||
|
|
||||||
|
| # | 陷阱 | 解决 |
|
||||||
|
|---|------|------|
|
||||||
|
| Go1 | go build 超时 | `unset proxy + GOPROXY=goproxy.cn + GOTOOLCHAIN=local` |
|
||||||
|
| Go2 | handler 不包裹 Response | 必须 `models.Response{Code:200, Data:...}` |
|
||||||
|
| Go3 | GORM 指针字段 | `*field` 解引用后再用 |
|
||||||
|
| Go4 | mock.go 重运行 | UNIQUE constraint → 用 API 注入新数据 |
|
||||||
|
| FE1 | 白屏无堆栈 | 90% 是列表 `{list,total}` 未解包 |
|
||||||
|
| FE2 | confirm() 冻结自动化 | 用 `useConfirm()` |
|
||||||
|
| FE3 | Token 获取 | `useUserStore.getState().token`,不是 localStorage |
|
||||||
|
| FE4 | Radix Dialog 警告 | 必须有 `<DialogDescription>` |
|
||||||
|
| FE5 | browser_click 不触发 toggle | 改用 `browser_console` 注入 `.click()` |
|
||||||
|
|
||||||
|
## 文件大小监控
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 检查超限文件(CI 检查脚本)
|
||||||
|
find backend -name "*.go" -not -path "*/vendor/*" | xargs wc -l | awk '$1 > 400 && $2 != "total"'
|
||||||
|
find frontend/src -name "*.tsx" -o -name "*.ts" | xargs wc -l | awk '$1 > 700 && $2 != "total"'
|
||||||
|
```
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,343 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListCronJobs 获取定时任务列表
|
||||||
|
// @Summary 获取定时任务列表
|
||||||
|
// @Description 获取所有定时任务列表
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /cron-jobs [get]
|
||||||
|
func (h *AutomationHandler) ListCronJobs(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
c.ShouldBindQuery(&query)
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
h.db.Model(&models.CronJob{}).Count(&total)
|
||||||
|
|
||||||
|
var jobs []models.CronJob
|
||||||
|
h.db.Preload("Script").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&jobs)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: jobs,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCronJob 获取定时任务详情
|
||||||
|
// @Summary 获取定时任务详情
|
||||||
|
// @Description 获取指定定时任务的详细信息
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "任务ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CronJob}
|
||||||
|
// @Router /cron-jobs/{id} [get]
|
||||||
|
func (h *AutomationHandler) GetCronJob(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var job models.CronJob
|
||||||
|
if err := h.db.Preload("Script").First(&job, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "定时任务不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: job,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCronJob 创建定时任务
|
||||||
|
// @Summary 创建定时任务
|
||||||
|
// @Description 创建新定时任务
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body models.CreateCronJobRequest true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CronJob}
|
||||||
|
// @Router /cron-jobs [post]
|
||||||
|
func (h *AutomationHandler) CreateCronJob(c *gin.Context) {
|
||||||
|
var req models.CreateCronJobRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
job := models.CronJob{
|
||||||
|
Name: req.Name,
|
||||||
|
Description: req.Description,
|
||||||
|
CronExpr: req.CronExpr,
|
||||||
|
Type: req.Type,
|
||||||
|
Content: req.Content,
|
||||||
|
ScriptID: req.ScriptID,
|
||||||
|
TargetType: req.TargetType,
|
||||||
|
Timeout: req.Timeout,
|
||||||
|
NotifyOn: req.NotifyOn,
|
||||||
|
Enabled: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if job.Timeout == 0 {
|
||||||
|
job.Timeout = 300
|
||||||
|
}
|
||||||
|
if job.NotifyOn == "" {
|
||||||
|
job.NotifyOn = "failure"
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&job).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: job,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCronJob 更新定时任务
|
||||||
|
// @Summary 更新定时任务
|
||||||
|
// @Description 更新指定定时任务
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "任务ID"
|
||||||
|
// @Param request body models.CreateCronJobRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CronJob}
|
||||||
|
// @Router /cron-jobs/{id} [put]
|
||||||
|
func (h *AutomationHandler) UpdateCronJob(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var req models.CreateCronJobRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var job models.CronJob
|
||||||
|
if err := h.db.First(&job, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "定时任务不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"name": req.Name,
|
||||||
|
"description": req.Description,
|
||||||
|
"cron_expr": req.CronExpr,
|
||||||
|
"type": req.Type,
|
||||||
|
"content": req.Content,
|
||||||
|
"script_id": req.ScriptID,
|
||||||
|
"target_type": req.TargetType,
|
||||||
|
"timeout": req.Timeout,
|
||||||
|
"notify_on": req.NotifyOn,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Model(&job).Updates(updates).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.Preload("Script").First(&job, id)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: job,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCronJob 删除定时任务
|
||||||
|
// @Summary 删除定时任务
|
||||||
|
// @Description 删除指定定时任务
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "任务ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /cron-jobs/{id} [delete]
|
||||||
|
func (h *AutomationHandler) DeleteCronJob(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.CronJob{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToggleCronJob 切换定时任务状态
|
||||||
|
// @Summary 切换定时任务状态
|
||||||
|
// @Description 启用或禁用定时任务
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "任务ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CronJob}
|
||||||
|
// @Router /cron-jobs/{id}/toggle [post]
|
||||||
|
func (h *AutomationHandler) ToggleCronJob(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var job models.CronJob
|
||||||
|
if err := h.db.First(&job, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "定时任务不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
job.Enabled = !job.Enabled
|
||||||
|
if err := h.db.Save(&job).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "操作失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "操作成功",
|
||||||
|
Data: job,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecuteCronJob 执行定时任务
|
||||||
|
// @Summary 执行定时任务
|
||||||
|
// @Description 手动执行定时任务
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "任务ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.TaskExecution}
|
||||||
|
// @Router /cron-jobs/{id}/execute [post]
|
||||||
|
func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var job models.CronJob
|
||||||
|
if err := h.db.First(&job, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "定时任务不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the content to execute. For type=script, load the linked Script.
|
||||||
|
content := job.Content
|
||||||
|
scriptType := "shell"
|
||||||
|
if job.Type == "script" && job.ScriptID != nil {
|
||||||
|
var script models.Script
|
||||||
|
if err := h.db.First(&script, *job.ScriptID).Error; err == nil {
|
||||||
|
content = script.Content
|
||||||
|
scriptType = script.Type
|
||||||
|
h.db.Model(&script).UpdateColumn("run_count", script.RunCount+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
execution := models.TaskExecution{
|
||||||
|
TaskType: "cron",
|
||||||
|
TaskID: uint(id),
|
||||||
|
TaskName: job.Name,
|
||||||
|
Status: "running",
|
||||||
|
TargetType: job.TargetType,
|
||||||
|
Targets: job.Targets,
|
||||||
|
StartedAt: &now,
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&execution).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建执行记录失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute locally on the AIOps host.
|
||||||
|
output, exitCode, duration := runLocal(scriptType, content, job.Timeout)
|
||||||
|
finishedAt := time.Now()
|
||||||
|
status := "success"
|
||||||
|
if exitCode != 0 {
|
||||||
|
status = "failed"
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.Model(&execution).Updates(map[string]interface{}{
|
||||||
|
"status": status,
|
||||||
|
"output": output,
|
||||||
|
"duration": duration,
|
||||||
|
"finished_at": finishedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Update cron job statistics.
|
||||||
|
statsUpdates := map[string]interface{}{
|
||||||
|
"last_run_at": now,
|
||||||
|
"last_status": status,
|
||||||
|
"run_count": job.RunCount + 1,
|
||||||
|
}
|
||||||
|
if status == "success" {
|
||||||
|
statsUpdates["success_count"] = job.SuccessCount + 1
|
||||||
|
} else {
|
||||||
|
statsUpdates["fail_count"] = job.FailCount + 1
|
||||||
|
}
|
||||||
|
h.db.Model(&job).Updates(statsUpdates)
|
||||||
|
|
||||||
|
execution.Output = output
|
||||||
|
execution.Status = status
|
||||||
|
execution.Duration = duration
|
||||||
|
execution.FinishedAt = &finishedAt
|
||||||
|
|
||||||
|
msg := "执行成功"
|
||||||
|
if status == "failed" {
|
||||||
|
msg = "执行失败"
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: msg,
|
||||||
|
Data: execution,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runPlaybookLocal executes an Ansible playbook YAML locally on the AIOps host.
|
||||||
|
// It writes the content to a temporary file and invokes `ansible-playbook`
|
||||||
|
// against localhost with a local connection. If the ansible-playbook binary is
|
||||||
|
// missing the exec error is captured in the output. Returns combined
|
||||||
|
// stdout+stderr, the exit code (-1 on failure) and duration in milliseconds.
|
||||||
|
func runPlaybookLocal(content, inventory string, timeoutSec int) (output string, exitCode int, durationMs int) {
|
||||||
|
start := time.Now()
|
||||||
|
timeout := time.Duration(timeoutSec) * time.Second
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = 600 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the playbook YAML to a temporary file.
|
||||||
|
tmpFile, err := os.CreateTemp("", "ezops-playbook-*.yml")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("创建临时文件失败: %v", err), -1, 0
|
||||||
|
}
|
||||||
|
defer os.Remove(tmpFile.Name())
|
||||||
|
if _, err := tmpFile.WriteString(content); err != nil {
|
||||||
|
tmpFile.Close()
|
||||||
|
return fmt.Sprintf("写入临时文件失败: %v", err), -1, 0
|
||||||
|
}
|
||||||
|
tmpFile.Close()
|
||||||
|
|
||||||
|
// Write an optional inventory file.
|
||||||
|
inventoryArg := "localhost,"
|
||||||
|
if inventory != "" {
|
||||||
|
invFile, err := os.CreateTemp("", "ezops-inventory-*.ini")
|
||||||
|
if err == nil {
|
||||||
|
if _, werr := invFile.WriteString(inventory); werr == nil {
|
||||||
|
inventoryArg = invFile.Name()
|
||||||
|
defer os.Remove(invFile.Name())
|
||||||
|
}
|
||||||
|
invFile.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
args := []string{"-i", inventoryArg}
|
||||||
|
if inventoryArg == "localhost," {
|
||||||
|
args = append(args, "--connection=local")
|
||||||
|
}
|
||||||
|
args = append(args, tmpFile.Name())
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, "ansible-playbook", args...)
|
||||||
|
var out bytes.Buffer
|
||||||
|
cmd.Stdout = &out
|
||||||
|
cmd.Stderr = &out
|
||||||
|
runErr := cmd.Run()
|
||||||
|
|
||||||
|
durationMs = int(time.Since(start).Milliseconds())
|
||||||
|
output = out.String()
|
||||||
|
|
||||||
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
|
output += fmt.Sprintf("\n[超时] 执行超过 %d 秒被终止", timeoutSec)
|
||||||
|
return output, -1, durationMs
|
||||||
|
}
|
||||||
|
if runErr != nil {
|
||||||
|
if exitError, ok := runErr.(*exec.ExitError); ok {
|
||||||
|
exitCode = exitError.ExitCode()
|
||||||
|
} else {
|
||||||
|
// Binary not found or other exec error (e.g. ansible-playbook not
|
||||||
|
// installed). Provide a clear hint instead of an empty output.
|
||||||
|
exitCode = -1
|
||||||
|
if output == "" {
|
||||||
|
output = fmt.Sprintf("无法执行 ansible-playbook:%v\n(请确认 AIOps 主机已安装 ansible:yum install -y ansible / pip install ansible)", runErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output, exitCode, durationMs
|
||||||
|
}
|
||||||
|
return output, 0, durationMs
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPlaybooks 获取Playbook列表
|
||||||
|
// @Summary 获取Playbook列表
|
||||||
|
// @Description 获取所有Ansible Playbook列表
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /playbooks [get]
|
||||||
|
func (h *AutomationHandler) ListPlaybooks(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
c.ShouldBindQuery(&query)
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
h.db.Model(&models.Playbook{}).Count(&total)
|
||||||
|
|
||||||
|
var playbooks []models.Playbook
|
||||||
|
h.db.Order("created_at DESC").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&playbooks)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: playbooks,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPlaybook 获取Playbook详情
|
||||||
|
// @Summary 获取Playbook详情
|
||||||
|
// @Description 获取指定Playbook的详细信息
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "Playbook ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Playbook}
|
||||||
|
// @Router /playbooks/{id} [get]
|
||||||
|
func (h *AutomationHandler) GetPlaybook(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var playbook models.Playbook
|
||||||
|
if err := h.db.First(&playbook, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "Playbook不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: playbook,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreatePlaybook 创建Playbook
|
||||||
|
// @Summary 创建Playbook
|
||||||
|
// @Description 创建新的Ansible Playbook
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body models.CreatePlaybookRequest true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Playbook}
|
||||||
|
// @Router /playbooks [post]
|
||||||
|
func (h *AutomationHandler) CreatePlaybook(c *gin.Context) {
|
||||||
|
var req models.CreatePlaybookRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
playbook := models.Playbook{
|
||||||
|
Name: req.Name,
|
||||||
|
Code: randomCode("pb"),
|
||||||
|
Description: req.Description,
|
||||||
|
Content: req.Content,
|
||||||
|
Category: req.Category,
|
||||||
|
Tags: req.Tags,
|
||||||
|
Variables: req.Variables,
|
||||||
|
Inventory: req.Inventory,
|
||||||
|
Timeout: req.Timeout,
|
||||||
|
}
|
||||||
|
if playbook.Category == "" {
|
||||||
|
playbook.Category = "deployment"
|
||||||
|
}
|
||||||
|
if playbook.Timeout == 0 {
|
||||||
|
playbook.Timeout = 600
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&playbook).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建失败: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: playbook,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePlaybook 更新Playbook
|
||||||
|
// @Summary 更新Playbook
|
||||||
|
// @Description 更新指定Playbook
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "Playbook ID"
|
||||||
|
// @Param request body models.CreatePlaybookRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Playbook}
|
||||||
|
// @Router /playbooks/{id} [put]
|
||||||
|
func (h *AutomationHandler) UpdatePlaybook(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var req models.CreatePlaybookRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var playbook models.Playbook
|
||||||
|
if err := h.db.First(&playbook, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "Playbook不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"name": req.Name,
|
||||||
|
"description": req.Description,
|
||||||
|
"content": req.Content,
|
||||||
|
"category": req.Category,
|
||||||
|
"tags": req.Tags,
|
||||||
|
"variables": req.Variables,
|
||||||
|
"inventory": req.Inventory,
|
||||||
|
"timeout": req.Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Model(&playbook).Updates(updates).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.First(&playbook, id)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: playbook,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletePlaybook 删除Playbook
|
||||||
|
// @Summary 删除Playbook
|
||||||
|
// @Description 删除指定Playbook
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "Playbook ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /playbooks/{id} [delete]
|
||||||
|
func (h *AutomationHandler) DeletePlaybook(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.Playbook{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecutePlaybook 执行Playbook
|
||||||
|
// @Summary 执行Playbook
|
||||||
|
// @Description 在AIOps主机上本地执行Ansible Playbook
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "Playbook ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.TaskExecution}
|
||||||
|
// @Router /playbooks/{id}/execute [post]
|
||||||
|
func (h *AutomationHandler) ExecutePlaybook(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var playbook models.Playbook
|
||||||
|
if err := h.db.First(&playbook, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "Playbook不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
execution := models.TaskExecution{
|
||||||
|
TaskType: "playbook",
|
||||||
|
TaskID: uint(id),
|
||||||
|
TaskName: playbook.Name,
|
||||||
|
Status: "running",
|
||||||
|
StartedAt: &now,
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&execution).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建执行记录失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute the playbook locally on the AIOps host.
|
||||||
|
output, exitCode, duration := runPlaybookLocal(playbook.Content, playbook.Inventory, playbook.Timeout)
|
||||||
|
finishedAt := time.Now()
|
||||||
|
status := "success"
|
||||||
|
if exitCode != 0 {
|
||||||
|
status = "failed"
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.Model(&execution).Updates(map[string]interface{}{
|
||||||
|
"status": status,
|
||||||
|
"output": output,
|
||||||
|
"duration": duration,
|
||||||
|
"finished_at": finishedAt,
|
||||||
|
})
|
||||||
|
h.db.Model(&playbook).UpdateColumn("run_count", playbook.RunCount+1)
|
||||||
|
|
||||||
|
execution.Output = output
|
||||||
|
execution.Status = status
|
||||||
|
execution.Duration = duration
|
||||||
|
execution.FinishedAt = &finishedAt
|
||||||
|
|
||||||
|
msg := "执行成功"
|
||||||
|
if status == "failed" {
|
||||||
|
msg = "执行失败"
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: msg,
|
||||||
|
Data: execution,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListScripts 获取脚本列表
|
||||||
|
// @Summary 获取脚本列表
|
||||||
|
// @Description 获取所有脚本列表
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /scripts [get]
|
||||||
|
func (h *AutomationHandler) ListScripts(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
c.ShouldBindQuery(&query)
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
h.db.Model(&models.Script{}).Count(&total)
|
||||||
|
|
||||||
|
var scripts []models.Script
|
||||||
|
h.db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&scripts)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: scripts,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScript 获取脚本详情
|
||||||
|
// @Summary 获取脚本详情
|
||||||
|
// @Description 获取指定脚本的详细信息
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "脚本ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Script}
|
||||||
|
// @Router /scripts/{id} [get]
|
||||||
|
func (h *AutomationHandler) GetScript(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var script models.Script
|
||||||
|
if err := h.db.First(&script, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "脚本不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: script,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateScript 创建脚本
|
||||||
|
// @Summary 创建脚本
|
||||||
|
// @Description 创建新脚本
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body models.CreateScriptRequest true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Script}
|
||||||
|
// @Router /scripts [post]
|
||||||
|
func (h *AutomationHandler) CreateScript(c *gin.Context) {
|
||||||
|
var req models.CreateScriptRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
script := models.Script{
|
||||||
|
Name: req.Name,
|
||||||
|
Code: req.Code,
|
||||||
|
Description: req.Description,
|
||||||
|
Type: req.Type,
|
||||||
|
Content: req.Content,
|
||||||
|
Params: req.Params,
|
||||||
|
Timeout: req.Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
if script.Type == "" {
|
||||||
|
script.Type = "shell"
|
||||||
|
}
|
||||||
|
if script.Timeout == 0 {
|
||||||
|
script.Timeout = 300
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&script).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: script,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateScript 更新脚本
|
||||||
|
// @Summary 更新脚本
|
||||||
|
// @Description 更新指定脚本
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "脚本ID"
|
||||||
|
// @Param request body models.CreateScriptRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Script}
|
||||||
|
// @Router /scripts/{id} [put]
|
||||||
|
func (h *AutomationHandler) UpdateScript(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var req models.CreateScriptRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var script models.Script
|
||||||
|
if err := h.db.First(&script, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "脚本不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"name": req.Name,
|
||||||
|
"description": req.Description,
|
||||||
|
"type": req.Type,
|
||||||
|
"content": req.Content,
|
||||||
|
"params": req.Params,
|
||||||
|
"timeout": req.Timeout,
|
||||||
|
"version": script.Version + 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Model(&script).Updates(updates).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.First(&script, id)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: script,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteScript 删除脚本
|
||||||
|
// @Summary 删除脚本
|
||||||
|
// @Description 删除指定脚本
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "脚本ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /scripts/{id} [delete]
|
||||||
|
func (h *AutomationHandler) DeleteScript(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.Script{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecuteScript 执行脚本
|
||||||
|
// @Summary 执行脚本
|
||||||
|
// @Description 在目标服务器上执行脚本
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "脚本ID"
|
||||||
|
// @Param request body models.ExecuteScriptRequest true "执行请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.TaskExecution}
|
||||||
|
// @Router /scripts/{id}/execute [post]
|
||||||
|
func (h *AutomationHandler) ExecuteScript(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var script models.Script
|
||||||
|
if err := h.db.First(&script, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "脚本不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// The request body is optional — when omitted we execute locally.
|
||||||
|
var req models.ExecuteScriptRequest
|
||||||
|
_ = c.ShouldBindJSON(&req)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
execution := models.TaskExecution{
|
||||||
|
TaskType: "script",
|
||||||
|
TaskID: uint(id),
|
||||||
|
TaskName: script.Name,
|
||||||
|
Status: "running",
|
||||||
|
TargetType: req.TargetType,
|
||||||
|
StartedAt: &now,
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&execution).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建执行记录失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute locally on the AIOps host.
|
||||||
|
output, exitCode, duration := runLocal(script.Type, script.Content, script.Timeout)
|
||||||
|
finishedAt := time.Now()
|
||||||
|
status := "success"
|
||||||
|
if exitCode != 0 {
|
||||||
|
status = "failed"
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.Model(&execution).Updates(map[string]interface{}{
|
||||||
|
"status": status,
|
||||||
|
"output": output,
|
||||||
|
"duration": duration,
|
||||||
|
"finished_at": finishedAt,
|
||||||
|
})
|
||||||
|
h.db.Model(&script).UpdateColumn("run_count", script.RunCount+1)
|
||||||
|
|
||||||
|
execution.Output = output
|
||||||
|
execution.Status = status
|
||||||
|
execution.Duration = duration
|
||||||
|
execution.FinishedAt = &finishedAt
|
||||||
|
|
||||||
|
msg := "执行成功"
|
||||||
|
if status == "failed" {
|
||||||
|
msg = "执行失败"
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: msg,
|
||||||
|
Data: execution,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListExecutions 获取任务执行记录列表
|
||||||
|
// @Summary 获取任务执行记录
|
||||||
|
// @Description 获取脚本/定时任务的执行历史记录(支持 task_type / task_id 筛选)
|
||||||
|
// @Tags 自动化运维
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Param task_type query string false "任务类型 (cron/script)"
|
||||||
|
// @Param task_id query string false "任务ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /task-executions [get]
|
||||||
|
func (h *AutomationHandler) ListExecutions(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
c.ShouldBindQuery(&query)
|
||||||
|
|
||||||
|
db := h.db.Model(&models.TaskExecution{})
|
||||||
|
if taskType := c.Query("task_type"); taskType != "" {
|
||||||
|
db = db.Where("task_type = ?", taskType)
|
||||||
|
}
|
||||||
|
if taskID := c.Query("task_id"); taskID != "" {
|
||||||
|
db = db.Where("task_id = ?", taskID)
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
db.Count(&total)
|
||||||
|
|
||||||
|
var execs []models.TaskExecution
|
||||||
|
db.Order("created_at DESC").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&execs)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: execs,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CloudAccountHandler 云账号处理器
|
||||||
|
type CloudAccountHandler struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCloudAccountHandler 创建云账号处理器
|
||||||
|
func NewCloudAccountHandler(db *gorm.DB) *CloudAccountHandler {
|
||||||
|
return &CloudAccountHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListCloudAccounts 获取云账号列表
|
||||||
|
// @Summary 获取云账号列表
|
||||||
|
// @Description 获取所有云账号列表
|
||||||
|
// @Tags 云账号
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /cloud-accounts [get]
|
||||||
|
func (h *CloudAccountHandler) ListCloudAccounts(c *gin.Context) {
|
||||||
|
var accounts []models.CloudAccount
|
||||||
|
h.db.Find(&accounts)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: accounts,
|
||||||
|
Total: int64(len(accounts)),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// createCloudAccountRequest 创建云账号请求(独立 request struct,避免 CloudAccount.AccessKey/SecretKey 的 json:"-" 导致无法反序列化)
|
||||||
|
type createCloudAccountRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
AccessKey string `json:"access_key"`
|
||||||
|
SecretKey string `json:"secret_key"`
|
||||||
|
MonthlyCost float64 `json:"monthly_cost"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCloudAccount 创建云账号
|
||||||
|
// @Summary 创建云账号
|
||||||
|
// @Description 创建新云账号
|
||||||
|
// @Tags 云账号
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body createCloudAccountRequest true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CloudAccount}
|
||||||
|
// @Router /cloud-accounts [post]
|
||||||
|
func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) {
|
||||||
|
var req createCloudAccountRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Provider) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "账号名称和云平台不能为空",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := strings.TrimSpace(req.Status)
|
||||||
|
if status == "" {
|
||||||
|
status = "active"
|
||||||
|
}
|
||||||
|
|
||||||
|
account := models.CloudAccount{
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Provider: strings.TrimSpace(req.Provider),
|
||||||
|
AccessKey: req.AccessKey,
|
||||||
|
SecretKey: req.SecretKey,
|
||||||
|
MonthlyCost: req.MonthlyCost,
|
||||||
|
Status: status,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&account).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: account,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCloudAccount 更新云账号
|
||||||
|
// @Summary 更新云账号
|
||||||
|
// @Description 更新指定云账号信息
|
||||||
|
// @Tags 云账号
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "云账号ID"
|
||||||
|
// @Param request body createCloudAccountRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.CloudAccount}
|
||||||
|
// @Router /cloud-accounts/{id} [put]
|
||||||
|
func (h *CloudAccountHandler) UpdateCloudAccount(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
var req createCloudAccountRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var account models.CloudAccount
|
||||||
|
if err := h.db.First(&account, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "云账号不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只在提供非空值时更新凭证字段
|
||||||
|
if strings.TrimSpace(req.Name) != "" {
|
||||||
|
account.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Provider) != "" {
|
||||||
|
account.Provider = strings.TrimSpace(req.Provider)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.AccessKey) != "" {
|
||||||
|
account.AccessKey = req.AccessKey
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.SecretKey) != "" {
|
||||||
|
account.SecretKey = req.SecretKey
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Status) != "" {
|
||||||
|
account.Status = strings.TrimSpace(req.Status)
|
||||||
|
}
|
||||||
|
account.MonthlyCost = req.MonthlyCost
|
||||||
|
|
||||||
|
if err := h.db.Save(&account).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: account,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCloudAccount 删除云账号
|
||||||
|
// @Summary 删除云账号
|
||||||
|
// @Description 删除指定云账号
|
||||||
|
// @Tags 云账号
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "云账号ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /cloud-accounts/{id} [delete]
|
||||||
|
func (h *CloudAccountHandler) DeleteCloudAccount(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.CloudAccount{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DomainHandler 域名处理器
|
||||||
|
type DomainHandler struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDomainHandler 创建域名处理器
|
||||||
|
func NewDomainHandler(db *gorm.DB) *DomainHandler {
|
||||||
|
return &DomainHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListDomains 获取域名列表
|
||||||
|
// @Summary 获取域名列表
|
||||||
|
// @Description 获取所有域名列表
|
||||||
|
// @Tags 域名
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Param keyword query string false "搜索关键词"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /domains [get]
|
||||||
|
func (h *DomainHandler) ListDomains(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
c.ShouldBindQuery(&query)
|
||||||
|
|
||||||
|
db := h.db.Model(&models.Domain{})
|
||||||
|
if query.Keyword != "" {
|
||||||
|
db = db.Where("name LIKE ?", "%"+query.Keyword+"%")
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
db.Count(&total)
|
||||||
|
|
||||||
|
var domains []models.Domain
|
||||||
|
db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&domains)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: domains,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateDomain 创建域名
|
||||||
|
// @Summary 创建域名
|
||||||
|
// @Description 创建新域名
|
||||||
|
// @Tags 域名
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body models.Domain true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Domain}
|
||||||
|
// @Router /domains [post]
|
||||||
|
func (h *DomainHandler) CreateDomain(c *gin.Context) {
|
||||||
|
var req updateDomainRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Name) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "域名不能为空",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := req.Status
|
||||||
|
if status == "" {
|
||||||
|
status = "active"
|
||||||
|
}
|
||||||
|
|
||||||
|
domain := models.Domain{
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Registrar: req.Registrar,
|
||||||
|
Status: status,
|
||||||
|
ExpireDate: parseDateStr(req.ExpireDate),
|
||||||
|
DNSProvider: req.DNSProvider,
|
||||||
|
RecordCount: req.RecordCount,
|
||||||
|
SSLEnabled: req.SSLEnabled,
|
||||||
|
SSLExpireDate: parseDateStr(req.SSLExpireDate),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&domain).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: domain,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateDomainRequest 域名创建/更新请求(日期字段用字符串接收,避免 RFC3339 解析失败)
|
||||||
|
type updateDomainRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Registrar string `json:"registrar"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
ExpireDate string `json:"expire_date"`
|
||||||
|
DNSProvider string `json:"dns_provider"`
|
||||||
|
RecordCount int `json:"record_count"`
|
||||||
|
SSLEnabled bool `json:"ssl_enabled"`
|
||||||
|
SSLExpireDate string `json:"ssl_expire_date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseDateStr 将 YYYY-MM-DD 格式字符串解析为 *time.Time,空串返回 nil
|
||||||
|
func parseDateStr(s string) *time.Time {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
t, err := time.Parse("2006-01-02", s)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteDomain 删除域名
|
||||||
|
// @Summary 删除域名
|
||||||
|
// @Description 删除指定域名
|
||||||
|
// @Tags 域名
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "域名ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /domains/{id} [delete]
|
||||||
|
func (h *DomainHandler) DeleteDomain(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.Domain{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateDomain 更新域名
|
||||||
|
// @Summary 更新域名
|
||||||
|
// @Description 更新指定域名信息
|
||||||
|
// @Tags 域名
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "域名ID"
|
||||||
|
// @Param request body updateDomainRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.Domain}
|
||||||
|
// @Router /domains/{id} [put]
|
||||||
|
func (h *DomainHandler) UpdateDomain(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
var req updateDomainRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var domain models.Domain
|
||||||
|
if err := h.db.First(&domain, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "域名不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Name) != "" {
|
||||||
|
domain.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
domain.Registrar = req.Registrar
|
||||||
|
domain.Status = req.Status
|
||||||
|
if domain.Status == "" {
|
||||||
|
domain.Status = "active"
|
||||||
|
}
|
||||||
|
domain.ExpireDate = parseDateStr(req.ExpireDate)
|
||||||
|
domain.DNSProvider = req.DNSProvider
|
||||||
|
domain.RecordCount = req.RecordCount
|
||||||
|
domain.SSLEnabled = req.SSLEnabled
|
||||||
|
domain.SSLExpireDate = parseDateStr(req.SSLExpireDate)
|
||||||
|
|
||||||
|
if err := h.db.Save(&domain).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: domain,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ==================== 云平台(Platform / Cloud)====================
|
||||||
|
|
||||||
|
// PlatformHandler 云平台处理器
|
||||||
|
type PlatformHandler struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPlatformHandler(db *gorm.DB) *PlatformHandler {
|
||||||
|
return &PlatformHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// platformRequest 云平台创建/更新请求
|
||||||
|
type platformRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Website string `json:"website"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPlatforms 获取云平台列表
|
||||||
|
func (h *PlatformHandler) ListPlatforms(c *gin.Context) {
|
||||||
|
var platforms []models.Cloud
|
||||||
|
h.db.Find(&platforms)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: platforms,
|
||||||
|
Total: int64(len(platforms)),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreatePlatform 创建云平台
|
||||||
|
func (h *PlatformHandler) CreatePlatform(c *gin.Context) {
|
||||||
|
var req platformRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "平台名称和编码不能为空"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cloudType := strings.TrimSpace(req.Type)
|
||||||
|
if cloudType == "" {
|
||||||
|
cloudType = "public"
|
||||||
|
}
|
||||||
|
status := strings.TrimSpace(req.Status)
|
||||||
|
if status == "" {
|
||||||
|
status = "active"
|
||||||
|
}
|
||||||
|
|
||||||
|
platform := models.Cloud{
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Code: strings.TrimSpace(req.Code),
|
||||||
|
Type: cloudType,
|
||||||
|
Status: status,
|
||||||
|
Website: req.Website,
|
||||||
|
Description: req.Description,
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&platform).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: platform})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePlatform 更新云平台
|
||||||
|
func (h *PlatformHandler) UpdatePlatform(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
var req platformRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var platform models.Cloud
|
||||||
|
if err := h.db.First(&platform, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云平台不存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Name) != "" {
|
||||||
|
platform.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Code) != "" {
|
||||||
|
platform.Code = strings.TrimSpace(req.Code)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Type) != "" {
|
||||||
|
platform.Type = strings.TrimSpace(req.Type)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Status) != "" {
|
||||||
|
platform.Status = strings.TrimSpace(req.Status)
|
||||||
|
}
|
||||||
|
platform.Website = req.Website
|
||||||
|
platform.Description = req.Description
|
||||||
|
|
||||||
|
if err := h.db.Save(&platform).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: platform})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletePlatform 删除云平台
|
||||||
|
func (h *PlatformHandler) DeletePlatform(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
if err := h.db.Delete(&models.Cloud{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ==================== 区域管理(Region)====================
|
||||||
|
|
||||||
|
// RegionHandler 区域处理器
|
||||||
|
type RegionHandler struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegionHandler(db *gorm.DB) *RegionHandler {
|
||||||
|
return &RegionHandler{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// regionRequest 区域创建/更新请求
|
||||||
|
type regionRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
Location string `json:"location"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Endpoint string `json:"endpoint"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRegions 获取区域列表
|
||||||
|
func (h *RegionHandler) ListRegions(c *gin.Context) {
|
||||||
|
var regions []models.Region
|
||||||
|
h.db.Find(®ions)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: regions,
|
||||||
|
Total: int64(len(regions)),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateRegion 创建区域
|
||||||
|
func (h *RegionHandler) CreateRegion(c *gin.Context) {
|
||||||
|
var req regionRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "区域名称和编码不能为空"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := strings.TrimSpace(req.Status)
|
||||||
|
if status == "" {
|
||||||
|
status = "active"
|
||||||
|
}
|
||||||
|
|
||||||
|
region := models.Region{
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Code: strings.TrimSpace(req.Code),
|
||||||
|
Provider: strings.TrimSpace(req.Provider),
|
||||||
|
Location: req.Location,
|
||||||
|
Status: status,
|
||||||
|
Endpoint: req.Endpoint,
|
||||||
|
}
|
||||||
|
if err := h.db.Create(®ion).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: region})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateRegion 更新区域
|
||||||
|
func (h *RegionHandler) UpdateRegion(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
var req regionRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var region models.Region
|
||||||
|
if err := h.db.First(®ion, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "区域不存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Name) != "" {
|
||||||
|
region.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Code) != "" {
|
||||||
|
region.Code = strings.TrimSpace(req.Code)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Provider) != "" {
|
||||||
|
region.Provider = strings.TrimSpace(req.Provider)
|
||||||
|
}
|
||||||
|
region.Location = req.Location
|
||||||
|
if strings.TrimSpace(req.Status) != "" {
|
||||||
|
region.Status = strings.TrimSpace(req.Status)
|
||||||
|
}
|
||||||
|
region.Endpoint = req.Endpoint
|
||||||
|
|
||||||
|
if err := h.db.Save(®ion).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: region})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteRegion 删除区域
|
||||||
|
func (h *RegionHandler) DeleteRegion(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
if err := h.db.Delete(&models.Region{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
||||||
|
}
|
||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/go-ldap/ldap/v3"
|
"github.com/go-ldap/ldap/v3"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -318,498 +317,3 @@ func (h *LDAPHandler) TestLDAPConnection(c *gin.Context) {
|
|||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"success": true, "message": "LDAP连接成功,管理员认证通过"}})
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"success": true, "message": "LDAP连接成功,管理员认证通过"}})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListLDAPUsers 列出LDAP用户
|
|
||||||
// POST /api/v1/admin/ldap-config/users
|
|
||||||
func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
OuDn string `json:"ou_dn"`
|
|
||||||
}
|
|
||||||
c.ShouldBindJSON(&req)
|
|
||||||
|
|
||||||
var cfg models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").First(&cfg).Error; err != nil {
|
|
||||||
c.JSON(http.StatusOK, []interface{}{})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := dialLDAP(&cfg)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, []interface{}{})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusOK, []interface{}{})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
searchBase := cfg.BaseDN
|
|
||||||
if req.OuDn != "" {
|
|
||||||
searchBase = req.OuDn
|
|
||||||
}
|
|
||||||
|
|
||||||
baseFilter := "(objectClass=inetOrgPerson)"
|
|
||||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
|
||||||
sf := *cfg.SearchFilter
|
|
||||||
if strings.Contains(sf, "%s") {
|
|
||||||
baseFilter = strings.ReplaceAll(sf, "%s", "*")
|
|
||||||
} else {
|
|
||||||
baseFilter = sf
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
||||||
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
||||||
200, 0, false, baseFilter,
|
|
||||||
[]string{"uid", "cn", "mail", "dn", "telephoneNumber", "title", "department"},
|
|
||||||
nil,
|
|
||||||
))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, []interface{}{})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type LdapUser struct {
|
|
||||||
DN string `json:"dn"`
|
|
||||||
UID string `json:"uid"`
|
|
||||||
CN string `json:"cn"`
|
|
||||||
Mail string `json:"mail"`
|
|
||||||
Phone string `json:"phone"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Department string `json:"department"`
|
|
||||||
}
|
|
||||||
var users []LdapUser
|
|
||||||
for _, e := range sr.Entries {
|
|
||||||
users = append(users, LdapUser{
|
|
||||||
DN: e.DN,
|
|
||||||
UID: e.GetAttributeValue("uid"),
|
|
||||||
CN: e.GetAttributeValue("cn"),
|
|
||||||
Mail: e.GetAttributeValue("mail"),
|
|
||||||
Phone: e.GetAttributeValue("telephoneNumber"),
|
|
||||||
Title: e.GetAttributeValue("title"),
|
|
||||||
Department: e.GetAttributeValue("department"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: users})
|
|
||||||
}
|
|
||||||
|
|
||||||
// BatchImportLDAP 批量导入LDAP用户
|
|
||||||
// POST /api/v1/admin/ldap-config/import
|
|
||||||
func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
Users []struct {
|
|
||||||
UID string `json:"uid"`
|
|
||||||
CN string `json:"cn"`
|
|
||||||
Mail string `json:"mail"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
Nickname string `json:"nickname"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
} `json:"users"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
imported := 0
|
|
||||||
skipped := 0
|
|
||||||
for _, lu := range req.Users {
|
|
||||||
uid := lu.UID
|
|
||||||
if uid == "" {
|
|
||||||
uid = lu.Username
|
|
||||||
}
|
|
||||||
cn := lu.CN
|
|
||||||
if cn == "" {
|
|
||||||
cn = lu.Nickname
|
|
||||||
}
|
|
||||||
mail := lu.Mail
|
|
||||||
if mail == "" {
|
|
||||||
mail = lu.Email
|
|
||||||
}
|
|
||||||
if uid == "" {
|
|
||||||
skipped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Check if already exists
|
|
||||||
var existing models.User
|
|
||||||
if err := h.db.Where("username = ?", uid).First(&existing).Error; err == nil {
|
|
||||||
// Already exists, update info
|
|
||||||
updates := map[string]interface{}{
|
|
||||||
"auth_source": "ldap",
|
|
||||||
}
|
|
||||||
if cn != "" {
|
|
||||||
updates["real_name"] = cn
|
|
||||||
}
|
|
||||||
if mail != "" {
|
|
||||||
updates["email"] = mail
|
|
||||||
}
|
|
||||||
h.db.Model(&existing).Updates(updates)
|
|
||||||
imported++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create new LDAP user
|
|
||||||
user := models.User{
|
|
||||||
Username: uid,
|
|
||||||
Password: "-", // LDAP users don't have local password
|
|
||||||
RealName: cn,
|
|
||||||
Email: mail,
|
|
||||||
Status: 1,
|
|
||||||
AuthSource: "ldap",
|
|
||||||
}
|
|
||||||
if err := h.db.Create(&user).Error; err != nil {
|
|
||||||
skipped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
imported++
|
|
||||||
}
|
|
||||||
|
|
||||||
// bcrypt import to avoid unused import error
|
|
||||||
_ = bcrypt.MinCost
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: fmt.Sprintf("导入完成: %d 个用户成功, %d 个跳过", imported, skipped),
|
|
||||||
Data: gin.H{"imported": imported, "skipped": skipped},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListLDAPOUs 列出 LDAP 组织单元
|
|
||||||
// POST /api/v1/admin/ldap-config/ou-list
|
|
||||||
func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) {
|
|
||||||
var configs []models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cfg := configs[0]
|
|
||||||
port := 389
|
|
||||||
if cfg.LDAPPort != nil {
|
|
||||||
port = *cfg.LDAPPort
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
conn.SetTimeout(5 * time.Second)
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
searchReq := ldap.NewSearchRequest(
|
|
||||||
cfg.BaseDN,
|
|
||||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
|
||||||
"(objectClass=organizationalUnit)",
|
|
||||||
[]string{"ou", "description"},
|
|
||||||
nil,
|
|
||||||
)
|
|
||||||
sr, err := conn.Search(searchReq)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type OU struct {
|
|
||||||
DN string `json:"dn"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
}
|
|
||||||
var ous []OU
|
|
||||||
for _, e := range sr.Entries {
|
|
||||||
ous = append(ous, OU{
|
|
||||||
DN: e.DN,
|
|
||||||
Name: e.GetAttributeValue("ou"),
|
|
||||||
Description: e.GetAttributeValue("description"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Data: ous})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateLDAPOU 创建组织单元
|
|
||||||
// POST /api/v1/admin/ldap-config/create-ou
|
|
||||||
func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
OUName string `json:"ou_name"`
|
|
||||||
ParentDN string `json:"parent_dn"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var configs []models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cfg := configs[0]
|
|
||||||
port := 389
|
|
||||||
if cfg.LDAPPort != nil {
|
|
||||||
port = *cfg.LDAPPort
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.ParentDN == "" {
|
|
||||||
req.ParentDN = cfg.BaseDN
|
|
||||||
}
|
|
||||||
ouDN := fmt.Sprintf("ou=%s,%s", ldap.EscapeFilter(req.OUName), req.ParentDN)
|
|
||||||
|
|
||||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
conn.SetTimeout(5 * time.Second)
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addReq := ldap.NewAddRequest(ouDN, nil)
|
|
||||||
addReq.Attribute("objectClass", []string{"organizationalUnit", "top"})
|
|
||||||
addReq.Attribute("ou", []string{req.OUName})
|
|
||||||
if req.Description != "" {
|
|
||||||
addReq.Attribute("description", []string{req.Description})
|
|
||||||
}
|
|
||||||
if err := conn.Add(addReq); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建OU失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "OU创建成功", Data: gin.H{"dn": ouDN}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateLDAPUser 在LDAP中创建用户
|
|
||||||
// POST /api/v1/admin/ldap-config/create-user
|
|
||||||
func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
DisplayName string `json:"display_name"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
OUDN string `json:"ou_dn"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if req.Username == "" || req.Password == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "用户名和密码不能为空"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var configs []models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cfg := configs[0]
|
|
||||||
port := 389
|
|
||||||
if cfg.LDAPPort != nil {
|
|
||||||
port = *cfg.LDAPPort
|
|
||||||
}
|
|
||||||
if req.OUDN == "" {
|
|
||||||
req.OUDN = cfg.BaseDN
|
|
||||||
}
|
|
||||||
userDN := fmt.Sprintf("uid=%s,%s", ldap.EscapeFilter(req.Username), req.OUDN)
|
|
||||||
|
|
||||||
// Parse user mapping
|
|
||||||
mapping := map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
|
||||||
if cfg.UserMapping != nil {
|
|
||||||
_ = json.Unmarshal([]byte(*cfg.UserMapping), &mapping)
|
|
||||||
}
|
|
||||||
|
|
||||||
uidAttr := mapping["username"]
|
|
||||||
if uidAttr == "" {
|
|
||||||
uidAttr = "uid"
|
|
||||||
}
|
|
||||||
mailAttr := mapping["email"]
|
|
||||||
if mailAttr == "" {
|
|
||||||
mailAttr = "mail"
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
conn.SetTimeout(5 * time.Second)
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addReq := ldap.NewAddRequest(userDN, nil)
|
|
||||||
addReq.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
|
|
||||||
addReq.Attribute(uidAttr, []string{req.Username})
|
|
||||||
addReq.Attribute("cn", []string{req.DisplayName})
|
|
||||||
addReq.Attribute("sn", []string{req.DisplayName})
|
|
||||||
if req.Email != "" {
|
|
||||||
addReq.Attribute(mailAttr, []string{req.Email})
|
|
||||||
}
|
|
||||||
addReq.Attribute("userPassword", []string{req.Password})
|
|
||||||
if err := conn.Add(addReq); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建用户失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "用户创建成功", Data: gin.H{"dn": userDN}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteLDAPUser 删除LDAP条目(用户或OU)
|
|
||||||
// POST /api/v1/admin/ldap-config/delete-user
|
|
||||||
func (h *LDAPHandler) DeleteLDAPUser(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
DN string `json:"dn"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var configs []models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cfg := configs[0]
|
|
||||||
port := 389
|
|
||||||
if cfg.LDAPPort != nil {
|
|
||||||
port = *cfg.LDAPPort
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
conn.SetTimeout(5 * time.Second)
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
delReq := ldap.NewDelRequest(req.DN, nil)
|
|
||||||
if err := conn.Del(delReq); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateLDAPUser 修改 LDAP 用户属性
|
|
||||||
// POST /api/v1/admin/ldap-config/update-user
|
|
||||||
func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
DN string `json:"dn"`
|
|
||||||
CN string `json:"cn"`
|
|
||||||
Mail string `json:"mail"`
|
|
||||||
Phone string `json:"phone"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var configs []models.LDAPConfig
|
|
||||||
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cfg := configs[0]
|
|
||||||
port := 389
|
|
||||||
if cfg.LDAPPort != nil {
|
|
||||||
port = *cfg.LDAPPort
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
conn.SetTimeout(5 * time.Second)
|
|
||||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 先查当前值,做 diff
|
|
||||||
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
||||||
req.DN, ldap.ScopeBaseObject, ldap.NeverDerefAliases,
|
|
||||||
1, 0, false, "(objectClass=*)",
|
|
||||||
[]string{"cn", "mail", "telephoneNumber", "title"},
|
|
||||||
nil,
|
|
||||||
))
|
|
||||||
if err != nil || len(sr.Entries) == 0 {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "用户不存在"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
entry := sr.Entries[0]
|
|
||||||
|
|
||||||
modReq := ldap.NewModifyRequest(req.DN, nil)
|
|
||||||
|
|
||||||
// cn
|
|
||||||
oldCN := entry.GetAttributeValue("cn")
|
|
||||||
if req.CN != "" && req.CN != oldCN {
|
|
||||||
modReq.Replace("cn", []string{req.CN})
|
|
||||||
modReq.Replace("sn", []string{req.CN}) // sn 同步更新
|
|
||||||
}
|
|
||||||
// mail
|
|
||||||
oldMail := entry.GetAttributeValue("mail")
|
|
||||||
if req.Mail != oldMail {
|
|
||||||
if req.Mail == "" {
|
|
||||||
oldVals := entry.GetAttributeValues("mail")
|
|
||||||
if len(oldVals) > 0 {
|
|
||||||
modReq.Delete("mail", oldVals)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
modReq.Replace("mail", []string{req.Mail})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// telephoneNumber
|
|
||||||
oldPhone := entry.GetAttributeValue("telephoneNumber")
|
|
||||||
if req.Phone != oldPhone {
|
|
||||||
if req.Phone == "" {
|
|
||||||
oldVals := entry.GetAttributeValues("telephoneNumber")
|
|
||||||
if len(oldVals) > 0 {
|
|
||||||
modReq.Delete("telephoneNumber", oldVals)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
modReq.Replace("telephoneNumber", []string{req.Phone})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// title
|
|
||||||
oldTitle := entry.GetAttributeValue("title")
|
|
||||||
if req.Title != oldTitle {
|
|
||||||
if req.Title == "" {
|
|
||||||
oldVals := entry.GetAttributeValues("title")
|
|
||||||
if len(oldVals) > 0 {
|
|
||||||
modReq.Delete("title", oldVals)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
modReq.Replace("title", []string{req.Title})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(modReq.Changes) > 0 {
|
|
||||||
if err := conn.Modify(modReq); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "修改失败: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "修改成功"})
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/go-ldap/ldap/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListLDAPOUs 列出 LDAP 组织单元
|
||||||
|
// POST /api/v1/admin/ldap-config/ou-list
|
||||||
|
func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) {
|
||||||
|
var configs []models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := configs[0]
|
||||||
|
port := 389
|
||||||
|
if cfg.LDAPPort != nil {
|
||||||
|
port = *cfg.LDAPPort
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetTimeout(5 * time.Second)
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
searchReq := ldap.NewSearchRequest(
|
||||||
|
cfg.BaseDN,
|
||||||
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
|
"(objectClass=organizationalUnit)",
|
||||||
|
[]string{"ou", "description"},
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
sr, err := conn.Search(searchReq)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type OU struct {
|
||||||
|
DN string `json:"dn"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
var ous []OU
|
||||||
|
for _, e := range sr.Entries {
|
||||||
|
ous = append(ous, OU{
|
||||||
|
DN: e.DN,
|
||||||
|
Name: e.GetAttributeValue("ou"),
|
||||||
|
Description: e.GetAttributeValue("description"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: ous})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLDAPOU 创建组织单元
|
||||||
|
// POST /api/v1/admin/ldap-config/create-ou
|
||||||
|
func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
OUName string `json:"ou_name"`
|
||||||
|
ParentDN string `json:"parent_dn"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs []models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := configs[0]
|
||||||
|
port := 389
|
||||||
|
if cfg.LDAPPort != nil {
|
||||||
|
port = *cfg.LDAPPort
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.ParentDN == "" {
|
||||||
|
req.ParentDN = cfg.BaseDN
|
||||||
|
}
|
||||||
|
ouDN := fmt.Sprintf("ou=%s,%s", ldap.EscapeFilter(req.OUName), req.ParentDN)
|
||||||
|
|
||||||
|
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetTimeout(5 * time.Second)
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addReq := ldap.NewAddRequest(ouDN, nil)
|
||||||
|
addReq.Attribute("objectClass", []string{"organizationalUnit", "top"})
|
||||||
|
addReq.Attribute("ou", []string{req.OUName})
|
||||||
|
if req.Description != "" {
|
||||||
|
addReq.Attribute("description", []string{req.Description})
|
||||||
|
}
|
||||||
|
if err := conn.Add(addReq); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建OU失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "OU创建成功", Data: gin.H{"dn": ouDN}})
|
||||||
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/go-ldap/ldap/v3"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListLDAPUsers 列出LDAP用户
|
||||||
|
// POST /api/v1/admin/ldap-config/users
|
||||||
|
func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
OuDn string `json:"ou_dn"`
|
||||||
|
}
|
||||||
|
c.ShouldBindJSON(&req)
|
||||||
|
|
||||||
|
var cfg models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").First(&cfg).Error; err != nil {
|
||||||
|
c.JSON(http.StatusOK, []interface{}{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := dialLDAP(&cfg)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, []interface{}{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusOK, []interface{}{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
searchBase := cfg.BaseDN
|
||||||
|
if req.OuDn != "" {
|
||||||
|
searchBase = req.OuDn
|
||||||
|
}
|
||||||
|
|
||||||
|
baseFilter := "(objectClass=inetOrgPerson)"
|
||||||
|
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||||
|
sf := *cfg.SearchFilter
|
||||||
|
if strings.Contains(sf, "%s") {
|
||||||
|
baseFilter = strings.ReplaceAll(sf, "%s", "*")
|
||||||
|
} else {
|
||||||
|
baseFilter = sf
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
||||||
|
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
||||||
|
200, 0, false, baseFilter,
|
||||||
|
[]string{"uid", "cn", "mail", "dn", "telephoneNumber", "title", "department"},
|
||||||
|
nil,
|
||||||
|
))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, []interface{}{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type LdapUser struct {
|
||||||
|
DN string `json:"dn"`
|
||||||
|
UID string `json:"uid"`
|
||||||
|
CN string `json:"cn"`
|
||||||
|
Mail string `json:"mail"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Department string `json:"department"`
|
||||||
|
}
|
||||||
|
var users []LdapUser
|
||||||
|
for _, e := range sr.Entries {
|
||||||
|
users = append(users, LdapUser{
|
||||||
|
DN: e.DN,
|
||||||
|
UID: e.GetAttributeValue("uid"),
|
||||||
|
CN: e.GetAttributeValue("cn"),
|
||||||
|
Mail: e.GetAttributeValue("mail"),
|
||||||
|
Phone: e.GetAttributeValue("telephoneNumber"),
|
||||||
|
Title: e.GetAttributeValue("title"),
|
||||||
|
Department: e.GetAttributeValue("department"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Data: users})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchImportLDAP 批量导入LDAP用户
|
||||||
|
// POST /api/v1/admin/ldap-config/import
|
||||||
|
func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Users []struct {
|
||||||
|
UID string `json:"uid"`
|
||||||
|
CN string `json:"cn"`
|
||||||
|
Mail string `json:"mail"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Nickname string `json:"nickname"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
} `json:"users"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
imported := 0
|
||||||
|
skipped := 0
|
||||||
|
for _, lu := range req.Users {
|
||||||
|
uid := lu.UID
|
||||||
|
if uid == "" {
|
||||||
|
uid = lu.Username
|
||||||
|
}
|
||||||
|
cn := lu.CN
|
||||||
|
if cn == "" {
|
||||||
|
cn = lu.Nickname
|
||||||
|
}
|
||||||
|
mail := lu.Mail
|
||||||
|
if mail == "" {
|
||||||
|
mail = lu.Email
|
||||||
|
}
|
||||||
|
if uid == "" {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Check if already exists
|
||||||
|
var existing models.User
|
||||||
|
if err := h.db.Where("username = ?", uid).First(&existing).Error; err == nil {
|
||||||
|
// Already exists, update info
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"auth_source": "ldap",
|
||||||
|
}
|
||||||
|
if cn != "" {
|
||||||
|
updates["real_name"] = cn
|
||||||
|
}
|
||||||
|
if mail != "" {
|
||||||
|
updates["email"] = mail
|
||||||
|
}
|
||||||
|
h.db.Model(&existing).Updates(updates)
|
||||||
|
imported++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new LDAP user
|
||||||
|
user := models.User{
|
||||||
|
Username: uid,
|
||||||
|
Password: "-", // LDAP users don't have local password
|
||||||
|
RealName: cn,
|
||||||
|
Email: mail,
|
||||||
|
Status: 1,
|
||||||
|
AuthSource: "ldap",
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&user).Error; err != nil {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
imported++
|
||||||
|
}
|
||||||
|
|
||||||
|
// bcrypt import to avoid unused import error
|
||||||
|
_ = bcrypt.MinCost
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: fmt.Sprintf("导入完成: %d 个用户成功, %d 个跳过", imported, skipped),
|
||||||
|
Data: gin.H{"imported": imported, "skipped": skipped},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLDAPUser 在LDAP中创建用户
|
||||||
|
// POST /api/v1/admin/ldap-config/create-user
|
||||||
|
func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
OUDN string `json:"ou_dn"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Username == "" || req.Password == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "用户名和密码不能为空"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs []models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := configs[0]
|
||||||
|
port := 389
|
||||||
|
if cfg.LDAPPort != nil {
|
||||||
|
port = *cfg.LDAPPort
|
||||||
|
}
|
||||||
|
if req.OUDN == "" {
|
||||||
|
req.OUDN = cfg.BaseDN
|
||||||
|
}
|
||||||
|
userDN := fmt.Sprintf("uid=%s,%s", ldap.EscapeFilter(req.Username), req.OUDN)
|
||||||
|
|
||||||
|
// Parse user mapping
|
||||||
|
mapping := map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
||||||
|
if cfg.UserMapping != nil {
|
||||||
|
_ = json.Unmarshal([]byte(*cfg.UserMapping), &mapping)
|
||||||
|
}
|
||||||
|
|
||||||
|
uidAttr := mapping["username"]
|
||||||
|
if uidAttr == "" {
|
||||||
|
uidAttr = "uid"
|
||||||
|
}
|
||||||
|
mailAttr := mapping["email"]
|
||||||
|
if mailAttr == "" {
|
||||||
|
mailAttr = "mail"
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetTimeout(5 * time.Second)
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addReq := ldap.NewAddRequest(userDN, nil)
|
||||||
|
addReq.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
|
||||||
|
addReq.Attribute(uidAttr, []string{req.Username})
|
||||||
|
addReq.Attribute("cn", []string{req.DisplayName})
|
||||||
|
addReq.Attribute("sn", []string{req.DisplayName})
|
||||||
|
if req.Email != "" {
|
||||||
|
addReq.Attribute(mailAttr, []string{req.Email})
|
||||||
|
}
|
||||||
|
addReq.Attribute("userPassword", []string{req.Password})
|
||||||
|
if err := conn.Add(addReq); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建用户失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "用户创建成功", Data: gin.H{"dn": userDN}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLDAPUser 删除LDAP条目(用户或OU)
|
||||||
|
// POST /api/v1/admin/ldap-config/delete-user
|
||||||
|
func (h *LDAPHandler) DeleteLDAPUser(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
DN string `json:"dn"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs []models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := configs[0]
|
||||||
|
port := 389
|
||||||
|
if cfg.LDAPPort != nil {
|
||||||
|
port = *cfg.LDAPPort
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetTimeout(5 * time.Second)
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
delReq := ldap.NewDelRequest(req.DN, nil)
|
||||||
|
if err := conn.Del(delReq); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateLDAPUser 修改 LDAP 用户属性
|
||||||
|
// POST /api/v1/admin/ldap-config/update-user
|
||||||
|
func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
DN string `json:"dn"`
|
||||||
|
CN string `json:"cn"`
|
||||||
|
Mail string `json:"mail"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs []models.LDAPConfig
|
||||||
|
if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := configs[0]
|
||||||
|
port := 389
|
||||||
|
if cfg.LDAPPort != nil {
|
||||||
|
port = *cfg.LDAPPort
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetTimeout(5 * time.Second)
|
||||||
|
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先查当前值,做 diff
|
||||||
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
||||||
|
req.DN, ldap.ScopeBaseObject, ldap.NeverDerefAliases,
|
||||||
|
1, 0, false, "(objectClass=*)",
|
||||||
|
[]string{"cn", "mail", "telephoneNumber", "title"},
|
||||||
|
nil,
|
||||||
|
))
|
||||||
|
if err != nil || len(sr.Entries) == 0 {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "用户不存在"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry := sr.Entries[0]
|
||||||
|
|
||||||
|
modReq := ldap.NewModifyRequest(req.DN, nil)
|
||||||
|
// cn
|
||||||
|
oldCN := entry.GetAttributeValue("cn")
|
||||||
|
if req.CN != "" && req.CN != oldCN {
|
||||||
|
modReq.Replace("cn", []string{req.CN})
|
||||||
|
modReq.Replace("sn", []string{req.CN}) // sn 同步更新
|
||||||
|
}
|
||||||
|
// mail
|
||||||
|
oldMail := entry.GetAttributeValue("mail")
|
||||||
|
if req.Mail != oldMail {
|
||||||
|
if req.Mail == "" {
|
||||||
|
oldVals := entry.GetAttributeValues("mail")
|
||||||
|
if len(oldVals) > 0 {
|
||||||
|
modReq.Delete("mail", oldVals)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
modReq.Replace("mail", []string{req.Mail})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// telephoneNumber
|
||||||
|
oldPhone := entry.GetAttributeValue("telephoneNumber")
|
||||||
|
if req.Phone != oldPhone {
|
||||||
|
if req.Phone == "" {
|
||||||
|
oldVals := entry.GetAttributeValues("telephoneNumber")
|
||||||
|
if len(oldVals) > 0 {
|
||||||
|
modReq.Delete("telephoneNumber", oldVals)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
modReq.Replace("telephoneNumber", []string{req.Phone})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// title
|
||||||
|
oldTitle := entry.GetAttributeValue("title")
|
||||||
|
if req.Title != oldTitle {
|
||||||
|
if req.Title == "" {
|
||||||
|
oldVals := entry.GetAttributeValues("title")
|
||||||
|
if len(oldVals) > 0 {
|
||||||
|
modReq.Delete("title", oldVals)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
modReq.Replace("title", []string{req.Title})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(modReq.Changes) > 0 {
|
||||||
|
if err := conn.Modify(modReq); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "修改失败: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "修改成功"})
|
||||||
|
}
|
||||||
@@ -3,8 +3,6 @@ package handlers
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"ezops/internal/models"
|
"ezops/internal/models"
|
||||||
|
|
||||||
@@ -370,642 +368,3 @@ func (h *ServerHandler) GetServerStats(c *gin.Context) {
|
|||||||
Data: stats,
|
Data: stats,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// CloudAccountHandler 云账号处理器
|
|
||||||
type CloudAccountHandler struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewCloudAccountHandler 创建云账号处理器
|
|
||||||
func NewCloudAccountHandler(db *gorm.DB) *CloudAccountHandler {
|
|
||||||
return &CloudAccountHandler{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListCloudAccounts 获取云账号列表
|
|
||||||
// @Summary 获取云账号列表
|
|
||||||
// @Description 获取所有云账号列表
|
|
||||||
// @Tags 云账号
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Success 200 {object} models.Response{data=models.ListResponse}
|
|
||||||
// @Router /cloud-accounts [get]
|
|
||||||
func (h *CloudAccountHandler) ListCloudAccounts(c *gin.Context) {
|
|
||||||
var accounts []models.CloudAccount
|
|
||||||
h.db.Find(&accounts)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: models.ListResponse{
|
|
||||||
List: accounts,
|
|
||||||
Total: int64(len(accounts)),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// createCloudAccountRequest 创建云账号请求(独立 request struct,避免 CloudAccount.AccessKey/SecretKey 的 json:"-" 导致无法反序列化)
|
|
||||||
type createCloudAccountRequest struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Provider string `json:"provider"`
|
|
||||||
AccessKey string `json:"access_key"`
|
|
||||||
SecretKey string `json:"secret_key"`
|
|
||||||
MonthlyCost float64 `json:"monthly_cost"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateCloudAccount 创建云账号
|
|
||||||
// @Summary 创建云账号
|
|
||||||
// @Description 创建新云账号
|
|
||||||
// @Tags 云账号
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param request body createCloudAccountRequest true "创建请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.CloudAccount}
|
|
||||||
// @Router /cloud-accounts [post]
|
|
||||||
func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) {
|
|
||||||
var req createCloudAccountRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Provider) == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "账号名称和云平台不能为空",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
status := strings.TrimSpace(req.Status)
|
|
||||||
if status == "" {
|
|
||||||
status = "active"
|
|
||||||
}
|
|
||||||
|
|
||||||
account := models.CloudAccount{
|
|
||||||
Name: strings.TrimSpace(req.Name),
|
|
||||||
Provider: strings.TrimSpace(req.Provider),
|
|
||||||
AccessKey: req.AccessKey,
|
|
||||||
SecretKey: req.SecretKey,
|
|
||||||
MonthlyCost: req.MonthlyCost,
|
|
||||||
Status: status,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.db.Create(&account).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "创建失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "创建成功",
|
|
||||||
Data: account,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateCloudAccount 更新云账号
|
|
||||||
// @Summary 更新云账号
|
|
||||||
// @Description 更新指定云账号信息
|
|
||||||
// @Tags 云账号
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "云账号ID"
|
|
||||||
// @Param request body createCloudAccountRequest true "更新请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.CloudAccount}
|
|
||||||
// @Router /cloud-accounts/{id} [put]
|
|
||||||
func (h *CloudAccountHandler) UpdateCloudAccount(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
var req createCloudAccountRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var account models.CloudAccount
|
|
||||||
if err := h.db.First(&account, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{
|
|
||||||
Code: 404,
|
|
||||||
Message: "云账号不存在",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 只在提供非空值时更新凭证字段
|
|
||||||
if strings.TrimSpace(req.Name) != "" {
|
|
||||||
account.Name = strings.TrimSpace(req.Name)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Provider) != "" {
|
|
||||||
account.Provider = strings.TrimSpace(req.Provider)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.AccessKey) != "" {
|
|
||||||
account.AccessKey = req.AccessKey
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.SecretKey) != "" {
|
|
||||||
account.SecretKey = req.SecretKey
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Status) != "" {
|
|
||||||
account.Status = strings.TrimSpace(req.Status)
|
|
||||||
}
|
|
||||||
account.MonthlyCost = req.MonthlyCost
|
|
||||||
|
|
||||||
if err := h.db.Save(&account).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "更新失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "更新成功",
|
|
||||||
Data: account,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteCloudAccount 删除云账号
|
|
||||||
// @Summary 删除云账号
|
|
||||||
// @Description 删除指定云账号
|
|
||||||
// @Tags 云账号
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "云账号ID"
|
|
||||||
// @Success 200 {object} models.Response
|
|
||||||
// @Router /cloud-accounts/{id} [delete]
|
|
||||||
func (h *CloudAccountHandler) DeleteCloudAccount(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
|
|
||||||
if err := h.db.Delete(&models.CloudAccount{}, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "删除失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "删除成功",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DomainHandler 域名处理器
|
|
||||||
type DomainHandler struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDomainHandler 创建域名处理器
|
|
||||||
func NewDomainHandler(db *gorm.DB) *DomainHandler {
|
|
||||||
return &DomainHandler{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListDomains 获取域名列表
|
|
||||||
// @Summary 获取域名列表
|
|
||||||
// @Description 获取所有域名列表
|
|
||||||
// @Tags 域名
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param page query int false "页码"
|
|
||||||
// @Param page_size query int false "每页数量"
|
|
||||||
// @Param keyword query string false "搜索关键词"
|
|
||||||
// @Success 200 {object} models.Response{data=models.ListResponse}
|
|
||||||
// @Router /domains [get]
|
|
||||||
func (h *DomainHandler) ListDomains(c *gin.Context) {
|
|
||||||
var query models.PageQuery
|
|
||||||
c.ShouldBindQuery(&query)
|
|
||||||
|
|
||||||
db := h.db.Model(&models.Domain{})
|
|
||||||
if query.Keyword != "" {
|
|
||||||
db = db.Where("name LIKE ?", "%"+query.Keyword+"%")
|
|
||||||
}
|
|
||||||
|
|
||||||
var total int64
|
|
||||||
db.Count(&total)
|
|
||||||
|
|
||||||
var domains []models.Domain
|
|
||||||
db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&domains)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: models.ListResponse{
|
|
||||||
List: domains,
|
|
||||||
Total: total,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateDomain 创建域名
|
|
||||||
// @Summary 创建域名
|
|
||||||
// @Description 创建新域名
|
|
||||||
// @Tags 域名
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param request body models.Domain true "创建请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.Domain}
|
|
||||||
// @Router /domains [post]
|
|
||||||
func (h *DomainHandler) CreateDomain(c *gin.Context) {
|
|
||||||
var req updateDomainRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(req.Name) == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "域名不能为空",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
status := req.Status
|
|
||||||
if status == "" {
|
|
||||||
status = "active"
|
|
||||||
}
|
|
||||||
|
|
||||||
domain := models.Domain{
|
|
||||||
Name: strings.TrimSpace(req.Name),
|
|
||||||
Registrar: req.Registrar,
|
|
||||||
Status: status,
|
|
||||||
ExpireDate: parseDateStr(req.ExpireDate),
|
|
||||||
DNSProvider: req.DNSProvider,
|
|
||||||
RecordCount: req.RecordCount,
|
|
||||||
SSLEnabled: req.SSLEnabled,
|
|
||||||
SSLExpireDate: parseDateStr(req.SSLExpireDate),
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.db.Create(&domain).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "创建失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "创建成功",
|
|
||||||
Data: domain,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateDomainRequest 域名创建/更新请求(日期字段用字符串接收,避免 RFC3339 解析失败)
|
|
||||||
type updateDomainRequest struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Registrar string `json:"registrar"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
ExpireDate string `json:"expire_date"`
|
|
||||||
DNSProvider string `json:"dns_provider"`
|
|
||||||
RecordCount int `json:"record_count"`
|
|
||||||
SSLEnabled bool `json:"ssl_enabled"`
|
|
||||||
SSLExpireDate string `json:"ssl_expire_date"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseDateStr 将 YYYY-MM-DD 格式字符串解析为 *time.Time,空串返回 nil
|
|
||||||
func parseDateStr(s string) *time.Time {
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
if s == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
t, err := time.Parse("2006-01-02", s)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return &t
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteDomain 删除域名
|
|
||||||
// @Summary 删除域名
|
|
||||||
// @Description 删除指定域名
|
|
||||||
// @Tags 域名
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "域名ID"
|
|
||||||
// @Success 200 {object} models.Response
|
|
||||||
// @Router /domains/{id} [delete]
|
|
||||||
func (h *DomainHandler) DeleteDomain(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
|
|
||||||
if err := h.db.Delete(&models.Domain{}, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "删除失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "删除成功",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateDomain 更新域名
|
|
||||||
// @Summary 更新域名
|
|
||||||
// @Description 更新指定域名信息
|
|
||||||
// @Tags 域名
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "域名ID"
|
|
||||||
// @Param request body updateDomainRequest true "更新请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.Domain}
|
|
||||||
// @Router /domains/{id} [put]
|
|
||||||
func (h *DomainHandler) UpdateDomain(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
var req updateDomainRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var domain models.Domain
|
|
||||||
if err := h.db.First(&domain, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{
|
|
||||||
Code: 404,
|
|
||||||
Message: "域名不存在",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(req.Name) != "" {
|
|
||||||
domain.Name = strings.TrimSpace(req.Name)
|
|
||||||
}
|
|
||||||
domain.Registrar = req.Registrar
|
|
||||||
domain.Status = req.Status
|
|
||||||
if domain.Status == "" {
|
|
||||||
domain.Status = "active"
|
|
||||||
}
|
|
||||||
domain.ExpireDate = parseDateStr(req.ExpireDate)
|
|
||||||
domain.DNSProvider = req.DNSProvider
|
|
||||||
domain.RecordCount = req.RecordCount
|
|
||||||
domain.SSLEnabled = req.SSLEnabled
|
|
||||||
domain.SSLExpireDate = parseDateStr(req.SSLExpireDate)
|
|
||||||
|
|
||||||
if err := h.db.Save(&domain).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "更新失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "更新成功",
|
|
||||||
Data: domain,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== 云平台(Platform / Cloud)====================
|
|
||||||
|
|
||||||
// PlatformHandler 云平台处理器
|
|
||||||
type PlatformHandler struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPlatformHandler(db *gorm.DB) *PlatformHandler {
|
|
||||||
return &PlatformHandler{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
// platformRequest 云平台创建/更新请求
|
|
||||||
type platformRequest struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Code string `json:"code"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
Website string `json:"website"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPlatforms 获取云平台列表
|
|
||||||
func (h *PlatformHandler) ListPlatforms(c *gin.Context) {
|
|
||||||
var platforms []models.Cloud
|
|
||||||
h.db.Find(&platforms)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: models.ListResponse{
|
|
||||||
List: platforms,
|
|
||||||
Total: int64(len(platforms)),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreatePlatform 创建云平台
|
|
||||||
func (h *PlatformHandler) CreatePlatform(c *gin.Context) {
|
|
||||||
var req platformRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "平台名称和编码不能为空"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cloudType := strings.TrimSpace(req.Type)
|
|
||||||
if cloudType == "" {
|
|
||||||
cloudType = "public"
|
|
||||||
}
|
|
||||||
status := strings.TrimSpace(req.Status)
|
|
||||||
if status == "" {
|
|
||||||
status = "active"
|
|
||||||
}
|
|
||||||
|
|
||||||
platform := models.Cloud{
|
|
||||||
Name: strings.TrimSpace(req.Name),
|
|
||||||
Code: strings.TrimSpace(req.Code),
|
|
||||||
Type: cloudType,
|
|
||||||
Status: status,
|
|
||||||
Website: req.Website,
|
|
||||||
Description: req.Description,
|
|
||||||
}
|
|
||||||
if err := h.db.Create(&platform).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: platform})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdatePlatform 更新云平台
|
|
||||||
func (h *PlatformHandler) UpdatePlatform(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
var req platformRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var platform models.Cloud
|
|
||||||
if err := h.db.First(&platform, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云平台不存在"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(req.Name) != "" {
|
|
||||||
platform.Name = strings.TrimSpace(req.Name)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Code) != "" {
|
|
||||||
platform.Code = strings.TrimSpace(req.Code)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Type) != "" {
|
|
||||||
platform.Type = strings.TrimSpace(req.Type)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Status) != "" {
|
|
||||||
platform.Status = strings.TrimSpace(req.Status)
|
|
||||||
}
|
|
||||||
platform.Website = req.Website
|
|
||||||
platform.Description = req.Description
|
|
||||||
|
|
||||||
if err := h.db.Save(&platform).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: platform})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeletePlatform 删除云平台
|
|
||||||
func (h *PlatformHandler) DeletePlatform(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
if err := h.db.Delete(&models.Cloud{}, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== 区域管理(Region)====================
|
|
||||||
|
|
||||||
// RegionHandler 区域处理器
|
|
||||||
type RegionHandler struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegionHandler(db *gorm.DB) *RegionHandler {
|
|
||||||
return &RegionHandler{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
// regionRequest 区域创建/更新请求
|
|
||||||
type regionRequest struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Code string `json:"code"`
|
|
||||||
Provider string `json:"provider"`
|
|
||||||
Location string `json:"location"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
Endpoint string `json:"endpoint"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListRegions 获取区域列表
|
|
||||||
func (h *RegionHandler) ListRegions(c *gin.Context) {
|
|
||||||
var regions []models.Region
|
|
||||||
h.db.Find(®ions)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: models.ListResponse{
|
|
||||||
List: regions,
|
|
||||||
Total: int64(len(regions)),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateRegion 创建区域
|
|
||||||
func (h *RegionHandler) CreateRegion(c *gin.Context) {
|
|
||||||
var req regionRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "区域名称和编码不能为空"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
status := strings.TrimSpace(req.Status)
|
|
||||||
if status == "" {
|
|
||||||
status = "active"
|
|
||||||
}
|
|
||||||
|
|
||||||
region := models.Region{
|
|
||||||
Name: strings.TrimSpace(req.Name),
|
|
||||||
Code: strings.TrimSpace(req.Code),
|
|
||||||
Provider: strings.TrimSpace(req.Provider),
|
|
||||||
Location: req.Location,
|
|
||||||
Status: status,
|
|
||||||
Endpoint: req.Endpoint,
|
|
||||||
}
|
|
||||||
if err := h.db.Create(®ion).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: region})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateRegion 更新区域
|
|
||||||
func (h *RegionHandler) UpdateRegion(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
var req regionRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var region models.Region
|
|
||||||
if err := h.db.First(®ion, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "区域不存在"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(req.Name) != "" {
|
|
||||||
region.Name = strings.TrimSpace(req.Name)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Code) != "" {
|
|
||||||
region.Code = strings.TrimSpace(req.Code)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(req.Provider) != "" {
|
|
||||||
region.Provider = strings.TrimSpace(req.Provider)
|
|
||||||
}
|
|
||||||
region.Location = req.Location
|
|
||||||
if strings.TrimSpace(req.Status) != "" {
|
|
||||||
region.Status = strings.TrimSpace(req.Status)
|
|
||||||
}
|
|
||||||
region.Endpoint = req.Endpoint
|
|
||||||
|
|
||||||
if err := h.db.Save(®ion).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: region})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteRegion 删除区域
|
|
||||||
func (h *RegionHandler) DeleteRegion(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
if err := h.db.Delete(&models.Region{}, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"})
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"ezops/internal/api/middleware"
|
"ezops/internal/api/middleware"
|
||||||
"ezops/internal/config"
|
"ezops/internal/config"
|
||||||
@@ -361,344 +358,3 @@ func (h *UserHandler) ChangePassword(c *gin.Context) {
|
|||||||
Message: "密码修改成功",
|
Message: "密码修改成功",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListUsers 获取用户列表
|
|
||||||
// @Summary 获取用户列表
|
|
||||||
// @Description 获取所有用户列表(管理员)
|
|
||||||
// @Tags 用户
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param page query int false "页码"
|
|
||||||
// @Param page_size query int false "每页数量"
|
|
||||||
// @Param keyword query string false "搜索关键词"
|
|
||||||
// @Success 200 {object} models.Response{data=models.ListResponse}
|
|
||||||
// @Router /users [get]
|
|
||||||
func (h *UserHandler) ListUsers(c *gin.Context) {
|
|
||||||
var query models.PageQuery
|
|
||||||
if err := c.ShouldBindQuery(&query); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
db := h.db.Model(&models.User{})
|
|
||||||
if query.Keyword != "" {
|
|
||||||
db = db.Where("username LIKE ? OR email LIKE ? OR real_name LIKE ?",
|
|
||||||
"%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%")
|
|
||||||
}
|
|
||||||
|
|
||||||
var total int64
|
|
||||||
db.Count(&total)
|
|
||||||
|
|
||||||
var users []models.User
|
|
||||||
db.Preload("Roles").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&users)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: models.ListResponse{
|
|
||||||
List: users,
|
|
||||||
Total: total,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUser 获取用户详情
|
|
||||||
// @Summary 获取用户详情
|
|
||||||
// @Description 获取指定用户的详细信息
|
|
||||||
// @Tags 用户
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "用户ID"
|
|
||||||
// @Success 200 {object} models.Response{data=models.User}
|
|
||||||
// @Router /users/{id} [get]
|
|
||||||
func (h *UserHandler) GetUser(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
|
|
||||||
var user models.User
|
|
||||||
if err := h.db.Preload("Roles").First(&user, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{
|
|
||||||
Code: 404,
|
|
||||||
Message: "用户不存在",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "success",
|
|
||||||
Data: user,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateUser 创建用户
|
|
||||||
// @Summary 创建用户
|
|
||||||
// @Description 创建新用户(管理员)
|
|
||||||
// @Tags 用户
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param request body models.CreateUserRequest true "创建请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.User}
|
|
||||||
// @Router /users [post]
|
|
||||||
func (h *UserHandler) CreateUser(c *gin.Context) {
|
|
||||||
var req models.CreateUserRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查用户名是否已存在
|
|
||||||
var existingUser models.User
|
|
||||||
if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "用户名已存在",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 加密密码
|
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "密码加密失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user := models.User{
|
|
||||||
Username: req.Username,
|
|
||||||
Password: string(hashedPassword),
|
|
||||||
Email: req.Email,
|
|
||||||
Phone: req.Phone,
|
|
||||||
RealName: req.RealName,
|
|
||||||
Status: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.db.Create(&user).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "创建用户失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 关联角色
|
|
||||||
if len(req.RoleIDs) > 0 {
|
|
||||||
var roles []models.Role
|
|
||||||
h.db.Find(&roles, req.RoleIDs)
|
|
||||||
h.db.Model(&user).Association("Roles").Append(roles)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "创建成功",
|
|
||||||
Data: user,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateUser 更新用户
|
|
||||||
// @Summary 更新用户
|
|
||||||
// @Description 更新指定用户信息(管理员)
|
|
||||||
// @Tags 用户
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "用户ID"
|
|
||||||
// @Param request body models.UpdateUserRequest true "更新请求"
|
|
||||||
// @Success 200 {object} models.Response{data=models.User}
|
|
||||||
// @Router /users/{id} [put]
|
|
||||||
func (h *UserHandler) UpdateUser(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
|
|
||||||
var req models.UpdateUserRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var user models.User
|
|
||||||
if err := h.db.First(&user, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, models.Response{
|
|
||||||
Code: 404,
|
|
||||||
Message: "用户不存在",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
updates := map[string]interface{}{}
|
|
||||||
if req.Email != "" {
|
|
||||||
updates["email"] = req.Email
|
|
||||||
}
|
|
||||||
if req.Phone != "" {
|
|
||||||
updates["phone"] = req.Phone
|
|
||||||
}
|
|
||||||
if req.RealName != "" {
|
|
||||||
updates["real_name"] = req.RealName
|
|
||||||
}
|
|
||||||
if req.Status != nil {
|
|
||||||
updates["status"] = *req.Status
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.db.Model(&user).Updates(updates).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "更新失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新角色
|
|
||||||
if len(req.RoleIDs) > 0 {
|
|
||||||
var roles []models.Role
|
|
||||||
h.db.Find(&roles, req.RoleIDs)
|
|
||||||
h.db.Model(&user).Association("Roles").Replace(roles)
|
|
||||||
}
|
|
||||||
|
|
||||||
h.db.Preload("Roles").First(&user, id)
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "更新成功",
|
|
||||||
Data: user,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteUser 删除用户
|
|
||||||
// @Summary 删除用户
|
|
||||||
// @Description 删除指定用户(管理员)
|
|
||||||
// @Tags 用户
|
|
||||||
// @Produce json
|
|
||||||
// @Security Bearer
|
|
||||||
// @Param id path int true "用户ID"
|
|
||||||
// @Success 200 {object} models.Response
|
|
||||||
// @Router /users/{id} [delete]
|
|
||||||
func (h *UserHandler) DeleteUser(c *gin.Context) {
|
|
||||||
id, _ := strconv.Atoi(c.Param("id"))
|
|
||||||
|
|
||||||
if err := h.db.Delete(&models.User{}, id).Error; err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, models.Response{
|
|
||||||
Code: 500,
|
|
||||||
Message: "删除失败",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: "删除成功",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// BatchImportUsers 批量导入用户
|
|
||||||
// POST /api/v1/admin/users/batch-import
|
|
||||||
func (h *UserHandler) BatchImportUsers(c *gin.Context) {
|
|
||||||
var req struct {
|
|
||||||
Users []struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Nickname string `json:"nickname"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Phone string `json:"phone"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
} `json:"users"`
|
|
||||||
SkipExisting bool `json:"skip_existing"`
|
|
||||||
}
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, models.Response{
|
|
||||||
Code: 400,
|
|
||||||
Message: "请求参数错误: " + err.Error(),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
imported := 0
|
|
||||||
skipped := 0
|
|
||||||
var errors []string
|
|
||||||
|
|
||||||
for i, u := range req.Users {
|
|
||||||
if u.Username == "" {
|
|
||||||
errors = append(errors, fmt.Sprintf("第%d行: 用户名为空", i+1))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Check if exists
|
|
||||||
var existing models.User
|
|
||||||
if err := h.db.Where("username = ?", u.Username).First(&existing).Error; err == nil {
|
|
||||||
if req.SkipExisting {
|
|
||||||
skipped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
errors = append(errors, fmt.Sprintf("第%d行: 用户 %s 已存在", i+1, u.Username))
|
|
||||||
skipped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default password
|
|
||||||
pwd := u.Password
|
|
||||||
if pwd == "" {
|
|
||||||
pwd = "admin123"
|
|
||||||
}
|
|
||||||
hashed, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
|
|
||||||
if err != nil {
|
|
||||||
errors = append(errors, fmt.Sprintf("第%d行: 密码加密失败", i+1))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
user := models.User{
|
|
||||||
Username: u.Username,
|
|
||||||
Password: string(hashed),
|
|
||||||
Email: u.Email,
|
|
||||||
Phone: u.Phone,
|
|
||||||
RealName: u.Nickname,
|
|
||||||
Status: 1,
|
|
||||||
AuthSource: "local",
|
|
||||||
}
|
|
||||||
if err := h.db.Create(&user).Error; err != nil {
|
|
||||||
errors = append(errors, fmt.Sprintf("第%d行: 创建用户 %s 失败", i+1, u.Username))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
imported++
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := fmt.Sprintf("导入完成: %d 成功, %d 跳过", imported, skipped)
|
|
||||||
if len(errors) > 0 {
|
|
||||||
msg += fmt.Sprintf(", %d 个错误", len(errors))
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.Response{
|
|
||||||
Code: 200,
|
|
||||||
Message: msg,
|
|
||||||
Data: gin.H{
|
|
||||||
"imported": imported,
|
|
||||||
"skipped": skipped,
|
|
||||||
"errors": errors,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ImportTemplate 下载用户导入模板
|
|
||||||
// GET /api/v1/admin/users/import-template
|
|
||||||
func (h *UserHandler) ImportTemplate(c *gin.Context) {
|
|
||||||
// UTF-8 BOM for Excel compatibility
|
|
||||||
bom := "\xEF\xBB\xBF"
|
|
||||||
csv := bom + "用户名,昵称,邮箱,手机号,角色,密码\n"
|
|
||||||
csv += "zhangsan,张三,zhangsan@example.com,13800138000,developer,123456\n"
|
|
||||||
csv += "lisi,李四,lisi@example.com,13800138001,developer,123456\n"
|
|
||||||
|
|
||||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
|
||||||
c.Header("Content-Disposition", "attachment; filename=users_import_template.csv")
|
|
||||||
c.String(http.StatusOK, csv)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensure strings import is used
|
|
||||||
var _ = strings.TrimSpace
|
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"ezops/internal/models"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListUsers 获取用户列表
|
||||||
|
// @Summary 获取用户列表
|
||||||
|
// @Description 获取所有用户列表(管理员)
|
||||||
|
// @Tags 用户
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param page query int false "页码"
|
||||||
|
// @Param page_size query int false "每页数量"
|
||||||
|
// @Param keyword query string false "搜索关键词"
|
||||||
|
// @Success 200 {object} models.Response{data=models.ListResponse}
|
||||||
|
// @Router /users [get]
|
||||||
|
func (h *UserHandler) ListUsers(c *gin.Context) {
|
||||||
|
var query models.PageQuery
|
||||||
|
if err := c.ShouldBindQuery(&query); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
db := h.db.Model(&models.User{})
|
||||||
|
if query.Keyword != "" {
|
||||||
|
db = db.Where("username LIKE ? OR email LIKE ? OR real_name LIKE ?",
|
||||||
|
"%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%")
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
db.Count(&total)
|
||||||
|
|
||||||
|
var users []models.User
|
||||||
|
db.Preload("Roles").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&users)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: models.ListResponse{
|
||||||
|
List: users,
|
||||||
|
Total: total,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUser 获取用户详情
|
||||||
|
// @Summary 获取用户详情
|
||||||
|
// @Description 获取指定用户的详细信息
|
||||||
|
// @Tags 用户
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "用户ID"
|
||||||
|
// @Success 200 {object} models.Response{data=models.User}
|
||||||
|
// @Router /users/{id} [get]
|
||||||
|
func (h *UserHandler) GetUser(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := h.db.Preload("Roles").First(&user, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "用户不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "success",
|
||||||
|
Data: user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateUser 创建用户
|
||||||
|
// @Summary 创建用户
|
||||||
|
// @Description 创建新用户(管理员)
|
||||||
|
// @Tags 用户
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param request body models.CreateUserRequest true "创建请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.User}
|
||||||
|
// @Router /users [post]
|
||||||
|
func (h *UserHandler) CreateUser(c *gin.Context) {
|
||||||
|
var req models.CreateUserRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查用户名是否已存在
|
||||||
|
var existingUser models.User
|
||||||
|
if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "用户名已存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加密密码
|
||||||
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "密码加密失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user := models.User{
|
||||||
|
Username: req.Username,
|
||||||
|
Password: string(hashedPassword),
|
||||||
|
Email: req.Email,
|
||||||
|
Phone: req.Phone,
|
||||||
|
RealName: req.RealName,
|
||||||
|
Status: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Create(&user).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "创建用户失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关联角色
|
||||||
|
if len(req.RoleIDs) > 0 {
|
||||||
|
var roles []models.Role
|
||||||
|
h.db.Find(&roles, req.RoleIDs)
|
||||||
|
h.db.Model(&user).Association("Roles").Append(roles)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "创建成功",
|
||||||
|
Data: user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateUser 更新用户
|
||||||
|
// @Summary 更新用户
|
||||||
|
// @Description 更新指定用户信息(管理员)
|
||||||
|
// @Tags 用户
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "用户ID"
|
||||||
|
// @Param request body models.UpdateUserRequest true "更新请求"
|
||||||
|
// @Success 200 {object} models.Response{data=models.User}
|
||||||
|
// @Router /users/{id} [put]
|
||||||
|
func (h *UserHandler) UpdateUser(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
var req models.UpdateUserRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := h.db.First(&user, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, models.Response{
|
||||||
|
Code: 404,
|
||||||
|
Message: "用户不存在",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updates := map[string]interface{}{}
|
||||||
|
if req.Email != "" {
|
||||||
|
updates["email"] = req.Email
|
||||||
|
}
|
||||||
|
if req.Phone != "" {
|
||||||
|
updates["phone"] = req.Phone
|
||||||
|
}
|
||||||
|
if req.RealName != "" {
|
||||||
|
updates["real_name"] = req.RealName
|
||||||
|
}
|
||||||
|
if req.Status != nil {
|
||||||
|
updates["status"] = *req.Status
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.db.Model(&user).Updates(updates).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "更新失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新角色
|
||||||
|
if len(req.RoleIDs) > 0 {
|
||||||
|
var roles []models.Role
|
||||||
|
h.db.Find(&roles, req.RoleIDs)
|
||||||
|
h.db.Model(&user).Association("Roles").Replace(roles)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.db.Preload("Roles").First(&user, id)
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "更新成功",
|
||||||
|
Data: user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteUser 删除用户
|
||||||
|
// @Summary 删除用户
|
||||||
|
// @Description 删除指定用户(管理员)
|
||||||
|
// @Tags 用户
|
||||||
|
// @Produce json
|
||||||
|
// @Security Bearer
|
||||||
|
// @Param id path int true "用户ID"
|
||||||
|
// @Success 200 {object} models.Response
|
||||||
|
// @Router /users/{id} [delete]
|
||||||
|
func (h *UserHandler) DeleteUser(c *gin.Context) {
|
||||||
|
id, _ := strconv.Atoi(c.Param("id"))
|
||||||
|
|
||||||
|
if err := h.db.Delete(&models.User{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.Response{
|
||||||
|
Code: 500,
|
||||||
|
Message: "删除失败",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: "删除成功",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchImportUsers 批量导入用户
|
||||||
|
// POST /api/v1/admin/users/batch-import
|
||||||
|
func (h *UserHandler) BatchImportUsers(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Users []struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Nickname string `json:"nickname"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
} `json:"users"`
|
||||||
|
SkipExisting bool `json:"skip_existing"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.Response{
|
||||||
|
Code: 400,
|
||||||
|
Message: "请求参数错误: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
imported := 0
|
||||||
|
skipped := 0
|
||||||
|
var errors []string
|
||||||
|
|
||||||
|
for i, u := range req.Users {
|
||||||
|
if u.Username == "" {
|
||||||
|
errors = append(errors, fmt.Sprintf("第%d行: 用户名为空", i+1))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Check if exists
|
||||||
|
var existing models.User
|
||||||
|
if err := h.db.Where("username = ?", u.Username).First(&existing).Error; err == nil {
|
||||||
|
if req.SkipExisting {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
errors = append(errors, fmt.Sprintf("第%d行: 用户 %s 已存在", i+1, u.Username))
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default password
|
||||||
|
pwd := u.Password
|
||||||
|
if pwd == "" {
|
||||||
|
pwd = "admin123"
|
||||||
|
}
|
||||||
|
hashed, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
errors = append(errors, fmt.Sprintf("第%d行: 密码加密失败", i+1))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
user := models.User{
|
||||||
|
Username: u.Username,
|
||||||
|
Password: string(hashed),
|
||||||
|
Email: u.Email,
|
||||||
|
Phone: u.Phone,
|
||||||
|
RealName: u.Nickname,
|
||||||
|
Status: 1,
|
||||||
|
AuthSource: "local",
|
||||||
|
}
|
||||||
|
if err := h.db.Create(&user).Error; err != nil {
|
||||||
|
errors = append(errors, fmt.Sprintf("第%d行: 创建用户 %s 失败", i+1, u.Username))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
imported++
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := fmt.Sprintf("导入完成: %d 成功, %d 跳过", imported, skipped)
|
||||||
|
if len(errors) > 0 {
|
||||||
|
msg += fmt.Sprintf(", %d 个错误", len(errors))
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.Response{
|
||||||
|
Code: 200,
|
||||||
|
Message: msg,
|
||||||
|
Data: gin.H{
|
||||||
|
"imported": imported,
|
||||||
|
"skipped": skipped,
|
||||||
|
"errors": errors,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImportTemplate 下载用户导入模板
|
||||||
|
// GET /api/v1/admin/users/import-template
|
||||||
|
func (h *UserHandler) ImportTemplate(c *gin.Context) {
|
||||||
|
// UTF-8 BOM for Excel compatibility
|
||||||
|
bom := "\xEF\xBB\xBF"
|
||||||
|
csv := bom + "用户名,昵称,邮箱,手机号,角色,密码\n"
|
||||||
|
csv += "zhangsan,张三,zhangsan@example.com,13800138000,developer,123456\n"
|
||||||
|
csv += "lisi,李四,lisi@example.com,13800138001,developer,123456\n"
|
||||||
|
|
||||||
|
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
c.Header("Content-Disposition", "attachment; filename=users_import_template.csv")
|
||||||
|
c.String(http.StatusOK, csv)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,304 @@
|
|||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
CheckCircle2,
|
||||||
|
XCircle,
|
||||||
|
Eye,
|
||||||
|
Loader2,
|
||||||
|
GitCommit,
|
||||||
|
Server,
|
||||||
|
KeyRound,
|
||||||
|
FileText,
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
function parseSteps(steps: any) {
|
||||||
|
if (Array.isArray(steps)) return steps;
|
||||||
|
if (typeof steps === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(steps);
|
||||||
|
return Array.isArray(parsed) ? parsed : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 审批类型字典
|
||||||
|
const APPROVAL_TYPE_OPTIONS = [
|
||||||
|
{ value: 'deploy', label: '发布审批', icon: GitCommit, color: 'var(--dg-blue)' },
|
||||||
|
{ value: 'server', label: '服务器操作', icon: Server, color: 'var(--dg-cyan)' },
|
||||||
|
{ value: 'permission', label: '权限申请', icon: KeyRound, color: 'var(--dg-purple)' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const getApprovalTypeLabel = (value: string): string =>
|
||||||
|
APPROVAL_TYPE_OPTIONS.find((o) => o.value === value)?.label || value || '通用审批';
|
||||||
|
|
||||||
|
const getApprovalTypeColor = (value: string): string =>
|
||||||
|
APPROVAL_TYPE_OPTIONS.find((o) => o.value === value)?.color || 'var(--dg-text-secondary)';
|
||||||
|
|
||||||
|
const getApprovalTypeIcon = (value: string): React.ElementType =>
|
||||||
|
APPROVAL_TYPE_OPTIONS.find((o) => o.value === value)?.icon || FileText;
|
||||||
|
|
||||||
|
// 状态标签页定义
|
||||||
|
const STATUS_TABS = [
|
||||||
|
{ key: 'all', label: '全部', value: '' },
|
||||||
|
{ key: 'pending', label: '待审批', value: 'pending' },
|
||||||
|
{ key: 'approved', label: '已通过', value: 'approved' },
|
||||||
|
{ key: 'rejected', label: '已拒绝', value: 'rejected' },
|
||||||
|
{ key: 'processing', label: '进行中', value: 'processing' },
|
||||||
|
{ key: 'completed', label: '已完成', value: 'completed' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function getStatusBadge(status: string) {
|
||||||
|
const statusMap: Record<string, { label: string; className: string; dot: string }> = {
|
||||||
|
pending: {
|
||||||
|
label: '待审批',
|
||||||
|
className: 'border-amber-500/30 text-amber-400 bg-amber-500/10',
|
||||||
|
dot: 'bg-amber-400',
|
||||||
|
},
|
||||||
|
approved: {
|
||||||
|
label: '已通过',
|
||||||
|
className: 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10',
|
||||||
|
dot: 'bg-emerald-400',
|
||||||
|
},
|
||||||
|
rejected: {
|
||||||
|
label: '已拒绝',
|
||||||
|
className: 'border-red-500/30 text-red-400 bg-red-500/10',
|
||||||
|
dot: 'bg-red-400',
|
||||||
|
},
|
||||||
|
processing: {
|
||||||
|
label: '进行中',
|
||||||
|
className: 'border-[var(--dg-blue)]/30 text-[var(--dg-blue)] bg-[var(--dg-blue)]/10',
|
||||||
|
dot: 'bg-[var(--dg-blue)]',
|
||||||
|
},
|
||||||
|
completed: {
|
||||||
|
label: '已完成',
|
||||||
|
className: 'border-[var(--dg-border)] text-[var(--dg-text-secondary)] bg-[var(--dg-bg-tertiary)]',
|
||||||
|
dot: 'bg-[var(--dg-text-secondary)]',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = statusMap[status] || statusMap.pending;
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className={config.className}>
|
||||||
|
<div className={cn('w-1.5 h-1.5 rounded-full mr-1.5', config.dot)} />
|
||||||
|
{config.label}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取进度信息
|
||||||
|
function getProgressInfo(instance: any) {
|
||||||
|
const steps = parseSteps(instance.steps);
|
||||||
|
const currentIndex = instance.current_step ?? 0;
|
||||||
|
const total = steps.length;
|
||||||
|
const completed = steps.filter((s: any) => s.status === 'approved' || s.status === 'completed').length;
|
||||||
|
const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||||
|
return { steps, currentIndex, total, completed, percentage };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 渲染审批进度
|
||||||
|
function renderStepProgress(instance: any) {
|
||||||
|
const { steps, currentIndex } = getProgressInfo(instance);
|
||||||
|
if (steps.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1 overflow-x-auto">
|
||||||
|
{steps.map((step: any, index: number) => {
|
||||||
|
const isCompleted = step.status === 'approved' || step.status === 'completed';
|
||||||
|
const isCurrent = index === currentIndex;
|
||||||
|
const isRejected = step.status === 'rejected';
|
||||||
|
return (
|
||||||
|
<div key={step.id || index} className="flex items-center">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs whitespace-nowrap',
|
||||||
|
isCompleted && 'bg-emerald-500/10 text-emerald-400',
|
||||||
|
isCurrent && !isRejected && 'bg-amber-500/10 text-amber-400 border border-amber-500/30',
|
||||||
|
isRejected && 'bg-red-500/10 text-red-400',
|
||||||
|
!isCompleted && !isCurrent && !isRejected && 'bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-muted)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{isCompleted && <CheckCircle2 className="h-3 w-3" />}
|
||||||
|
{isRejected && <XCircle className="h-3 w-3" />}
|
||||||
|
{isCurrent && !isRejected && (
|
||||||
|
<Loader2 className="h-3 w-3 animate-spin" />
|
||||||
|
)}
|
||||||
|
<span>{step.name || step.approver_name || `步骤 ${index + 1}`}</span>
|
||||||
|
</div>
|
||||||
|
{index < steps.length - 1 && (
|
||||||
|
<div className={cn('w-4 h-px', isCompleted ? 'bg-emerald-500/30' : 'bg-[var(--dg-border)]')} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ApprovalProcessTabProps {
|
||||||
|
processes: any[];
|
||||||
|
filteredInstances: any[];
|
||||||
|
loading: boolean;
|
||||||
|
searchQuery: string;
|
||||||
|
setSearchQuery: (v: string) => void;
|
||||||
|
statusFilter: string;
|
||||||
|
setStatusFilter: (v: string) => void;
|
||||||
|
onView: (instance: any) => void;
|
||||||
|
onApprove: (instance: any) => void;
|
||||||
|
onReject: (instance: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ApprovalProcessTab({
|
||||||
|
filteredInstances,
|
||||||
|
loading,
|
||||||
|
searchQuery,
|
||||||
|
setSearchQuery,
|
||||||
|
statusFilter,
|
||||||
|
setStatusFilter,
|
||||||
|
onView,
|
||||||
|
onApprove,
|
||||||
|
onReject,
|
||||||
|
}: ApprovalProcessTabProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* 搜索 + 状态筛选 */}
|
||||||
|
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||||
|
<div className="relative w-72">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-muted)]" />
|
||||||
|
<Input
|
||||||
|
placeholder="搜索标题/申请人..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 h-9 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg p-1">
|
||||||
|
{STATUS_TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.key}
|
||||||
|
onClick={() => setStatusFilter(tab.value)}
|
||||||
|
className={cn(
|
||||||
|
'px-3 py-1.5 rounded-md text-sm transition-colors',
|
||||||
|
statusFilter === tab.value
|
||||||
|
? 'bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium'
|
||||||
|
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 流程实例列表 */}
|
||||||
|
{loading ? (
|
||||||
|
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||||
|
<CardContent className="p-12">
|
||||||
|
<div className="flex items-center justify-center text-[var(--dg-text-muted)]">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||||
|
加载中...
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : filteredInstances.length === 0 ? (
|
||||||
|
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||||
|
<CardContent className="p-12">
|
||||||
|
<div className="text-center">
|
||||||
|
<FileText className="h-12 w-12 mx-auto text-[var(--dg-text-muted)] mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-[var(--dg-text-secondary)] mb-2">暂无审批流程</h3>
|
||||||
|
<p className="text-sm text-[var(--dg-text-muted)]">当前筛选条件下没有匹配的流程实例</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 gap-4">
|
||||||
|
{filteredInstances.map((instance) => {
|
||||||
|
const Icon = getApprovalTypeIcon(instance.type);
|
||||||
|
const { percentage } = getProgressInfo(instance);
|
||||||
|
return (
|
||||||
|
<Card key={instance.id} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] hover:border-[var(--dg-border)] transition-colors">
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<div className="flex items-start justify-between mb-3">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-lg bg-[var(--dg-bg-tertiary)] flex items-center justify-center" style={{ color: getApprovalTypeColor(instance.type) }}>
|
||||||
|
<Icon className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<h3 className="font-medium text-[var(--dg-text-primary)]">{instance.title}</h3>
|
||||||
|
{getStatusBadge(instance.status)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 text-xs text-[var(--dg-text-muted)]">
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<Badge variant="outline" className="text-xs border-[var(--dg-border)]" style={{ color: getApprovalTypeColor(instance.type) }}>
|
||||||
|
{getApprovalTypeLabel(instance.type)}
|
||||||
|
</Badge>
|
||||||
|
</span>
|
||||||
|
<span>申请人:{instance.applicant_name || instance.applicant || '--'}</span>
|
||||||
|
<span>提交于 {instance.created_at ? new Date(instance.created_at).toLocaleString() : '--'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="ghost" size="sm" className="text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]" onClick={() => onView(instance)}>
|
||||||
|
<Eye className="h-4 w-4 mr-1" />
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
{instance.status === 'pending' && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10"
|
||||||
|
onClick={() => onApprove(instance)}
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="h-4 w-4 mr-1" />
|
||||||
|
通过
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="border-red-500/30 text-red-400 hover:bg-red-500/10"
|
||||||
|
onClick={() => onReject(instance)}
|
||||||
|
>
|
||||||
|
<XCircle className="h-4 w-4 mr-1" />
|
||||||
|
拒绝
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* 审批进度条 */}
|
||||||
|
<div className="mb-3">
|
||||||
|
<div className="flex items-center justify-between text-xs text-[var(--dg-text-muted)] mb-1.5">
|
||||||
|
<span>审批进度</span>
|
||||||
|
<span>{percentage}%</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'h-full rounded-full transition-all',
|
||||||
|
instance.status === 'rejected' ? 'bg-red-400' : 'bg-[var(--dg-blue)]'
|
||||||
|
)}
|
||||||
|
style={{ width: `${percentage}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* 步骤进度 */}
|
||||||
|
<div className="bg-[var(--dg-bg-primary)] rounded-lg p-3">
|
||||||
|
{renderStepProgress(instance)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Filter, Edit, GitBranch, ArrowRight } from 'lucide-react';
|
||||||
|
|
||||||
|
function parseSteps(steps: any) {
|
||||||
|
if (Array.isArray(steps)) return steps;
|
||||||
|
if (typeof steps === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(steps);
|
||||||
|
return Array.isArray(parsed) ? parsed : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 审批类型字典
|
||||||
|
const APPROVAL_TYPE_OPTIONS = [
|
||||||
|
{ value: 'deploy', label: '发布审批', color: 'var(--dg-blue)' },
|
||||||
|
{ value: 'server', label: '服务器操作', color: 'var(--dg-cyan)' },
|
||||||
|
{ value: 'permission', label: '权限申请', color: 'var(--dg-purple)' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const getApprovalTypeLabel = (value: string): string =>
|
||||||
|
APPROVAL_TYPE_OPTIONS.find((o) => o.value === value)?.label || value || '通用审批';
|
||||||
|
|
||||||
|
const getApprovalTypeColor = (value: string): string =>
|
||||||
|
APPROVAL_TYPE_OPTIONS.find((o) => o.value === value)?.color || 'var(--dg-text-secondary)';
|
||||||
|
|
||||||
|
// 模拟审批流程图
|
||||||
|
function renderFlowChart(flow: any) {
|
||||||
|
const nodes = parseSteps(flow.steps);
|
||||||
|
if (nodes.length === 0) {
|
||||||
|
return <div className="text-[var(--dg-text-muted)] text-center py-4">暂无流程节点</div>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 overflow-x-auto py-4">
|
||||||
|
{nodes.map((node: any, index: number) => (
|
||||||
|
<div key={node.id || index} className="flex items-center">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'px-4 py-2 rounded-lg border min-w-[100px] text-center',
|
||||||
|
node.type === 'start' && 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400',
|
||||||
|
node.type === 'approval' && 'bg-[var(--dg-blue)]/10 border-[var(--dg-blue)]/30 text-[var(--dg-blue)]',
|
||||||
|
node.type === 'condition' && 'bg-amber-500/10 border-amber-500/30 text-amber-400',
|
||||||
|
node.type === 'end' && 'bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-secondary)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<p className="text-sm font-medium">{node.name}</p>
|
||||||
|
{node.approvers && (
|
||||||
|
<p className="text-xs text-[var(--dg-text-muted)] mt-1">
|
||||||
|
{Array.isArray(node.approvers) ? node.approvers.join(', ') : node.approvers}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{index < nodes.length - 1 && (
|
||||||
|
<ArrowRight className="h-4 w-4 text-[var(--dg-text-muted)] mx-2" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ApprovalTemplateTabProps {
|
||||||
|
filteredTemplates: any[];
|
||||||
|
templateTypeFilter: string;
|
||||||
|
setTemplateTypeFilter: (value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ApprovalTemplateTab({
|
||||||
|
filteredTemplates,
|
||||||
|
templateTypeFilter,
|
||||||
|
setTemplateTypeFilter,
|
||||||
|
}: ApprovalTemplateTabProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* 类型筛选 */}
|
||||||
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
|
<div className="flex items-center gap-1.5 text-sm text-[var(--dg-text-secondary)]">
|
||||||
|
<Filter className="h-4 w-4" />
|
||||||
|
<span>类型筛选:</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg p-1">
|
||||||
|
<button
|
||||||
|
onClick={() => setTemplateTypeFilter('all')}
|
||||||
|
className={cn(
|
||||||
|
'px-3 py-1.5 rounded-md text-sm transition-colors',
|
||||||
|
templateTypeFilter === 'all'
|
||||||
|
? 'bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium'
|
||||||
|
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
全部类型
|
||||||
|
</button>
|
||||||
|
{APPROVAL_TYPE_OPTIONS.map((opt) => (
|
||||||
|
<button
|
||||||
|
key={opt.value}
|
||||||
|
onClick={() => setTemplateTypeFilter(opt.value)}
|
||||||
|
className={cn(
|
||||||
|
'px-3 py-1.5 rounded-md text-sm transition-colors flex items-center gap-1.5',
|
||||||
|
templateTypeFilter === opt.value
|
||||||
|
? 'bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium'
|
||||||
|
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span style={{ color: opt.color }}>●</span>
|
||||||
|
{opt.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-4">
|
||||||
|
{filteredTemplates.length === 0 ? (
|
||||||
|
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||||
|
<CardContent className="p-8">
|
||||||
|
<div className="text-center">
|
||||||
|
<GitBranch className="h-12 w-12 mx-auto text-[var(--dg-text-muted)] mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-[var(--dg-text-secondary)] mb-2">暂无流程模板</h3>
|
||||||
|
<p className="text-sm text-[var(--dg-text-muted)]">当前筛选条件下没有匹配的模板</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
filteredTemplates.map((flow) => (
|
||||||
|
<Card key={flow.id} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-lg bg-[var(--dg-blue)]/10 flex items-center justify-center">
|
||||||
|
<GitBranch className="h-5 w-5 text-[var(--dg-blue)]" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<CardTitle className="text-base text-[var(--dg-text-primary)]">{flow.name}</CardTitle>
|
||||||
|
{flow.type && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="text-xs border-[var(--dg-border)]"
|
||||||
|
style={{ color: getApprovalTypeColor(flow.type) }}
|
||||||
|
>
|
||||||
|
{getApprovalTypeLabel(flow.type)}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<CardDescription className="text-[var(--dg-text-muted)]">{flow.description}</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
flow.status === 1 || flow.status === 'active' || flow.status === true
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: 'border-[var(--dg-border)] text-[var(--dg-text-secondary)] bg-[var(--dg-bg-tertiary)]'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{flow.status === 1 || flow.status === 'active' || flow.status === true ? '已启用' : '已停用'}
|
||||||
|
</Badge>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]">
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="bg-[var(--dg-bg-primary)] rounded-lg p-4 overflow-x-auto">
|
||||||
|
{renderFlowChart(flow)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between mt-4 text-sm text-[var(--dg-text-muted)]">
|
||||||
|
<span>创建于 {flow.created_at ? new Date(flow.created_at).toLocaleDateString() : '--'}</span>
|
||||||
|
<span>{parseSteps(flow.steps).length} 个节点</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -49,13 +49,15 @@ export function CronJobManager() {
|
|||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [jobs, setJobs] = useState<any[]>([]);
|
const [jobs, setJobs] = useState<any[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
const [isFormDialogOpen, setIsFormDialogOpen] = useState(false);
|
||||||
const [isLogDialogOpen, setIsLogDialogOpen] = useState(false);
|
const [isLogDialogOpen, setIsLogDialogOpen] = useState(false);
|
||||||
const [executions, setExecutions] = useState<any[]>([]);
|
const [executions, setExecutions] = useState<any[]>([]);
|
||||||
const [executionsLoading, setExecutionsLoading] = useState(false);
|
const [executionsLoading, setExecutionsLoading] = useState(false);
|
||||||
const [expandedExec, setExpandedExec] = useState<number | null>(null);
|
const [expandedExec, setExpandedExec] = useState<number | null>(null);
|
||||||
const [executingId, setExecutingId] = useState<number | null>(null);
|
const [executingId, setExecutingId] = useState<number | null>(null);
|
||||||
const [newJob, setNewJob] = useState({
|
// editingId === null 表示新建模式;非 null 表示编辑已有任务
|
||||||
|
const [editingId, setEditingId] = useState<number | null>(null);
|
||||||
|
const [formJob, setFormJob] = useState({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
cron_expr: '',
|
cron_expr: '',
|
||||||
@@ -63,6 +65,24 @@ export function CronJobManager() {
|
|||||||
content: '',
|
content: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const openCreate = () => {
|
||||||
|
setEditingId(null);
|
||||||
|
setFormJob({ name: '', description: '', cron_expr: '', type: 'command', content: '' });
|
||||||
|
setIsFormDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEdit = (job: any) => {
|
||||||
|
setEditingId(job.id);
|
||||||
|
setFormJob({
|
||||||
|
name: job.name || '',
|
||||||
|
description: job.description || '',
|
||||||
|
cron_expr: job.cron_expr || '',
|
||||||
|
type: job.type || 'command',
|
||||||
|
content: job.content || '',
|
||||||
|
});
|
||||||
|
setIsFormDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -145,26 +165,31 @@ export function CronJobManager() {
|
|||||||
return patterns[schedule] || schedule;
|
return patterns[schedule] || schedule;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCreateJob = async () => {
|
const handleSaveJob = async () => {
|
||||||
if (!newJob.name || !newJob.cron_expr) {
|
if (!formJob.name || !formJob.cron_expr) {
|
||||||
toast.error('请填写任务名称和 Cron 表达式');
|
toast.error('请填写任务名称和 Cron 表达式');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await cronJobApi.createJob({
|
const payload = {
|
||||||
name: newJob.name,
|
name: formJob.name,
|
||||||
description: newJob.description,
|
description: formJob.description,
|
||||||
cron_expr: newJob.cron_expr,
|
cron_expr: formJob.cron_expr,
|
||||||
type: newJob.type,
|
type: formJob.type,
|
||||||
content: newJob.content,
|
content: formJob.content,
|
||||||
});
|
};
|
||||||
|
if (editingId !== null) {
|
||||||
|
await cronJobApi.updateJob(editingId, payload);
|
||||||
|
toast.success('任务更新成功');
|
||||||
|
} else {
|
||||||
|
await cronJobApi.createJob(payload);
|
||||||
toast.success('任务创建成功');
|
toast.success('任务创建成功');
|
||||||
setIsCreateDialogOpen(false);
|
}
|
||||||
setNewJob({ name: '', description: '', cron_expr: '', type: 'command', content: '' });
|
setIsFormDialogOpen(false);
|
||||||
loadData();
|
loadData();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create cron job:', error);
|
console.error('Failed to save cron job:', error);
|
||||||
toast.error('创建失败');
|
toast.error(editingId !== null ? '更新失败' : '创建失败');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -221,7 +246,7 @@ export function CronJobManager() {
|
|||||||
<History className="h-4 w-4 mr-2" />
|
<History className="h-4 w-4 mr-2" />
|
||||||
执行历史
|
执行历史
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="bg-blue-600 hover:bg-blue-700" onClick={() => setIsCreateDialogOpen(true)}>
|
<Button className="bg-blue-600 hover:bg-blue-700" onClick={openCreate}>
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
新建任务
|
新建任务
|
||||||
</Button>
|
</Button>
|
||||||
@@ -350,7 +375,13 @@ export function CronJobManager() {
|
|||||||
>
|
>
|
||||||
{job.enabled ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
{job.enabled ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-blue-400">
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-blue-400"
|
||||||
|
title="编辑"
|
||||||
|
onClick={() => openEdit(job)}
|
||||||
|
>
|
||||||
<Edit className="h-4 w-4" />
|
<Edit className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
@@ -368,19 +399,19 @@ export function CronJobManager() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Create Job Dialog */}
|
{/* Create / Edit Job Dialog (共用) */}
|
||||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
<Dialog open={isFormDialogOpen} onOpenChange={setIsFormDialogOpen}>
|
||||||
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700 text-slate-100">
|
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700 text-slate-100">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>新建定时任务</DialogTitle>
|
<DialogTitle>{editingId !== null ? '编辑定时任务' : '新建定时任务'}</DialogTitle>
|
||||||
<DialogDescription className="text-slate-500">配置 Cron 定时任务</DialogDescription>
|
<DialogDescription className="text-slate-500">配置 Cron 定时任务</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="space-y-4 py-4">
|
<div className="space-y-4 py-4">
|
||||||
<div>
|
<div>
|
||||||
<Label className="text-slate-300">任务名称</Label>
|
<Label className="text-slate-300">任务名称</Label>
|
||||||
<Input
|
<Input
|
||||||
value={newJob.name}
|
value={formJob.name}
|
||||||
onChange={(e) => setNewJob({ ...newJob, name: e.target.value })}
|
onChange={(e) => setFormJob({ ...formJob, name: e.target.value })}
|
||||||
placeholder="例如: 数据库备份"
|
placeholder="例如: 数据库备份"
|
||||||
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
||||||
/>
|
/>
|
||||||
@@ -388,8 +419,8 @@ export function CronJobManager() {
|
|||||||
<div>
|
<div>
|
||||||
<Label className="text-slate-300">描述</Label>
|
<Label className="text-slate-300">描述</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
value={newJob.description}
|
value={formJob.description}
|
||||||
onChange={(e) => setNewJob({ ...newJob, description: e.target.value })}
|
onChange={(e) => setFormJob({ ...formJob, description: e.target.value })}
|
||||||
placeholder="任务描述..."
|
placeholder="任务描述..."
|
||||||
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
||||||
/>
|
/>
|
||||||
@@ -398,12 +429,12 @@ export function CronJobManager() {
|
|||||||
<Label className="text-slate-300">Cron 表达式</Label>
|
<Label className="text-slate-300">Cron 表达式</Label>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={newJob.cron_expr}
|
value={formJob.cron_expr}
|
||||||
onChange={(e) => setNewJob({ ...newJob, cron_expr: e.target.value })}
|
onChange={(e) => setFormJob({ ...formJob, cron_expr: e.target.value })}
|
||||||
placeholder="0 2 * * *"
|
placeholder="0 2 * * *"
|
||||||
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
|
||||||
/>
|
/>
|
||||||
<Select onValueChange={(v) => setNewJob({ ...newJob, cron_expr: v })}>
|
<Select onValueChange={(v) => setFormJob({ ...formJob, cron_expr: v })}>
|
||||||
<SelectTrigger className="w-48 bg-slate-800 border-slate-700 text-slate-100 mt-1">
|
<SelectTrigger className="w-48 bg-slate-800 border-slate-700 text-slate-100 mt-1">
|
||||||
<SelectValue placeholder="快速选择" />
|
<SelectValue placeholder="快速选择" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@@ -421,19 +452,19 @@ export function CronJobManager() {
|
|||||||
<div>
|
<div>
|
||||||
<Label className="text-slate-300">执行命令</Label>
|
<Label className="text-slate-300">执行命令</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
value={newJob.content}
|
value={formJob.content}
|
||||||
onChange={(e) => setNewJob({ ...newJob, content: e.target.value })}
|
onChange={(e) => setFormJob({ ...formJob, content: e.target.value })}
|
||||||
placeholder="/scripts/backup.sh"
|
placeholder="/scripts/backup.sh"
|
||||||
className="bg-slate-800 border-slate-700 text-slate-100 mt-1 font-mono"
|
className="bg-slate-800 border-slate-700 text-slate-100 mt-1 font-mono"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)} className="border-slate-700 text-slate-300">
|
<Button variant="outline" onClick={() => setIsFormDialogOpen(false)} className="border-slate-700 text-slate-300">
|
||||||
取消
|
取消
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="bg-blue-600 hover:bg-blue-700" onClick={handleCreateJob}>
|
<Button className="bg-blue-600 hover:bg-blue-700" onClick={handleSaveJob}>
|
||||||
创建任务
|
{editingId !== null ? '保存修改' : '创建任务'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -1,790 +1,16 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Clock, Activity, Server, Cloud, Bell, DollarSign } from 'lucide-react';
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
|
||||||
import {
|
|
||||||
Server,
|
|
||||||
Cloud,
|
|
||||||
Bell,
|
|
||||||
Rocket,
|
|
||||||
TrendingUp,
|
|
||||||
TrendingDown,
|
|
||||||
AlertTriangle,
|
|
||||||
CheckCircle,
|
|
||||||
Clock,
|
|
||||||
Activity,
|
|
||||||
Cpu,
|
|
||||||
HardDrive,
|
|
||||||
ArrowRight,
|
|
||||||
DollarSign,
|
|
||||||
Shield,
|
|
||||||
MemoryStick,
|
|
||||||
Database,
|
|
||||||
} from 'lucide-react';
|
|
||||||
import {
|
|
||||||
AreaChart,
|
|
||||||
Area,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
ResponsiveContainer,
|
|
||||||
PieChart,
|
|
||||||
Pie,
|
|
||||||
Cell,
|
|
||||||
BarChart,
|
|
||||||
Bar,
|
|
||||||
} from 'recharts';
|
|
||||||
import { dashboardStatsApi, serverApi, k8sApi } from '@/services/api';
|
import { dashboardStatsApi, serverApi, k8sApi } from '@/services/api';
|
||||||
|
import { StatCard } from './DashboardStats';
|
||||||
// 云平台颜色映射
|
import { CostOverviewCard, TopResourceUsageCard, ResourceUsageCard, computeMonthChange } from './DashboardCharts';
|
||||||
const CLOUD_COLORS: Record<string, string> = {
|
import {
|
||||||
'阿里云': '#ff6a00',
|
AlertMessagesCard,
|
||||||
aliyun: '#ff6a00',
|
CertificateExpiryCard,
|
||||||
AWS: '#ff9900',
|
ReleaseHistoryCard,
|
||||||
aws: '#ff9900',
|
ServerStatusCard,
|
||||||
'腾讯云': '#006eff',
|
K8sClusterCard,
|
||||||
tencent: '#006eff',
|
} from './DashboardRecent';
|
||||||
'华为云': '#ff0000',
|
|
||||||
huawei: '#ff0000',
|
|
||||||
Azure: '#0078d4',
|
|
||||||
azure: '#0078d4',
|
|
||||||
};
|
|
||||||
const FALLBACK_CLOUD_COLORS = ['#ff6a00', '#ff9900', '#006eff', '#ff0000', '#0078d4', '#10b981', '#a855f7', '#ec4899'];
|
|
||||||
|
|
||||||
// 计算月度环比变化(基于 month_trend 最后两个月)
|
|
||||||
function computeMonthChange(monthTrend: any[]): {
|
|
||||||
pct: number;
|
|
||||||
label: string;
|
|
||||||
direction: 'up' | 'down' | 'neutral';
|
|
||||||
} {
|
|
||||||
if (!monthTrend || monthTrend.length < 2) {
|
|
||||||
return { pct: 0, label: '暂无数据', direction: 'neutral' };
|
|
||||||
}
|
|
||||||
const cur = Number(monthTrend[monthTrend.length - 1].cost ?? 0);
|
|
||||||
const prev = Number(monthTrend[monthTrend.length - 2].cost ?? 0);
|
|
||||||
if (prev === 0) {
|
|
||||||
return { pct: 0, label: cur > 0 ? '新增费用' : '持平', direction: 'neutral' };
|
|
||||||
}
|
|
||||||
const pct = ((cur - prev) / prev) * 100;
|
|
||||||
const direction = pct > 0.05 ? 'up' : pct < -0.05 ? 'down' : 'neutral';
|
|
||||||
const label = `${pct > 0 ? '+' : ''}${pct.toFixed(1)}% 较上月`;
|
|
||||||
return { pct, label, direction };
|
|
||||||
}
|
|
||||||
|
|
||||||
// 根据平均值生成24小时趋势数据(无实时指标时使用)
|
|
||||||
function generateMetricsData(avgCpu: number, avgMemory: number, avgDisk: number, points = 24) {
|
|
||||||
const data = [];
|
|
||||||
for (let i = points - 1; i >= 0; i--) {
|
|
||||||
const d = new Date(Date.now() - i * 60 * 60 * 1000);
|
|
||||||
data.push({
|
|
||||||
time: `${d.getHours().toString().padStart(2, '0')}:00`,
|
|
||||||
cpu: Number(Math.max(0, avgCpu + (Math.random() - 0.5) * 15).toFixed(1)),
|
|
||||||
memory: Number(Math.max(0, avgMemory + (Math.random() - 0.5) * 10).toFixed(1)),
|
|
||||||
disk: Number(Math.max(0, avgDisk + (Math.random() - 0.5) * 5).toFixed(1)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 统计卡片组件
|
|
||||||
function StatCard({
|
|
||||||
title,
|
|
||||||
value,
|
|
||||||
description,
|
|
||||||
icon: Icon,
|
|
||||||
trend,
|
|
||||||
trendValue,
|
|
||||||
color,
|
|
||||||
onClick,
|
|
||||||
}: {
|
|
||||||
title: string;
|
|
||||||
value: string | number;
|
|
||||||
description?: string;
|
|
||||||
icon: React.ElementType;
|
|
||||||
trend?: 'up' | 'down' | 'neutral';
|
|
||||||
trendValue?: string;
|
|
||||||
color: string;
|
|
||||||
onClick?: () => void;
|
|
||||||
}) {
|
|
||||||
const colorClasses: Record<string, { bg: string; text: string }> = {
|
|
||||||
blue: { bg: 'bg-blue-500/10', text: 'text-blue-400' },
|
|
||||||
emerald: { bg: 'bg-emerald-500/10', text: 'text-emerald-400' },
|
|
||||||
amber: { bg: 'bg-amber-500/10', text: 'text-amber-400' },
|
|
||||||
rose: { bg: 'bg-rose-500/10', text: 'text-rose-400' },
|
|
||||||
purple: { bg: 'bg-purple-500/10', text: 'text-purple-400' },
|
|
||||||
cyan: { bg: 'bg-cyan-500/10', text: 'text-cyan-400' },
|
|
||||||
orange: { bg: 'bg-orange-500/10', text: 'text-orange-400' },
|
|
||||||
};
|
|
||||||
const colors = colorClasses[color];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card
|
|
||||||
className="bg-slate-900 border-slate-800 hover:border-slate-700 transition-all cursor-pointer"
|
|
||||||
onClick={onClick}
|
|
||||||
>
|
|
||||||
<CardContent className="p-6">
|
|
||||||
<div className="flex items-start justify-between">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-sm font-medium text-slate-400">{title}</p>
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<h3 className="text-2xl font-bold text-slate-100">{value}</h3>
|
|
||||||
{trend && trendValue && (
|
|
||||||
<span
|
|
||||||
className={`flex items-center text-xs font-medium ${
|
|
||||||
trend === 'up' ? 'text-emerald-400' : trend === 'down' ? 'text-red-400' : 'text-slate-400'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{trend === 'up' ? (
|
|
||||||
<TrendingUp className="h-3 w-3 mr-0.5" />
|
|
||||||
) : trend === 'down' ? (
|
|
||||||
<TrendingDown className="h-3 w-3 mr-0.5" />
|
|
||||||
) : null}
|
|
||||||
{trendValue}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{description && <p className="text-xs text-slate-500">{description}</p>}
|
|
||||||
</div>
|
|
||||||
<div className={`p-3 rounded-lg ${colors.bg} ${colors.text}`}>
|
|
||||||
<Icon className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 成本费用卡片
|
|
||||||
function CostOverviewCard({ costStats }: { costStats: any }) {
|
|
||||||
const cloudCosts: any[] = costStats?.cloud_costs ?? [];
|
|
||||||
const monthTrend: any[] = costStats?.month_trend ?? [];
|
|
||||||
|
|
||||||
const costData = cloudCosts.map((c, i) => ({
|
|
||||||
name: c.cloud,
|
|
||||||
value: c.cost,
|
|
||||||
color: CLOUD_COLORS[c.cloud] || FALLBACK_CLOUD_COLORS[i % FALLBACK_CLOUD_COLORS.length],
|
|
||||||
}));
|
|
||||||
const monthlyData = monthTrend.map((m) => ({ month: m.month, cost: m.cost }));
|
|
||||||
const totalCost =
|
|
||||||
costStats?.total_cost ?? costData.reduce((sum, item) => sum + item.value, 0);
|
|
||||||
const costChange = computeMonthChange(monthTrend);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">云成本概览</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">本月各云平台费用支出</CardDescription>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<p className="text-2xl font-bold text-slate-100">¥{Number(totalCost).toLocaleString()}</p>
|
|
||||||
<p className={`text-xs ${
|
|
||||||
costChange.direction === 'up'
|
|
||||||
? 'text-emerald-400'
|
|
||||||
: costChange.direction === 'down'
|
|
||||||
? 'text-red-400'
|
|
||||||
: 'text-slate-500'
|
|
||||||
}`}>
|
|
||||||
{costChange.label}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm text-slate-400 mb-2">费用分布</p>
|
|
||||||
<div className="h-[180px]">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<PieChart>
|
|
||||||
<Pie
|
|
||||||
data={costData}
|
|
||||||
cx="50%"
|
|
||||||
cy="50%"
|
|
||||||
innerRadius={40}
|
|
||||||
outerRadius={70}
|
|
||||||
paddingAngle={2}
|
|
||||||
dataKey="value"
|
|
||||||
>
|
|
||||||
{costData.map((entry, index) => (
|
|
||||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
|
||||||
))}
|
|
||||||
</Pie>
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: '#0f172a',
|
|
||||||
border: '1px solid #1e293b',
|
|
||||||
borderRadius: '6px',
|
|
||||||
color: '#f8fafc',
|
|
||||||
}}
|
|
||||||
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
|
||||||
/>
|
|
||||||
</PieChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm text-slate-400 mb-2">月度趋势</p>
|
|
||||||
<div className="h-[180px]">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<BarChart data={monthlyData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
|
||||||
<XAxis dataKey="month" stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
|
||||||
<YAxis stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: '#0f172a',
|
|
||||||
border: '1px solid #1e293b',
|
|
||||||
borderRadius: '6px',
|
|
||||||
color: '#f8fafc',
|
|
||||||
}}
|
|
||||||
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
|
||||||
/>
|
|
||||||
<Bar dataKey="cost" fill="#3b82f6" radius={[4, 4, 0, 0]} />
|
|
||||||
</BarChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="mt-4 space-y-2">
|
|
||||||
{costData.map((item) => (
|
|
||||||
<div key={item.name} className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
|
|
||||||
<span className="text-sm text-slate-300">{item.name}</span>
|
|
||||||
</div>
|
|
||||||
<span className="text-sm font-medium text-slate-100">¥{Number(item.value).toLocaleString()}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 告警消息卡片
|
|
||||||
function AlertMessagesCard({ alerts }: { alerts: any[] }) {
|
|
||||||
const recentAlerts = alerts.filter((a) => a.status === 'firing').slice(0, 8);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">告警消息</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">最近触发的告警事件</CardDescription>
|
|
||||||
</div>
|
|
||||||
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
|
||||||
查看全部
|
|
||||||
<ArrowRight className="h-4 w-4 ml-1" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<ScrollArea className="h-[320px]">
|
|
||||||
<div className="space-y-2">
|
|
||||||
{recentAlerts.map((alert) => (
|
|
||||||
<div
|
|
||||||
key={alert.id}
|
|
||||||
className="flex items-start gap-3 p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
|
||||||
>
|
|
||||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
|
||||||
alert.severity === 'critical' ? 'bg-red-400' :
|
|
||||||
alert.severity === 'warning' ? 'bg-amber-400' : 'bg-blue-400'
|
|
||||||
}`} />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm font-medium text-slate-200 truncate">{alert.rule_name}</span>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={`text-xs ${
|
|
||||||
alert.severity === 'critical'
|
|
||||||
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
: alert.severity === 'warning'
|
|
||||||
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
: 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{alert.severity === 'critical' ? '严重' : alert.severity === 'warning' ? '警告' : '提示'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-slate-500 mt-1">{alert.target}</p>
|
|
||||||
<p className="text-xs text-slate-500">{alert.message}</p>
|
|
||||||
</div>
|
|
||||||
<span className="text-xs text-slate-500 whitespace-nowrap">
|
|
||||||
{alert.created_at ? new Date(alert.created_at).toLocaleString() : ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ScrollArea>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Top5 资源使用卡片
|
|
||||||
function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
|
|
||||||
const topCpuServers = (topUsage?.cpu ?? []).slice(0, 5);
|
|
||||||
const topMemoryServers = (topUsage?.memory ?? []).slice(0, 5);
|
|
||||||
const topDiskServers = (topUsage?.disk ?? []).slice(0, 5);
|
|
||||||
|
|
||||||
const renderList = (
|
|
||||||
items: any[],
|
|
||||||
color: string,
|
|
||||||
BarColor: string,
|
|
||||||
icon: React.ReactNode,
|
|
||||||
label: string
|
|
||||||
) => (
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center gap-2 mb-3">
|
|
||||||
{icon}
|
|
||||||
<span className="text-sm font-medium text-slate-300">{label}</span>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{items.map((item, index) => {
|
|
||||||
const usage = Number(item.usage ?? 0);
|
|
||||||
return (
|
|
||||||
<div key={item.id ?? index} className="flex items-center gap-2">
|
|
||||||
<span className="text-xs text-slate-500 w-4">{index + 1}</span>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-xs text-slate-300 truncate">{item.hostname}</p>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
|
||||||
<div
|
|
||||||
className={`h-full rounded-full ${
|
|
||||||
usage > 80 ? 'bg-red-400' : usage > 60 ? 'bg-amber-400' : BarColor
|
|
||||||
}`}
|
|
||||||
style={{ width: `${usage}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<span className={`text-xs ${
|
|
||||||
usage > 80 ? 'text-red-400' : usage > 60 ? 'text-amber-400' : 'text-slate-400'
|
|
||||||
}`}>
|
|
||||||
{usage.toFixed(1)}%
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">Top5 资源使用</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">CPU、内存、磁盘使用率最高</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="grid grid-cols-3 gap-4">
|
|
||||||
{/* CPU Top5 */}
|
|
||||||
{renderList(topCpuServers, 'blue', 'bg-blue-400', <Cpu className="h-4 w-4 text-blue-400" />, 'CPU')}
|
|
||||||
{/* Memory Top5 */}
|
|
||||||
{renderList(topMemoryServers, 'emerald', 'bg-emerald-400', <MemoryStick className="h-4 w-4 text-emerald-400" />, '内存')}
|
|
||||||
{/* Disk Top5 */}
|
|
||||||
{renderList(topDiskServers, 'purple', 'bg-purple-400', <Database className="h-4 w-4 text-purple-400" />, '磁盘')}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 证书到期卡片
|
|
||||||
function CertificateExpiryCard({ expCerts }: { expCerts: any[] }) {
|
|
||||||
const expiringDomains = (expCerts ?? [])
|
|
||||||
.map((d) => ({
|
|
||||||
...d,
|
|
||||||
daysUntilExpiry: d.days_until_expiry ?? Math.ceil((new Date(d.expire_date).getTime() - Date.now()) / (1000 * 60 * 60 * 24)),
|
|
||||||
}))
|
|
||||||
.sort((a, b) => a.daysUntilExpiry - b.daysUntilExpiry);
|
|
||||||
|
|
||||||
const criticalCount = expiringDomains.filter((d) => d.daysUntilExpiry < 30).length;
|
|
||||||
const warningCount = expiringDomains.filter((d) => d.daysUntilExpiry >= 30 && d.daysUntilExpiry < 60).length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">证书到期提醒</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">SSL证书到期时间监控</CardDescription>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{criticalCount > 0 && (
|
|
||||||
<Badge className="bg-red-500/20 text-red-400 border-0">
|
|
||||||
<AlertTriangle className="h-3 w-3 mr-1" />
|
|
||||||
{criticalCount} 即将过期
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{warningCount > 0 && (
|
|
||||||
<Badge className="bg-amber-500/20 text-amber-400 border-0">
|
|
||||||
{warningCount} 30天内过期
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<ScrollArea className="h-[280px]">
|
|
||||||
<div className="space-y-2">
|
|
||||||
{expiringDomains.map((domain) => (
|
|
||||||
<div
|
|
||||||
key={domain.id}
|
|
||||||
className="flex items-center justify-between p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
|
|
||||||
domain.daysUntilExpiry < 30 ? 'bg-red-500/10 text-red-400' :
|
|
||||||
domain.daysUntilExpiry < 60 ? 'bg-amber-500/10 text-amber-400' :
|
|
||||||
'bg-emerald-500/10 text-emerald-400'
|
|
||||||
}`}>
|
|
||||||
<Shield className="h-4 w-4" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-slate-200">{domain.name}</p>
|
|
||||||
<p className="text-xs text-slate-500">到期: {domain.expire_date?.substring(0, 10)}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={`text-xs ${
|
|
||||||
domain.daysUntilExpiry < 30
|
|
||||||
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
: domain.daysUntilExpiry < 60
|
|
||||||
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
: 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{domain.daysUntilExpiry < 0 ? '已过期' : `${domain.daysUntilExpiry} 天`}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ScrollArea>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 资源使用率趋势卡片
|
|
||||||
function ResourceUsageCard({
|
|
||||||
avgCpu,
|
|
||||||
avgMemory,
|
|
||||||
avgDisk,
|
|
||||||
}: {
|
|
||||||
avgCpu: number;
|
|
||||||
avgMemory: number;
|
|
||||||
avgDisk: number;
|
|
||||||
}) {
|
|
||||||
const data = generateMetricsData(avgCpu, avgMemory, avgDisk, 24);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">资源使用率趋势</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">过去24小时系统资源使用情况</CardDescription>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
|
|
||||||
<Cpu className="h-3 w-3 mr-1" />
|
|
||||||
CPU
|
|
||||||
</Badge>
|
|
||||||
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
|
|
||||||
<Activity className="h-3 w-3 mr-1" />
|
|
||||||
内存
|
|
||||||
</Badge>
|
|
||||||
<Badge variant="outline" className="border-purple-500/30 text-purple-400 bg-purple-500/10">
|
|
||||||
<HardDrive className="h-3 w-3 mr-1" />
|
|
||||||
磁盘
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="h-[280px]">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="colorDisk" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="#a855f7" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="#a855f7" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
|
||||||
<XAxis dataKey="time" stroke="#475569" fontSize={12} tickLine={false} axisLine={false} />
|
|
||||||
<YAxis stroke="#475569" fontSize={12} tickLine={false} axisLine={false} unit="%" />
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: '#0f172a',
|
|
||||||
border: '1px solid #1e293b',
|
|
||||||
borderRadius: '6px',
|
|
||||||
color: '#f8fafc',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="cpu"
|
|
||||||
stroke="#3b82f6"
|
|
||||||
fillOpacity={1}
|
|
||||||
fill="url(#colorCpu)"
|
|
||||||
strokeWidth={2}
|
|
||||||
name="CPU"
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="memory"
|
|
||||||
stroke="#10b981"
|
|
||||||
fillOpacity={1}
|
|
||||||
fill="url(#colorMemory)"
|
|
||||||
strokeWidth={2}
|
|
||||||
name="内存"
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="disk"
|
|
||||||
stroke="#a855f7"
|
|
||||||
fillOpacity={1}
|
|
||||||
fill="url(#colorDisk)"
|
|
||||||
strokeWidth={2}
|
|
||||||
name="磁盘"
|
|
||||||
/>
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发布历史卡片
|
|
||||||
function ReleaseHistoryCard({ releases }: { releases: any[] }) {
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">发布历史</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">今日应用发布记录</CardDescription>
|
|
||||||
</div>
|
|
||||||
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
|
||||||
查看全部
|
|
||||||
<ArrowRight className="h-4 w-4 ml-1" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{releases.slice(0, 5).map((release) => (
|
|
||||||
<div
|
|
||||||
key={release.id}
|
|
||||||
className="flex items-center gap-3 p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={`w-8 h-8 rounded-lg flex items-center justify-center ${
|
|
||||||
release.status === 'success'
|
|
||||||
? 'bg-emerald-500/10 text-emerald-400'
|
|
||||||
: release.status === 'failed'
|
|
||||||
? 'bg-red-500/10 text-red-400'
|
|
||||||
: release.status === 'deploying'
|
|
||||||
? 'bg-blue-500/10 text-blue-400'
|
|
||||||
: 'bg-amber-500/10 text-amber-400'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Rocket className="h-4 w-4" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm font-medium text-slate-200">{release.app_name}</span>
|
|
||||||
<Badge variant="outline" className="text-xs border-slate-700 text-slate-400">
|
|
||||||
{release.version}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 mt-0.5">
|
|
||||||
<span className="text-xs text-slate-500">{release.environment}</span>
|
|
||||||
<span className="text-xs text-slate-500">·</span>
|
|
||||||
<span className="text-xs text-slate-500">{release.commit_id}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={`text-xs ${
|
|
||||||
release.status === 'success'
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: release.status === 'failed'
|
|
||||||
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
: release.status === 'deploying'
|
|
||||||
? 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
|
||||||
: 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{release.status === 'success'
|
|
||||||
? '成功'
|
|
||||||
: release.status === 'failed'
|
|
||||||
? '失败'
|
|
||||||
: release.status === 'deploying'
|
|
||||||
? '发布中'
|
|
||||||
: release.status === 'rolled_back'
|
|
||||||
? '已回滚'
|
|
||||||
: '构建中'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 服务器状态卡片
|
|
||||||
function ServerStatusCard({ servers }: { servers: any[] }) {
|
|
||||||
const runningServers = servers.filter((s) => s.status === 'running').length;
|
|
||||||
const stoppedServers = servers.filter((s) => s.status === 'stopped').length;
|
|
||||||
const maintenanceServers = servers.filter((s) => s.status === 'maintenance').length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">服务器状态</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">服务器运行状态分布</CardDescription>
|
|
||||||
</div>
|
|
||||||
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
|
||||||
查看全部
|
|
||||||
<ArrowRight className="h-4 w-4 ml-1" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="grid grid-cols-3 gap-4 mb-4">
|
|
||||||
<div className="text-center p-3 rounded-lg bg-emerald-500/10">
|
|
||||||
<div className="text-2xl font-bold text-emerald-400">{runningServers}</div>
|
|
||||||
<div className="text-xs text-slate-400 mt-1">运行中</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-3 rounded-lg bg-amber-500/10">
|
|
||||||
<div className="text-2xl font-bold text-amber-400">{maintenanceServers}</div>
|
|
||||||
<div className="text-xs text-slate-400 mt-1">维护中</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-3 rounded-lg bg-slate-500/10">
|
|
||||||
<div className="text-2xl font-bold text-slate-400">{stoppedServers}</div>
|
|
||||||
<div className="text-xs text-slate-400 mt-1">已停止</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{servers.slice(0, 4).map((server) => (
|
|
||||||
<div key={server.id} className="flex items-center gap-3 p-2 rounded-lg bg-slate-800/50">
|
|
||||||
<div
|
|
||||||
className={`w-2 h-2 rounded-full ${
|
|
||||||
server.status === 'running'
|
|
||||||
? 'bg-emerald-400'
|
|
||||||
: server.status === 'maintenance'
|
|
||||||
? 'bg-amber-400'
|
|
||||||
: 'bg-slate-400'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm text-slate-200 truncate">{server.hostname}</p>
|
|
||||||
<p className="text-xs text-slate-500">{server.ip}</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<p className="text-xs text-slate-400">CPU {Number(server.cpu_usage ?? 0).toFixed(1)}%</p>
|
|
||||||
<p className="text-xs text-slate-400">内存 {Number(server.memory_usage ?? 0).toFixed(1)}%</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// K8s集群状态卡片
|
|
||||||
function K8sClusterCard({ clusters }: { clusters: any[] }) {
|
|
||||||
return (
|
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">K8s集群</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">Kubernetes集群健康状态</CardDescription>
|
|
||||||
</div>
|
|
||||||
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
|
||||||
查看全部
|
|
||||||
<ArrowRight className="h-4 w-4 ml-1" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="space-y-3">
|
|
||||||
{clusters.map((cluster) => {
|
|
||||||
const cpuUsage = Number(cluster.cpu_usage ?? 0);
|
|
||||||
const memoryUsage = Number(cluster.memory_usage ?? 0);
|
|
||||||
return (
|
|
||||||
<div key={cluster.id} className="p-3 rounded-lg bg-slate-800/50">
|
|
||||||
<div className="flex items-center justify-between mb-2">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Cloud className="h-4 w-4 text-blue-400" />
|
|
||||||
<span className="text-sm font-medium text-slate-200">{cluster.name}</span>
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={`text-xs ${
|
|
||||||
cluster.status === 'healthy'
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: cluster.status === 'warning'
|
|
||||||
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{cluster.status === 'healthy' ? '健康' : cluster.status === 'warning' ? '警告' : '异常'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-4 gap-2 text-center">
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-slate-200">{cluster.node_count ?? cluster.nodes ?? 0}</div>
|
|
||||||
<div className="text-xs text-slate-500">节点</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-slate-200">{cluster.pod_count ?? cluster.pods ?? 0}</div>
|
|
||||||
<div className="text-xs text-slate-500">Pod</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-slate-200">{cpuUsage.toFixed(1)}%</div>
|
|
||||||
<div className="text-xs text-slate-500">CPU</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-slate-200">{memoryUsage.toFixed(1)}%</div>
|
|
||||||
<div className="text-xs text-slate-500">内存</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Dashboard() {
|
export function Dashboard() {
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|||||||
@@ -0,0 +1,349 @@
|
|||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import {
|
||||||
|
AreaChart,
|
||||||
|
Area,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
PieChart,
|
||||||
|
Pie,
|
||||||
|
Cell,
|
||||||
|
BarChart,
|
||||||
|
Bar,
|
||||||
|
} from 'recharts';
|
||||||
|
import { Cpu, HardDrive, Activity, MemoryStick, Database } from 'lucide-react';
|
||||||
|
|
||||||
|
// 云平台颜色映射
|
||||||
|
const CLOUD_COLORS: Record<string, string> = {
|
||||||
|
'阿里云': '#ff6a00',
|
||||||
|
aliyun: '#ff6a00',
|
||||||
|
AWS: '#ff9900',
|
||||||
|
aws: '#ff9900',
|
||||||
|
'腾讯云': '#006eff',
|
||||||
|
tencent: '#006eff',
|
||||||
|
'华为云': '#ff0000',
|
||||||
|
huawei: '#ff0000',
|
||||||
|
Azure: '#0078d4',
|
||||||
|
azure: '#0078d4',
|
||||||
|
};
|
||||||
|
const FALLBACK_CLOUD_COLORS = ['#ff6a00', '#ff9900', '#006eff', '#ff0000', '#0078d4', '#10b981', '#a855f7', '#ec4899'];
|
||||||
|
|
||||||
|
// 计算月度环比变化(基于 month_trend 最后两个月)
|
||||||
|
export function computeMonthChange(monthTrend: any[]): {
|
||||||
|
pct: number;
|
||||||
|
label: string;
|
||||||
|
direction: 'up' | 'down' | 'neutral';
|
||||||
|
} {
|
||||||
|
if (!monthTrend || monthTrend.length < 2) {
|
||||||
|
return { pct: 0, label: '暂无数据', direction: 'neutral' };
|
||||||
|
}
|
||||||
|
const cur = Number(monthTrend[monthTrend.length - 1].cost ?? 0);
|
||||||
|
const prev = Number(monthTrend[monthTrend.length - 2].cost ?? 0);
|
||||||
|
if (prev === 0) {
|
||||||
|
return { pct: 0, label: cur > 0 ? '新增费用' : '持平', direction: 'neutral' };
|
||||||
|
}
|
||||||
|
const pct = ((cur - prev) / prev) * 100;
|
||||||
|
const direction = pct > 0.05 ? 'up' : pct < -0.05 ? 'down' : 'neutral';
|
||||||
|
const label = `${pct > 0 ? '+' : ''}${pct.toFixed(1)}% 较上月`;
|
||||||
|
return { pct, label, direction };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据平均值生成24小时趋势数据(无实时指标时使用)
|
||||||
|
function generateMetricsData(avgCpu: number, avgMemory: number, avgDisk: number, points = 24) {
|
||||||
|
const data = [];
|
||||||
|
for (let i = points - 1; i >= 0; i--) {
|
||||||
|
const d = new Date(Date.now() - i * 60 * 60 * 1000);
|
||||||
|
data.push({
|
||||||
|
time: `${d.getHours().toString().padStart(2, '0')}:00`,
|
||||||
|
cpu: Number(Math.max(0, avgCpu + (Math.random() - 0.5) * 15).toFixed(1)),
|
||||||
|
memory: Number(Math.max(0, avgMemory + (Math.random() - 0.5) * 10).toFixed(1)),
|
||||||
|
disk: Number(Math.max(0, avgDisk + (Math.random() - 0.5) * 5).toFixed(1)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 成本费用卡片
|
||||||
|
export function CostOverviewCard({ costStats }: { costStats: any }) {
|
||||||
|
const cloudCosts: any[] = costStats?.cloud_costs ?? [];
|
||||||
|
const monthTrend: any[] = costStats?.month_trend ?? [];
|
||||||
|
|
||||||
|
const costData = cloudCosts.map((c, i) => ({
|
||||||
|
name: c.cloud,
|
||||||
|
value: c.cost,
|
||||||
|
color: CLOUD_COLORS[c.cloud] || FALLBACK_CLOUD_COLORS[i % FALLBACK_CLOUD_COLORS.length],
|
||||||
|
}));
|
||||||
|
const monthlyData = monthTrend.map((m) => ({ month: m.month, cost: m.cost }));
|
||||||
|
const totalCost =
|
||||||
|
costStats?.total_cost ?? costData.reduce((sum, item) => sum + item.value, 0);
|
||||||
|
const costChange = computeMonthChange(monthTrend);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">云成本概览</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">本月各云平台费用支出</CardDescription>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-2xl font-bold text-slate-100">¥{Number(totalCost).toLocaleString()}</p>
|
||||||
|
<p className={`text-xs ${
|
||||||
|
costChange.direction === 'up'
|
||||||
|
? 'text-emerald-400'
|
||||||
|
: costChange.direction === 'down'
|
||||||
|
? 'text-red-400'
|
||||||
|
: 'text-slate-500'
|
||||||
|
}`}>
|
||||||
|
{costChange.label}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-slate-400 mb-2">费用分布</p>
|
||||||
|
<div className="h-[180px]">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<PieChart>
|
||||||
|
<Pie
|
||||||
|
data={costData}
|
||||||
|
cx="50%"
|
||||||
|
cy="50%"
|
||||||
|
innerRadius={40}
|
||||||
|
outerRadius={70}
|
||||||
|
paddingAngle={2}
|
||||||
|
dataKey="value"
|
||||||
|
>
|
||||||
|
{costData.map((entry, index) => (
|
||||||
|
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0f172a',
|
||||||
|
border: '1px solid #1e293b',
|
||||||
|
borderRadius: '6px',
|
||||||
|
color: '#f8fafc',
|
||||||
|
}}
|
||||||
|
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
||||||
|
/>
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-slate-400 mb-2">月度趋势</p>
|
||||||
|
<div className="h-[180px]">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart data={monthlyData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
||||||
|
<XAxis dataKey="month" stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
||||||
|
<YAxis stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0f172a',
|
||||||
|
border: '1px solid #1e293b',
|
||||||
|
borderRadius: '6px',
|
||||||
|
color: '#f8fafc',
|
||||||
|
}}
|
||||||
|
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
||||||
|
/>
|
||||||
|
<Bar dataKey="cost" fill="#3b82f6" radius={[4, 4, 0, 0]} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 space-y-2">
|
||||||
|
{costData.map((item) => (
|
||||||
|
<div key={item.name} className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
|
||||||
|
<span className="text-sm text-slate-300">{item.name}</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm font-medium text-slate-100">¥{Number(item.value).toLocaleString()}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Top5 资源使用卡片
|
||||||
|
export function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
|
||||||
|
const topCpuServers = (topUsage?.cpu ?? []).slice(0, 5);
|
||||||
|
const topMemoryServers = (topUsage?.memory ?? []).slice(0, 5);
|
||||||
|
const topDiskServers = (topUsage?.disk ?? []).slice(0, 5);
|
||||||
|
|
||||||
|
const renderList = (
|
||||||
|
items: any[],
|
||||||
|
color: string,
|
||||||
|
BarColor: string,
|
||||||
|
icon: React.ReactNode,
|
||||||
|
label: string
|
||||||
|
) => (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 mb-3">
|
||||||
|
{icon}
|
||||||
|
<span className="text-sm font-medium text-slate-300">{label}</span>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{items.map((item, index) => {
|
||||||
|
const usage = Number(item.usage ?? 0);
|
||||||
|
return (
|
||||||
|
<div key={item.id ?? index} className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-slate-500 w-4">{index + 1}</span>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-xs text-slate-300 truncate">{item.hostname}</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={`h-full rounded-full ${
|
||||||
|
usage > 80 ? 'bg-red-400' : usage > 60 ? 'bg-amber-400' : BarColor
|
||||||
|
}`}
|
||||||
|
style={{ width: `${usage}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className={`text-xs ${
|
||||||
|
usage > 80 ? 'text-red-400' : usage > 60 ? 'text-amber-400' : 'text-slate-400'
|
||||||
|
}`}>
|
||||||
|
{usage.toFixed(1)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">Top5 资源使用</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">CPU、内存、磁盘使用率最高</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
{/* CPU Top5 */}
|
||||||
|
{renderList(topCpuServers, 'blue', 'bg-blue-400', <Cpu className="h-4 w-4 text-blue-400" />, 'CPU')}
|
||||||
|
{/* Memory Top5 */}
|
||||||
|
{renderList(topMemoryServers, 'emerald', 'bg-emerald-400', <MemoryStick className="h-4 w-4 text-emerald-400" />, '内存')}
|
||||||
|
{/* Disk Top5 */}
|
||||||
|
{renderList(topDiskServers, 'purple', 'bg-purple-400', <Database className="h-4 w-4 text-purple-400" />, '磁盘')}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资源使用率趋势卡片
|
||||||
|
export function ResourceUsageCard({
|
||||||
|
avgCpu,
|
||||||
|
avgMemory,
|
||||||
|
avgDisk,
|
||||||
|
}: {
|
||||||
|
avgCpu: number;
|
||||||
|
avgMemory: number;
|
||||||
|
avgDisk: number;
|
||||||
|
}) {
|
||||||
|
const data = generateMetricsData(avgCpu, avgMemory, avgDisk, 24);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">资源使用率趋势</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">过去24小时系统资源使用情况</CardDescription>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
|
||||||
|
<Cpu className="h-3 w-3 mr-1" />
|
||||||
|
CPU
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
|
||||||
|
<Activity className="h-3 w-3 mr-1" />
|
||||||
|
内存
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="border-purple-500/30 text-purple-400 bg-purple-500/10">
|
||||||
|
<HardDrive className="h-3 w-3 mr-1" />
|
||||||
|
磁盘
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="h-[280px]">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="colorDisk" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#a855f7" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#a855f7" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
||||||
|
<XAxis dataKey="time" stroke="#475569" fontSize={12} tickLine={false} axisLine={false} />
|
||||||
|
<YAxis stroke="#475569" fontSize={12} tickLine={false} axisLine={false} unit="%" />
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0f172a',
|
||||||
|
border: '1px solid #1e293b',
|
||||||
|
borderRadius: '6px',
|
||||||
|
color: '#f8fafc',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="cpu"
|
||||||
|
stroke="#3b82f6"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorCpu)"
|
||||||
|
strokeWidth={2}
|
||||||
|
name="CPU"
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="memory"
|
||||||
|
stroke="#10b981"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorMemory)"
|
||||||
|
strokeWidth={2}
|
||||||
|
name="内存"
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="disk"
|
||||||
|
stroke="#a855f7"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorDisk)"
|
||||||
|
strokeWidth={2}
|
||||||
|
name="磁盘"
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import {
|
||||||
|
Rocket,
|
||||||
|
AlertTriangle,
|
||||||
|
ArrowRight,
|
||||||
|
Cloud,
|
||||||
|
Shield,
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
// 告警消息卡片
|
||||||
|
export function AlertMessagesCard({ alerts }: { alerts: any[] }) {
|
||||||
|
const recentAlerts = alerts.filter((a) => a.status === 'firing').slice(0, 8);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">告警消息</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">最近触发的告警事件</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
||||||
|
查看全部
|
||||||
|
<ArrowRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ScrollArea className="h-[320px]">
|
||||||
|
<div className="space-y-2">
|
||||||
|
{recentAlerts.map((alert) => (
|
||||||
|
<div
|
||||||
|
key={alert.id}
|
||||||
|
className="flex items-start gap-3 p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
||||||
|
>
|
||||||
|
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||||
|
alert.severity === 'critical' ? 'bg-red-400' :
|
||||||
|
alert.severity === 'warning' ? 'bg-amber-400' : 'bg-blue-400'
|
||||||
|
}`} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium text-slate-200 truncate">{alert.rule_name}</span>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={`text-xs ${
|
||||||
|
alert.severity === 'critical'
|
||||||
|
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
: alert.severity === 'warning'
|
||||||
|
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
: 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{alert.severity === 'critical' ? '严重' : alert.severity === 'warning' ? '警告' : '提示'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-slate-500 mt-1">{alert.target}</p>
|
||||||
|
<p className="text-xs text-slate-500">{alert.message}</p>
|
||||||
|
</div>
|
||||||
|
<span className="text-xs text-slate-500 whitespace-nowrap">
|
||||||
|
{alert.created_at ? new Date(alert.created_at).toLocaleString() : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 证书到期卡片
|
||||||
|
export function CertificateExpiryCard({ expCerts }: { expCerts: any[] }) {
|
||||||
|
const expiringDomains = (expCerts ?? [])
|
||||||
|
.map((d) => ({
|
||||||
|
...d,
|
||||||
|
daysUntilExpiry: d.days_until_expiry ?? Math.ceil((new Date(d.expire_date).getTime() - Date.now()) / (1000 * 60 * 60 * 24)),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.daysUntilExpiry - b.daysUntilExpiry);
|
||||||
|
|
||||||
|
const criticalCount = expiringDomains.filter((d) => d.daysUntilExpiry < 30).length;
|
||||||
|
const warningCount = expiringDomains.filter((d) => d.daysUntilExpiry >= 30 && d.daysUntilExpiry < 60).length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">证书到期提醒</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">SSL证书到期时间监控</CardDescription>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{criticalCount > 0 && (
|
||||||
|
<Badge className="bg-red-500/20 text-red-400 border-0">
|
||||||
|
<AlertTriangle className="h-3 w-3 mr-1" />
|
||||||
|
{criticalCount} 即将过期
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{warningCount > 0 && (
|
||||||
|
<Badge className="bg-amber-500/20 text-amber-400 border-0">
|
||||||
|
{warningCount} 30天内过期
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ScrollArea className="h-[280px]">
|
||||||
|
<div className="space-y-2">
|
||||||
|
{expiringDomains.map((domain) => (
|
||||||
|
<div
|
||||||
|
key={domain.id}
|
||||||
|
className="flex items-center justify-between p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
|
||||||
|
domain.daysUntilExpiry < 30 ? 'bg-red-500/10 text-red-400' :
|
||||||
|
domain.daysUntilExpiry < 60 ? 'bg-amber-500/10 text-amber-400' :
|
||||||
|
'bg-emerald-500/10 text-emerald-400'
|
||||||
|
}`}>
|
||||||
|
<Shield className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-slate-200">{domain.name}</p>
|
||||||
|
<p className="text-xs text-slate-500">到期: {domain.expire_date?.substring(0, 10)}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={`text-xs ${
|
||||||
|
domain.daysUntilExpiry < 30
|
||||||
|
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
: domain.daysUntilExpiry < 60
|
||||||
|
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
: 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{domain.daysUntilExpiry < 0 ? '已过期' : `${domain.daysUntilExpiry} 天`}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发布历史卡片
|
||||||
|
export function ReleaseHistoryCard({ releases }: { releases: any[] }) {
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">发布历史</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">今日应用发布记录</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
||||||
|
查看全部
|
||||||
|
<ArrowRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{releases.slice(0, 5).map((release) => (
|
||||||
|
<div
|
||||||
|
key={release.id}
|
||||||
|
className="flex items-center gap-3 p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`w-8 h-8 rounded-lg flex items-center justify-center ${
|
||||||
|
release.status === 'success'
|
||||||
|
? 'bg-emerald-500/10 text-emerald-400'
|
||||||
|
: release.status === 'failed'
|
||||||
|
? 'bg-red-500/10 text-red-400'
|
||||||
|
: release.status === 'deploying'
|
||||||
|
? 'bg-blue-500/10 text-blue-400'
|
||||||
|
: 'bg-amber-500/10 text-amber-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Rocket className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium text-slate-200">{release.app_name}</span>
|
||||||
|
<Badge variant="outline" className="text-xs border-slate-700 text-slate-400">
|
||||||
|
{release.version}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 mt-0.5">
|
||||||
|
<span className="text-xs text-slate-500">{release.environment}</span>
|
||||||
|
<span className="text-xs text-slate-500">·</span>
|
||||||
|
<span className="text-xs text-slate-500">{release.commit_id}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={`text-xs ${
|
||||||
|
release.status === 'success'
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: release.status === 'failed'
|
||||||
|
? 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
: release.status === 'deploying'
|
||||||
|
? 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
||||||
|
: 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{release.status === 'success'
|
||||||
|
? '成功'
|
||||||
|
: release.status === 'failed'
|
||||||
|
? '失败'
|
||||||
|
: release.status === 'deploying'
|
||||||
|
? '发布中'
|
||||||
|
: release.status === 'rolled_back'
|
||||||
|
? '已回滚'
|
||||||
|
: '构建中'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务器状态卡片
|
||||||
|
export function ServerStatusCard({ servers }: { servers: any[] }) {
|
||||||
|
const runningServers = servers.filter((s) => s.status === 'running').length;
|
||||||
|
const stoppedServers = servers.filter((s) => s.status === 'stopped').length;
|
||||||
|
const maintenanceServers = servers.filter((s) => s.status === 'maintenance').length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">服务器状态</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">服务器运行状态分布</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
||||||
|
查看全部
|
||||||
|
<ArrowRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-3 gap-4 mb-4">
|
||||||
|
<div className="text-center p-3 rounded-lg bg-emerald-500/10">
|
||||||
|
<div className="text-2xl font-bold text-emerald-400">{runningServers}</div>
|
||||||
|
<div className="text-xs text-slate-400 mt-1">运行中</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-3 rounded-lg bg-amber-500/10">
|
||||||
|
<div className="text-2xl font-bold text-amber-400">{maintenanceServers}</div>
|
||||||
|
<div className="text-xs text-slate-400 mt-1">维护中</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-3 rounded-lg bg-slate-500/10">
|
||||||
|
<div className="text-2xl font-bold text-slate-400">{stoppedServers}</div>
|
||||||
|
<div className="text-xs text-slate-400 mt-1">已停止</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{servers.slice(0, 4).map((server) => (
|
||||||
|
<div key={server.id} className="flex items-center gap-3 p-2 rounded-lg bg-slate-800/50">
|
||||||
|
<div
|
||||||
|
className={`w-2 h-2 rounded-full ${
|
||||||
|
server.status === 'running'
|
||||||
|
? 'bg-emerald-400'
|
||||||
|
: server.status === 'maintenance'
|
||||||
|
? 'bg-amber-400'
|
||||||
|
: 'bg-slate-400'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm text-slate-200 truncate">{server.hostname}</p>
|
||||||
|
<p className="text-xs text-slate-500">{server.ip}</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-xs text-slate-400">CPU {Number(server.cpu_usage ?? 0).toFixed(1)}%</p>
|
||||||
|
<p className="text-xs text-slate-400">内存 {Number(server.memory_usage ?? 0).toFixed(1)}%</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// K8s集群状态卡片
|
||||||
|
export function K8sClusterCard({ clusters }: { clusters: any[] }) {
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">K8s集群</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">Kubernetes集群健康状态</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-slate-100">
|
||||||
|
查看全部
|
||||||
|
<ArrowRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{clusters.map((cluster) => {
|
||||||
|
const cpuUsage = Number(cluster.cpu_usage ?? 0);
|
||||||
|
const memoryUsage = Number(cluster.memory_usage ?? 0);
|
||||||
|
return (
|
||||||
|
<div key={cluster.id} className="p-3 rounded-lg bg-slate-800/50">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Cloud className="h-4 w-4 text-blue-400" />
|
||||||
|
<span className="text-sm font-medium text-slate-200">{cluster.name}</span>
|
||||||
|
</div>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={`text-xs ${
|
||||||
|
cluster.status === 'healthy'
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: cluster.status === 'warning'
|
||||||
|
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{cluster.status === 'healthy' ? '健康' : cluster.status === 'warning' ? '警告' : '异常'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-4 gap-2 text-center">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-slate-200">{cluster.node_count ?? cluster.nodes ?? 0}</div>
|
||||||
|
<div className="text-xs text-slate-500">节点</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-slate-200">{cluster.pod_count ?? cluster.pods ?? 0}</div>
|
||||||
|
<div className="text-xs text-slate-500">Pod</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-slate-200">{cpuUsage.toFixed(1)}%</div>
|
||||||
|
<div className="text-xs text-slate-500">CPU</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-slate-200">{memoryUsage.toFixed(1)}%</div>
|
||||||
|
<div className="text-xs text-slate-500">内存</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { TrendingUp, TrendingDown } from 'lucide-react';
|
||||||
|
|
||||||
|
// 统计卡片组件
|
||||||
|
export function StatCard({
|
||||||
|
title,
|
||||||
|
value,
|
||||||
|
description,
|
||||||
|
icon: Icon,
|
||||||
|
trend,
|
||||||
|
trendValue,
|
||||||
|
color,
|
||||||
|
onClick,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
value: string | number;
|
||||||
|
description?: string;
|
||||||
|
icon: React.ElementType;
|
||||||
|
trend?: 'up' | 'down' | 'neutral';
|
||||||
|
trendValue?: string;
|
||||||
|
color: string;
|
||||||
|
onClick?: () => void;
|
||||||
|
}) {
|
||||||
|
const colorClasses: Record<string, { bg: string; text: string }> = {
|
||||||
|
blue: { bg: 'bg-blue-500/10', text: 'text-blue-400' },
|
||||||
|
emerald: { bg: 'bg-emerald-500/10', text: 'text-emerald-400' },
|
||||||
|
amber: { bg: 'bg-amber-500/10', text: 'text-amber-400' },
|
||||||
|
rose: { bg: 'bg-rose-500/10', text: 'text-rose-400' },
|
||||||
|
purple: { bg: 'bg-purple-500/10', text: 'text-purple-400' },
|
||||||
|
cyan: { bg: 'bg-cyan-500/10', text: 'text-cyan-400' },
|
||||||
|
orange: { bg: 'bg-orange-500/10', text: 'text-orange-400' },
|
||||||
|
};
|
||||||
|
const colors = colorClasses[color];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
className="bg-slate-900 border-slate-800 hover:border-slate-700 transition-all cursor-pointer"
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm font-medium text-slate-400">{title}</p>
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<h3 className="text-2xl font-bold text-slate-100">{value}</h3>
|
||||||
|
{trend && trendValue && (
|
||||||
|
<span
|
||||||
|
className={`flex items-center text-xs font-medium ${
|
||||||
|
trend === 'up' ? 'text-emerald-400' : trend === 'down' ? 'text-red-400' : 'text-slate-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{trend === 'up' ? (
|
||||||
|
<TrendingUp className="h-3 w-3 mr-0.5" />
|
||||||
|
) : trend === 'down' ? (
|
||||||
|
<TrendingDown className="h-3 w-3 mr-0.5" />
|
||||||
|
) : null}
|
||||||
|
{trendValue}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{description && <p className="text-xs text-slate-500">{description}</p>}
|
||||||
|
</div>
|
||||||
|
<div className={`p-3 rounded-lg ${colors.bg} ${colors.text}`}>
|
||||||
|
<Icon className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
|
import { Cloud, XCircle } from 'lucide-react';
|
||||||
|
import { k8sApi } from '@/services/api';
|
||||||
|
import {
|
||||||
|
AreaChart,
|
||||||
|
Area,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
} from 'recharts';
|
||||||
|
|
||||||
|
// 模拟资源使用趋势数据
|
||||||
|
const resourceData = [
|
||||||
|
{ time: '00:00', cpu: 45, memory: 52 },
|
||||||
|
{ time: '04:00', cpu: 38, memory: 48 },
|
||||||
|
{ time: '08:00', cpu: 62, memory: 68 },
|
||||||
|
{ time: '12:00', cpu: 78, memory: 82 },
|
||||||
|
{ time: '16:00', cpu: 72, memory: 76 },
|
||||||
|
{ time: '20:00', cpu: 58, memory: 64 },
|
||||||
|
{ time: '24:00', cpu: 48, memory: 56 },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function K8sClusterDetail({ cluster, onClose }: { cluster: any; onClose: () => void }) {
|
||||||
|
const [nodes, setNodes] = useState<any[]>([]);
|
||||||
|
const [pods, setPods] = useState<any[]>([]);
|
||||||
|
const [deployments, setDeployments] = useState<any[]>([]);
|
||||||
|
const [services, setServices] = useState<any[]>([]);
|
||||||
|
const [ingresses, setIngresses] = useState<any[]>([]);
|
||||||
|
|
||||||
|
const loadClusterDetail = async (clusterId: string) => {
|
||||||
|
try {
|
||||||
|
// 后端 ListNodes/ListPods/etc 返回 data 直接为数组(非 {list,total})
|
||||||
|
const [nodesRes, podsRes, depRes, svcRes, ingRes] = await Promise.all([
|
||||||
|
k8sApi.getNodes(clusterId).catch(() => []),
|
||||||
|
k8sApi.getPods(clusterId).catch(() => []),
|
||||||
|
k8sApi.getDeployments(clusterId).catch(() => []),
|
||||||
|
k8sApi.getServices(clusterId).catch(() => []),
|
||||||
|
k8sApi.getIngresses(clusterId).catch(() => []),
|
||||||
|
]);
|
||||||
|
const toArray = (v: any) => (Array.isArray(v) ? v : (v?.list || []));
|
||||||
|
setNodes(toArray(nodesRes));
|
||||||
|
setPods(toArray(podsRes));
|
||||||
|
setDeployments(toArray(depRes));
|
||||||
|
setServices(toArray(svcRes));
|
||||||
|
setIngresses(toArray(ingRes));
|
||||||
|
} catch (e) {
|
||||||
|
console.error('加载集群详情失败:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (cluster?.id) {
|
||||||
|
loadClusterDetail(cluster.id);
|
||||||
|
}
|
||||||
|
}, [cluster?.id]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Cloud className="h-6 w-6 text-blue-400" />
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-slate-100">{cluster.name}</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">
|
||||||
|
{cluster.version} · {cluster.node_count || 0} 节点 · 创建于{' '}
|
||||||
|
{cluster.created_at ? new Date(cluster.created_at).toLocaleDateString() : '-'}
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-slate-400 hover:text-slate-100"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<XCircle className="h-4 w-4 mr-2" />
|
||||||
|
关闭
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Tabs defaultValue="overview" className="w-full">
|
||||||
|
<TabsList className="bg-slate-800 border border-slate-700 flex-wrap h-auto">
|
||||||
|
<TabsTrigger value="overview" className="data-[state=active]:bg-slate-700">
|
||||||
|
概览
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="nodes" className="data-[state=active]:bg-slate-700">
|
||||||
|
节点 ({nodes.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="pods" className="data-[state=active]:bg-slate-700">
|
||||||
|
Pod ({pods.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="deployments" className="data-[state=active]:bg-slate-700">
|
||||||
|
Deployment ({deployments.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="services" className="data-[state=active]:bg-slate-700">
|
||||||
|
Service ({services.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="ingresses" className="data-[state=active]:bg-slate-700">
|
||||||
|
Ingress ({ingresses.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="events" className="data-[state=active]:bg-slate-700">
|
||||||
|
事件
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value="overview" className="mt-4 space-y-4">
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
|
<Card className="bg-slate-800/50 border-slate-700">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-sm text-slate-400">资源使用趋势</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="h-[200px]">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<AreaChart data={resourceData}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
||||||
|
<XAxis dataKey="time" stroke="#475569" fontSize={12} />
|
||||||
|
<YAxis stroke="#475569" fontSize={12} />
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0f172a',
|
||||||
|
border: '1px solid #1e293b',
|
||||||
|
borderRadius: '6px',
|
||||||
|
color: '#f8fafc',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="cpu"
|
||||||
|
stroke="#3b82f6"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorCpu)"
|
||||||
|
name="CPU"
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="memory"
|
||||||
|
stroke="#10b981"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorMemory)"
|
||||||
|
name="内存"
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className="bg-slate-800/50 border-slate-700">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardTitle className="text-sm text-slate-400">资源分布</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="text-center p-4 rounded-lg bg-slate-800">
|
||||||
|
<div className="text-3xl font-bold text-blue-400">{cluster.pod_count || 0}</div>
|
||||||
|
<div className="text-sm text-slate-500 mt-1">Pod</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 rounded-lg bg-slate-800">
|
||||||
|
<div className="text-3xl font-bold text-emerald-400">{cluster.service_count || 0}</div>
|
||||||
|
<div className="text-sm text-slate-500 mt-1">Service</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 rounded-lg bg-slate-800">
|
||||||
|
<div className="text-3xl font-bold text-purple-400">{cluster.deployment_count || 0}</div>
|
||||||
|
<div className="text-sm text-slate-500 mt-1">Deployment</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 rounded-lg bg-slate-800">
|
||||||
|
<div className="text-3xl font-bold text-amber-400">{cluster.node_count || 0}</div>
|
||||||
|
<div className="text-sm text-slate-500 mt-1">节点</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="nodes" className="mt-4">
|
||||||
|
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-slate-800">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">角色</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">状态</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">CPU</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">内存</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Pod</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">操作系统</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-800">
|
||||||
|
{nodes.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="px-4 py-8 text-center text-slate-500">暂无节点数据</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
nodes.map((node) => (
|
||||||
|
<tr key={node.id || node.name} className="hover:bg-slate-800/50">
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-200">{node.name}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
node.role === 'master'
|
||||||
|
? 'border-purple-500/30 text-purple-400 bg-purple-500/10'
|
||||||
|
: 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{node.role === 'master' ? 'Master' : 'Worker'}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
(node.status || '').toLowerCase() === 'ready'
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(node.status || '').toLowerCase() === 'ready' ? 'Ready' : 'NotReady'}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">
|
||||||
|
{Number(node.cpu_usage || 0).toFixed(1)}% / {node.cpu}核
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">
|
||||||
|
{Number(node.memory_usage || 0).toFixed(1)}% / {node.memory}GB
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{node.pods ?? node.pod_count ?? 0}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-400">{node.os}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="pods" className="mt-4">
|
||||||
|
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-slate-800">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">状态</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">重启次数</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">CPU</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">内存</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">节点</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-800">
|
||||||
|
{pods.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="px-4 py-8 text-center text-slate-500">暂无Pod数据</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
pods.map((pod) => (
|
||||||
|
<tr key={pod.id || pod.name} className="hover:bg-slate-800/50">
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-200">{pod.name}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{pod.namespace}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
(pod.status || '').toLowerCase() === 'running'
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: (pod.status || '').toLowerCase() === 'pending'
|
||||||
|
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{pod.status}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{pod.restart_count ?? 0}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{Number(pod.cpu_usage || 0).toFixed(1)}m</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{Number(pod.memory_usage || 0).toFixed(0)}Mi</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-400">{pod.node_name}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="deployments" className="mt-4">
|
||||||
|
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-slate-800">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">副本数</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">可用副本</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">镜像</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">创建时间</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-800">
|
||||||
|
{deployments.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="px-4 py-8 text-center text-slate-500">暂无Deployment数据</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
deployments.map((deployment) => (
|
||||||
|
<tr key={deployment.id || deployment.name} className="hover:bg-slate-800/50">
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-200">{deployment.name}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{deployment.namespace}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{deployment.replicas}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<span className={`text-sm ${(deployment.available_replicas ?? deployment.availableReplicas) === deployment.replicas ? 'text-emerald-400' : 'text-amber-400'}`}>
|
||||||
|
{deployment.available_replicas ?? deployment.availableReplicas} / {deployment.replicas}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-400 truncate max-w-[200px]">{deployment.image}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-400">{deployment.created_at || deployment.createdAt}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="services" className="mt-4">
|
||||||
|
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-slate-800">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">类型</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">ClusterIP</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">端口</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Selector</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-800">
|
||||||
|
{services.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="px-4 py-8 text-center text-slate-500">暂无Service数据</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
services.map((service) => (
|
||||||
|
<tr key={service.id || service.name} className="hover:bg-slate-800/50">
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-200">{service.name}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{service.namespace}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
service.type === 'ClusterIP'
|
||||||
|
? 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
||||||
|
: service.type === 'NodePort'
|
||||||
|
? 'border-purple-500/30 text-purple-400 bg-purple-500/10'
|
||||||
|
: 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{service.type}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{service.cluster_ip ?? service.clusterIP}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{service.ports}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-400">{service.selector}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="ingresses" className="mt-4">
|
||||||
|
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-slate-800">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Hosts</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">后端服务</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">TLS</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-slate-800">
|
||||||
|
{ingresses.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="px-4 py-8 text-center text-slate-500">暂无Ingress数据</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
ingresses.map((ingress) => (
|
||||||
|
<tr key={ingress.id || ingress.name} className="hover:bg-slate-800/50">
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-200">{ingress.name}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{ingress.namespace}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{ingress.hosts}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-slate-300">{ingress.backend}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
ingress.tls
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: 'border-slate-700 text-slate-400'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{ingress.tls ? '已启用' : '未启用'}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="events" className="mt-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[
|
||||||
|
{ type: 'Normal', reason: 'Started', message: 'Started container nginx', time: '2分钟前' },
|
||||||
|
{ type: 'Normal', reason: 'Created', message: 'Created pod nginx-deployment-xxx', time: '5分钟前' },
|
||||||
|
{ type: 'Warning', reason: 'FailedScheduling', message: '0/3 nodes are available', time: '10分钟前' },
|
||||||
|
{ type: 'Normal', reason: 'Pulling', message: 'Pulling image "nginx:latest"', time: '15分钟前' },
|
||||||
|
{ type: 'Normal', reason: 'Pulled', message: 'Successfully pulled image', time: '12分钟前' },
|
||||||
|
].map((event, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center gap-3 p-3 rounded-lg bg-slate-800/50"
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
event.type === 'Normal'
|
||||||
|
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
||||||
|
: 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{event.type}
|
||||||
|
</Badge>
|
||||||
|
<span className="text-sm font-medium text-slate-300 min-w-[120px]">{event.reason}</span>
|
||||||
|
<span className="text-sm text-slate-400 flex-1">{event.message}</span>
|
||||||
|
<span className="text-xs text-slate-500">{event.time}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { k8sApi } from '@/services/api';
|
||||||
|
|
||||||
|
const emptyForm = {
|
||||||
|
name: '',
|
||||||
|
version: '',
|
||||||
|
description: '',
|
||||||
|
config_type: 1, // 0=Token, 1=Kubeconfig
|
||||||
|
api_server: '',
|
||||||
|
token: '',
|
||||||
|
kube_config: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function K8sClusterDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
editingCluster,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editingCluster: any;
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const [formData, setFormData] = useState({ ...emptyForm });
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
// 打开时同步表单(编辑时填充,新建时重置)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
if (editingCluster) {
|
||||||
|
setFormData({
|
||||||
|
name: editingCluster.name || '',
|
||||||
|
version: editingCluster.version || '',
|
||||||
|
description: editingCluster.description || '',
|
||||||
|
config_type: Number(editingCluster.config_type ?? 1),
|
||||||
|
api_server: editingCluster.api_server || '',
|
||||||
|
token: editingCluster.token || '',
|
||||||
|
kube_config: editingCluster.kube_config || '',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setFormData({ ...emptyForm });
|
||||||
|
}
|
||||||
|
}, [open, editingCluster]);
|
||||||
|
|
||||||
|
// 从 kubeconfig YAML 中解析 server 地址
|
||||||
|
const parseApiServer = (yaml: string): string => {
|
||||||
|
const match = yaml.match(/^\s*server:\s*(\S+)\s*$/m);
|
||||||
|
return match ? match[1] : '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKubeConfigChange = (value: string) => {
|
||||||
|
const server = parseApiServer(value);
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
kube_config: value,
|
||||||
|
api_server: server || prev.api_server,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!formData.name.trim()) return;
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
const payload = {
|
||||||
|
name: formData.name,
|
||||||
|
version: formData.version,
|
||||||
|
description: formData.description,
|
||||||
|
config_type: formData.config_type,
|
||||||
|
api_server: formData.api_server,
|
||||||
|
token: formData.config_type === 0 ? formData.token : '',
|
||||||
|
kube_config: formData.config_type === 1 ? formData.kube_config : '',
|
||||||
|
};
|
||||||
|
if (editingCluster) {
|
||||||
|
await k8sApi.updateCluster(editingCluster.id, payload);
|
||||||
|
} else {
|
||||||
|
await k8sApi.createCluster(payload);
|
||||||
|
}
|
||||||
|
onOpenChange(false);
|
||||||
|
onSaved();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('保存集群失败:', e);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-[var(--dg-text-primary)]">
|
||||||
|
{editingCluster ? '编辑集群' : '添加集群'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-[var(--dg-text-secondary)]">
|
||||||
|
{editingCluster ? '修改集群接入配置' : '配置新的 Kubernetes 集群接入信息'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">集群名称</Label>
|
||||||
|
<Input
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
placeholder="例如:prod-cluster"
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">版本(可选)</Label>
|
||||||
|
<Input
|
||||||
|
value={formData.version}
|
||||||
|
onChange={(e) => setFormData({ ...formData, version: e.target.value })}
|
||||||
|
placeholder="例如:1.28.0"
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
|
||||||
|
<Input
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||||
|
placeholder="集群用途描述"
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">接入方式</Label>
|
||||||
|
<RadioGroup
|
||||||
|
value={String(formData.config_type)}
|
||||||
|
onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })}
|
||||||
|
className="flex gap-4"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]">
|
||||||
|
<RadioGroupItem value="0" id="ct-0" />
|
||||||
|
<Label htmlFor="ct-0" className="cursor-pointer text-[var(--dg-text-primary)] font-normal">Token</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]">
|
||||||
|
<RadioGroupItem value="1" id="ct-1" />
|
||||||
|
<Label htmlFor="ct-1" className="cursor-pointer text-[var(--dg-text-primary)] font-normal">Kubeconfig</Label>
|
||||||
|
</div>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">API Server</Label>
|
||||||
|
<Input
|
||||||
|
value={formData.api_server}
|
||||||
|
onChange={(e) => setFormData({ ...formData, api_server: e.target.value })}
|
||||||
|
placeholder="https://10.0.0.1:6443"
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{formData.config_type === 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">Token</Label>
|
||||||
|
<Textarea
|
||||||
|
value={formData.token}
|
||||||
|
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
|
||||||
|
placeholder="粘贴 Service Account Token..."
|
||||||
|
rows={4}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">Kubeconfig</Label>
|
||||||
|
<Textarea
|
||||||
|
value={formData.kube_config}
|
||||||
|
onChange={(e) => handleKubeConfigChange(e.target.value)}
|
||||||
|
placeholder={'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
|
||||||
|
rows={10}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-[var(--dg-text-muted)]">
|
||||||
|
粘贴 kubeconfig 内容后将自动解析 API Server 地址
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => { onOpenChange(false); }}
|
||||||
|
className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={submitting || !formData.name.trim()}
|
||||||
|
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
|
||||||
|
>
|
||||||
|
{submitting ? '保存中...' : editingCluster ? '保存' : '添加'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,12 +3,7 @@ import { cn } from '@/lib/utils';
|
|||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -17,23 +12,12 @@ import {
|
|||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
import {
|
||||||
Cloud,
|
Cloud,
|
||||||
Plus,
|
Plus,
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
Server,
|
Server,
|
||||||
Cpu,
|
|
||||||
Database,
|
Database,
|
||||||
Activity,
|
|
||||||
CheckCircle,
|
CheckCircle,
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
XCircle,
|
XCircle,
|
||||||
@@ -41,27 +25,13 @@ import {
|
|||||||
Settings,
|
Settings,
|
||||||
Eye,
|
Eye,
|
||||||
Trash2,
|
Trash2,
|
||||||
Edit,
|
|
||||||
Terminal,
|
Terminal,
|
||||||
Search,
|
Search,
|
||||||
Filter,
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { k8sApi } from '@/services/api';
|
import { k8sApi } from '@/services/api';
|
||||||
import type { K8sCluster } from '@/types';
|
import type { K8sCluster } from '@/types';
|
||||||
import {
|
import { K8sClusterDetail } from './K8sClusterDetail';
|
||||||
LineChart,
|
import { K8sClusterDialog } from './K8sClusterDialog';
|
||||||
Line,
|
|
||||||
AreaChart,
|
|
||||||
Area,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
ResponsiveContainer,
|
|
||||||
PieChart,
|
|
||||||
Pie,
|
|
||||||
Cell,
|
|
||||||
} from 'recharts';
|
|
||||||
|
|
||||||
export function K8sClusters() {
|
export function K8sClusters() {
|
||||||
const [clusters, setClusters] = useState<any[]>([]);
|
const [clusters, setClusters] = useState<any[]>([]);
|
||||||
@@ -69,26 +39,9 @@ export function K8sClusters() {
|
|||||||
const [selectedCluster, setSelectedCluster] = useState<string | null>(null);
|
const [selectedCluster, setSelectedCluster] = useState<string | null>(null);
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
|
||||||
// 创建/编辑集群表单
|
// 创建/编辑集群弹窗
|
||||||
const [dialogOpen, setDialogOpen] = useState(false);
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
const [editingCluster, setEditingCluster] = useState<any>(null);
|
const [editingCluster, setEditingCluster] = useState<any>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
|
||||||
const [formData, setFormData] = useState({
|
|
||||||
name: '',
|
|
||||||
version: '',
|
|
||||||
description: '',
|
|
||||||
config_type: 1, // 0=Token, 1=Kubeconfig
|
|
||||||
api_server: '',
|
|
||||||
token: '',
|
|
||||||
kube_config: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
// 集群详情关联资源
|
|
||||||
const [nodes, setNodes] = useState<any[]>([]);
|
|
||||||
const [pods, setPods] = useState<any[]>([]);
|
|
||||||
const [deployments, setDeployments] = useState<any[]>([]);
|
|
||||||
const [services, setServices] = useState<any[]>([]);
|
|
||||||
const [ingresses, setIngresses] = useState<any[]>([]);
|
|
||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -107,39 +60,6 @@ export function K8sClusters() {
|
|||||||
loadData();
|
loadData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const loadClusterDetail = async (clusterId: string) => {
|
|
||||||
try {
|
|
||||||
// 后端 ListNodes/ListPods/etc 返回 data 直接为数组(非 {list,total})
|
|
||||||
const [nodesRes, podsRes, depRes, svcRes, ingRes] = await Promise.all([
|
|
||||||
k8sApi.getNodes(clusterId).catch(() => []),
|
|
||||||
k8sApi.getPods(clusterId).catch(() => []),
|
|
||||||
k8sApi.getDeployments(clusterId).catch(() => []),
|
|
||||||
k8sApi.getServices(clusterId).catch(() => []),
|
|
||||||
k8sApi.getIngresses(clusterId).catch(() => []),
|
|
||||||
]);
|
|
||||||
const toArray = (v: any) => (Array.isArray(v) ? v : (v?.list || []));
|
|
||||||
setNodes(toArray(nodesRes));
|
|
||||||
setPods(toArray(podsRes));
|
|
||||||
setDeployments(toArray(depRes));
|
|
||||||
setServices(toArray(svcRes));
|
|
||||||
setIngresses(toArray(ingRes));
|
|
||||||
} catch (e) {
|
|
||||||
console.error('加载集群详情失败:', e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (selectedCluster) {
|
|
||||||
loadClusterDetail(selectedCluster);
|
|
||||||
} else {
|
|
||||||
setNodes([]);
|
|
||||||
setPods([]);
|
|
||||||
setDeployments([]);
|
|
||||||
setServices([]);
|
|
||||||
setIngresses([]);
|
|
||||||
}
|
|
||||||
}, [selectedCluster]);
|
|
||||||
|
|
||||||
const handleDelete = async (id: string) => {
|
const handleDelete = async (id: string) => {
|
||||||
try {
|
try {
|
||||||
await k8sApi.deleteCluster(id);
|
await k8sApi.deleteCluster(id);
|
||||||
@@ -149,81 +69,6 @@ export function K8sClusters() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setFormData({
|
|
||||||
name: '',
|
|
||||||
version: '',
|
|
||||||
description: '',
|
|
||||||
config_type: 1,
|
|
||||||
api_server: '',
|
|
||||||
token: '',
|
|
||||||
kube_config: '',
|
|
||||||
});
|
|
||||||
setEditingCluster(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const openCreateDialog = () => {
|
|
||||||
resetForm();
|
|
||||||
setDialogOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const openEditDialog = (cluster: any) => {
|
|
||||||
setEditingCluster(cluster);
|
|
||||||
setFormData({
|
|
||||||
name: cluster.name || '',
|
|
||||||
version: cluster.version || '',
|
|
||||||
description: cluster.description || '',
|
|
||||||
config_type: Number(cluster.config_type ?? 1),
|
|
||||||
api_server: cluster.api_server || '',
|
|
||||||
token: cluster.token || '',
|
|
||||||
kube_config: cluster.kube_config || '',
|
|
||||||
});
|
|
||||||
setDialogOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 从 kubeconfig YAML 中解析 server 地址
|
|
||||||
const parseApiServer = (yaml: string): string => {
|
|
||||||
const match = yaml.match(/^\s*server:\s*(\S+)\s*$/m);
|
|
||||||
return match ? match[1] : '';
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKubeConfigChange = (value: string) => {
|
|
||||||
const server = parseApiServer(value);
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
kube_config: value,
|
|
||||||
api_server: server || prev.api_server,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
|
||||||
if (!formData.name.trim()) return;
|
|
||||||
try {
|
|
||||||
setSubmitting(true);
|
|
||||||
const payload = {
|
|
||||||
name: formData.name,
|
|
||||||
version: formData.version,
|
|
||||||
description: formData.description,
|
|
||||||
config_type: formData.config_type,
|
|
||||||
api_server: formData.api_server,
|
|
||||||
token: formData.config_type === 0 ? formData.token : '',
|
|
||||||
kube_config: formData.config_type === 1 ? formData.kube_config : '',
|
|
||||||
};
|
|
||||||
if (editingCluster) {
|
|
||||||
await k8sApi.updateCluster(editingCluster.id, payload);
|
|
||||||
} else {
|
|
||||||
await k8sApi.createCluster(payload);
|
|
||||||
}
|
|
||||||
setDialogOpen(false);
|
|
||||||
resetForm();
|
|
||||||
loadData();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('保存集群失败:', e);
|
|
||||||
} finally {
|
|
||||||
setSubmitting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const filteredClusters = clusters.filter(
|
const filteredClusters = clusters.filter(
|
||||||
(cluster) =>
|
(cluster) =>
|
||||||
(cluster.name || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
|
(cluster.name || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
@@ -260,17 +105,6 @@ export function K8sClusters() {
|
|||||||
|
|
||||||
const clusterDetail = selectedCluster ? clusters.find((c) => c.id === selectedCluster) : null;
|
const clusterDetail = selectedCluster ? clusters.find((c) => c.id === selectedCluster) : null;
|
||||||
|
|
||||||
// 模拟资源使用趋势数据
|
|
||||||
const resourceData = [
|
|
||||||
{ time: '00:00', cpu: 45, memory: 52 },
|
|
||||||
{ time: '04:00', cpu: 38, memory: 48 },
|
|
||||||
{ time: '08:00', cpu: 62, memory: 68 },
|
|
||||||
{ time: '12:00', cpu: 78, memory: 82 },
|
|
||||||
{ time: '16:00', cpu: 72, memory: 76 },
|
|
||||||
{ time: '20:00', cpu: 58, memory: 64 },
|
|
||||||
{ time: '24:00', cpu: 48, memory: 56 },
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Page Header */}
|
{/* Page Header */}
|
||||||
@@ -288,7 +122,7 @@ export function K8sClusters() {
|
|||||||
<RefreshCw className={cn('h-4 w-4 mr-2', loading && 'animate-spin')} />
|
<RefreshCw className={cn('h-4 w-4 mr-2', loading && 'animate-spin')} />
|
||||||
刷新
|
刷新
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={openCreateDialog}>
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={() => { setEditingCluster(null); setDialogOpen(true); }}>
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
添加集群
|
添加集群
|
||||||
</Button>
|
</Button>
|
||||||
@@ -437,7 +271,8 @@ export function K8sClusters() {
|
|||||||
className="text-slate-300 focus:bg-slate-700 focus:text-slate-100"
|
className="text-slate-300 focus:bg-slate-700 focus:text-slate-100"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
openEditDialog(cluster);
|
setEditingCluster(cluster);
|
||||||
|
setDialogOpen(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Settings className="h-4 w-4 mr-2" />
|
<Settings className="h-4 w-4 mr-2" />
|
||||||
@@ -515,548 +350,16 @@ export function K8sClusters() {
|
|||||||
|
|
||||||
{/* Cluster Detail */}
|
{/* Cluster Detail */}
|
||||||
{clusterDetail && (
|
{clusterDetail && (
|
||||||
<Card className="bg-slate-900 border-slate-800">
|
<K8sClusterDetail cluster={clusterDetail} onClose={() => setSelectedCluster(null)} />
|
||||||
<CardHeader>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Cloud className="h-6 w-6 text-blue-400" />
|
|
||||||
<div>
|
|
||||||
<CardTitle className="text-slate-100">{clusterDetail.name}</CardTitle>
|
|
||||||
<CardDescription className="text-slate-500">
|
|
||||||
{clusterDetail.version} · {clusterDetail.node_count || 0} 节点 · 创建于{' '}
|
|
||||||
{clusterDetail.created_at ? new Date(clusterDetail.created_at).toLocaleDateString() : '-'}
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="text-slate-400 hover:text-slate-100"
|
|
||||||
onClick={() => setSelectedCluster(null)}
|
|
||||||
>
|
|
||||||
<XCircle className="h-4 w-4 mr-2" />
|
|
||||||
关闭
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<Tabs defaultValue="overview" className="w-full">
|
|
||||||
<TabsList className="bg-slate-800 border border-slate-700 flex-wrap h-auto">
|
|
||||||
<TabsTrigger value="overview" className="data-[state=active]:bg-slate-700">
|
|
||||||
概览
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="nodes" className="data-[state=active]:bg-slate-700">
|
|
||||||
节点 ({nodes.length})
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="pods" className="data-[state=active]:bg-slate-700">
|
|
||||||
Pod ({pods.length})
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="deployments" className="data-[state=active]:bg-slate-700">
|
|
||||||
Deployment ({deployments.length})
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="services" className="data-[state=active]:bg-slate-700">
|
|
||||||
Service ({services.length})
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="ingresses" className="data-[state=active]:bg-slate-700">
|
|
||||||
Ingress ({ingresses.length})
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="events" className="data-[state=active]:bg-slate-700">
|
|
||||||
事件
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
|
||||||
|
|
||||||
<TabsContent value="overview" className="mt-4 space-y-4">
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
|
||||||
<Card className="bg-slate-800/50 border-slate-700">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<CardTitle className="text-sm text-slate-400">资源使用趋势</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="h-[200px]">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<AreaChart data={resourceData}>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
|
|
||||||
<XAxis dataKey="time" stroke="#475569" fontSize={12} />
|
|
||||||
<YAxis stroke="#475569" fontSize={12} />
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: '#0f172a',
|
|
||||||
border: '1px solid #1e293b',
|
|
||||||
borderRadius: '6px',
|
|
||||||
color: '#f8fafc',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="cpu"
|
|
||||||
stroke="#3b82f6"
|
|
||||||
fillOpacity={1}
|
|
||||||
fill="url(#colorCpu)"
|
|
||||||
name="CPU"
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="memory"
|
|
||||||
stroke="#10b981"
|
|
||||||
fillOpacity={1}
|
|
||||||
fill="url(#colorMemory)"
|
|
||||||
name="内存"
|
|
||||||
/>
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card className="bg-slate-800/50 border-slate-700">
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<CardTitle className="text-sm text-slate-400">资源分布</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="text-center p-4 rounded-lg bg-slate-800">
|
|
||||||
<div className="text-3xl font-bold text-blue-400">{clusterDetail.pod_count || 0}</div>
|
|
||||||
<div className="text-sm text-slate-500 mt-1">Pod</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-4 rounded-lg bg-slate-800">
|
|
||||||
<div className="text-3xl font-bold text-emerald-400">{clusterDetail.service_count || 0}</div>
|
|
||||||
<div className="text-sm text-slate-500 mt-1">Service</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-4 rounded-lg bg-slate-800">
|
|
||||||
<div className="text-3xl font-bold text-purple-400">{clusterDetail.deployment_count || 0}</div>
|
|
||||||
<div className="text-sm text-slate-500 mt-1">Deployment</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-4 rounded-lg bg-slate-800">
|
|
||||||
<div className="text-3xl font-bold text-amber-400">{clusterDetail.node_count || 0}</div>
|
|
||||||
<div className="text-sm text-slate-500 mt-1">节点</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="nodes" className="mt-4">
|
|
||||||
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
|
||||||
<table className="w-full">
|
|
||||||
<thead className="bg-slate-800">
|
|
||||||
<tr>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">角色</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">状态</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">CPU</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">内存</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Pod</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">操作系统</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-slate-800">
|
|
||||||
{nodes.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={7} className="px-4 py-8 text-center text-slate-500">暂无节点数据</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
nodes.map((node) => (
|
|
||||||
<tr key={node.id || node.name} className="hover:bg-slate-800/50">
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-200">{node.name}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
node.role === 'master'
|
|
||||||
? 'border-purple-500/30 text-purple-400 bg-purple-500/10'
|
|
||||||
: 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{node.role === 'master' ? 'Master' : 'Worker'}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
(node.status || '').toLowerCase() === 'ready'
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{(node.status || '').toLowerCase() === 'ready' ? 'Ready' : 'NotReady'}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">
|
|
||||||
{Number(node.cpu_usage || 0).toFixed(1)}% / {node.cpu}核
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">
|
|
||||||
{Number(node.memory_usage || 0).toFixed(1)}% / {node.memory}GB
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{node.pods ?? node.pod_count ?? 0}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-400">{node.os}</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="pods" className="mt-4">
|
|
||||||
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
|
||||||
<table className="w-full">
|
|
||||||
<thead className="bg-slate-800">
|
|
||||||
<tr>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">状态</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">重启次数</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">CPU</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">内存</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">节点</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-slate-800">
|
|
||||||
{pods.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={7} className="px-4 py-8 text-center text-slate-500">暂无Pod数据</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
pods.map((pod) => (
|
|
||||||
<tr key={pod.id || pod.name} className="hover:bg-slate-800/50">
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-200">{pod.name}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
|
||||||
{pod.namespace}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
(pod.status || '').toLowerCase() === 'running'
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: (pod.status || '').toLowerCase() === 'pending'
|
|
||||||
? 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
: 'border-red-500/30 text-red-400 bg-red-500/10'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{pod.status}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{pod.restart_count ?? 0}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{Number(pod.cpu_usage || 0).toFixed(1)}m</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{Number(pod.memory_usage || 0).toFixed(0)}Mi</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-400">{pod.node_name}</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="deployments" className="mt-4">
|
|
||||||
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
|
||||||
<table className="w-full">
|
|
||||||
<thead className="bg-slate-800">
|
|
||||||
<tr>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">副本数</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">可用副本</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">镜像</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">创建时间</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-slate-800">
|
|
||||||
{deployments.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={6} className="px-4 py-8 text-center text-slate-500">暂无Deployment数据</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
deployments.map((deployment) => (
|
|
||||||
<tr key={deployment.id || deployment.name} className="hover:bg-slate-800/50">
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-200">{deployment.name}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
|
||||||
{deployment.namespace}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{deployment.replicas}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<span className={`text-sm ${(deployment.available_replicas ?? deployment.availableReplicas) === deployment.replicas ? 'text-emerald-400' : 'text-amber-400'}`}>
|
|
||||||
{deployment.available_replicas ?? deployment.availableReplicas} / {deployment.replicas}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-400 truncate max-w-[200px]">{deployment.image}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-400">{deployment.created_at || deployment.createdAt}</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="services" className="mt-4">
|
|
||||||
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
|
||||||
<table className="w-full">
|
|
||||||
<thead className="bg-slate-800">
|
|
||||||
<tr>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">类型</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">ClusterIP</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">端口</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Selector</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-slate-800">
|
|
||||||
{services.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={6} className="px-4 py-8 text-center text-slate-500">暂无Service数据</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
services.map((service) => (
|
|
||||||
<tr key={service.id || service.name} className="hover:bg-slate-800/50">
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-200">{service.name}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
|
||||||
{service.namespace}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
service.type === 'ClusterIP'
|
|
||||||
? 'border-blue-500/30 text-blue-400 bg-blue-500/10'
|
|
||||||
: service.type === 'NodePort'
|
|
||||||
? 'border-purple-500/30 text-purple-400 bg-purple-500/10'
|
|
||||||
: 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{service.type}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{service.cluster_ip ?? service.clusterIP}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{service.ports}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-400">{service.selector}</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="ingresses" className="mt-4">
|
|
||||||
<div className="border rounded-lg border-slate-700 overflow-hidden">
|
|
||||||
<table className="w-full">
|
|
||||||
<thead className="bg-slate-800">
|
|
||||||
<tr>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">名称</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">命名空间</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">Hosts</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">后端服务</th>
|
|
||||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-400">TLS</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-slate-800">
|
|
||||||
{ingresses.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={5} className="px-4 py-8 text-center text-slate-500">暂无Ingress数据</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
ingresses.map((ingress) => (
|
|
||||||
<tr key={ingress.id || ingress.name} className="hover:bg-slate-800/50">
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-200">{ingress.name}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge variant="outline" className="border-slate-700 text-slate-400">
|
|
||||||
{ingress.namespace}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{ingress.hosts}</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-slate-300">{ingress.backend}</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
ingress.tls
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: 'border-slate-700 text-slate-400'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{ingress.tls ? '已启用' : '未启用'}
|
|
||||||
</Badge>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="events" className="mt-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
{[
|
|
||||||
{ type: 'Normal', reason: 'Started', message: 'Started container nginx', time: '2分钟前' },
|
|
||||||
{ type: 'Normal', reason: 'Created', message: 'Created pod nginx-deployment-xxx', time: '5分钟前' },
|
|
||||||
{ type: 'Warning', reason: 'FailedScheduling', message: '0/3 nodes are available', time: '10分钟前' },
|
|
||||||
{ type: 'Normal', reason: 'Pulling', message: 'Pulling image "nginx:latest"', time: '15分钟前' },
|
|
||||||
{ type: 'Normal', reason: 'Pulled', message: 'Successfully pulled image', time: '12分钟前' },
|
|
||||||
].map((event, index) => (
|
|
||||||
<div
|
|
||||||
key={index}
|
|
||||||
className="flex items-center gap-3 p-3 rounded-lg bg-slate-800/50"
|
|
||||||
>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={
|
|
||||||
event.type === 'Normal'
|
|
||||||
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
|
|
||||||
: 'border-amber-500/30 text-amber-400 bg-amber-500/10'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{event.type}
|
|
||||||
</Badge>
|
|
||||||
<span className="text-sm font-medium text-slate-300 min-w-[120px]">{event.reason}</span>
|
|
||||||
<span className="text-sm text-slate-400 flex-1">{event.message}</span>
|
|
||||||
<span className="text-xs text-slate-500">{event.time}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
</Tabs>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 创建/编辑集群 Dialog */}
|
{/* 创建/编辑集群 Dialog */}
|
||||||
<Dialog open={dialogOpen} onOpenChange={(o) => { setDialogOpen(o); if (!o) resetForm(); }}>
|
<K8sClusterDialog
|
||||||
<DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl">
|
open={dialogOpen}
|
||||||
<DialogHeader>
|
onOpenChange={setDialogOpen}
|
||||||
<DialogTitle className="text-[var(--dg-text-primary)]">
|
editingCluster={editingCluster}
|
||||||
{editingCluster ? '编辑集群' : '添加集群'}
|
onSaved={loadData}
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription className="text-[var(--dg-text-secondary)]">
|
|
||||||
{editingCluster ? '修改集群接入配置' : '配置新的 Kubernetes 集群接入信息'}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">集群名称</Label>
|
|
||||||
<Input
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
|
||||||
placeholder="例如:prod-cluster"
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">版本(可选)</Label>
|
|
||||||
<Input
|
|
||||||
value={formData.version}
|
|
||||||
onChange={(e) => setFormData({ ...formData, version: e.target.value })}
|
|
||||||
placeholder="例如:1.28.0"
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
|
|
||||||
<Input
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
||||||
placeholder="集群用途描述"
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">接入方式</Label>
|
|
||||||
<RadioGroup
|
|
||||||
value={String(formData.config_type)}
|
|
||||||
onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })}
|
|
||||||
className="flex gap-4"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]">
|
|
||||||
<RadioGroupItem value="0" id="ct-0" />
|
|
||||||
<Label htmlFor="ct-0" className="cursor-pointer text-[var(--dg-text-primary)] font-normal">Token</Label>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]">
|
|
||||||
<RadioGroupItem value="1" id="ct-1" />
|
|
||||||
<Label htmlFor="ct-1" className="cursor-pointer text-[var(--dg-text-primary)] font-normal">Kubeconfig</Label>
|
|
||||||
</div>
|
|
||||||
</RadioGroup>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">API Server</Label>
|
|
||||||
<Input
|
|
||||||
value={formData.api_server}
|
|
||||||
onChange={(e) => setFormData({ ...formData, api_server: e.target.value })}
|
|
||||||
placeholder="https://10.0.0.1:6443"
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{formData.config_type === 0 ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">Token</Label>
|
|
||||||
<Textarea
|
|
||||||
value={formData.token}
|
|
||||||
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
|
|
||||||
placeholder="粘贴 Service Account Token..."
|
|
||||||
rows={4}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">Kubeconfig</Label>
|
|
||||||
<Textarea
|
|
||||||
value={formData.kube_config}
|
|
||||||
onChange={(e) => handleKubeConfigChange(e.target.value)}
|
|
||||||
placeholder={'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
|
|
||||||
rows={10}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-[var(--dg-text-muted)]">
|
|
||||||
粘贴 kubeconfig 内容后将自动解析 API Server 地址
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => { setDialogOpen(false); resetForm(); }}
|
|
||||||
className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleSubmit}
|
|
||||||
disabled={submitting || !formData.name.trim()}
|
|
||||||
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
|
|
||||||
>
|
|
||||||
{submitting ? '保存中...' : editingCluster ? '保存' : '添加'}
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useConfirm } from '@/components/ui/confirm-dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Plus, Trash2, Loader2 } from 'lucide-react';
|
||||||
|
import { alertApi } from '@/services/api';
|
||||||
|
import { CHANNEL_TYPES, getChannelTypeLabel } from './alertShared';
|
||||||
|
|
||||||
|
const defaultChannelForm = { name: '', type: 'dingtalk', config: '', enabled: true };
|
||||||
|
|
||||||
|
export function AlertChannelDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
notifyChannels,
|
||||||
|
onChannelsChanged,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
notifyChannels: any[];
|
||||||
|
onChannelsChanged: () => void;
|
||||||
|
}) {
|
||||||
|
const _confirm = useConfirm();
|
||||||
|
const [editingChannel, setEditingChannel] = useState<any>(null);
|
||||||
|
const [channelSaving, setChannelSaving] = useState(false);
|
||||||
|
const [channelTesting, setChannelTesting] = useState<number | null>(null);
|
||||||
|
const [channelForm, setChannelForm] = useState({ ...defaultChannelForm });
|
||||||
|
|
||||||
|
// 打开时重置为新建模式
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
setEditingChannel(null);
|
||||||
|
setChannelForm({ ...defaultChannelForm });
|
||||||
|
}
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
const openEditChannel = (ch: any) => {
|
||||||
|
setEditingChannel(ch);
|
||||||
|
setChannelForm({
|
||||||
|
name: ch.name || '',
|
||||||
|
type: ch.type || 'dingtalk',
|
||||||
|
config: ch.config || '',
|
||||||
|
enabled: ch.enabled !== false,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetChannelForm = () => {
|
||||||
|
setEditingChannel(null);
|
||||||
|
setChannelForm({ ...defaultChannelForm });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveChannel = async () => {
|
||||||
|
if (!channelForm.name.trim()) return;
|
||||||
|
setChannelSaving(true);
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
name: channelForm.name.trim(),
|
||||||
|
type: channelForm.type,
|
||||||
|
config: channelForm.config.trim(),
|
||||||
|
};
|
||||||
|
if (editingChannel) {
|
||||||
|
await alertApi.updateNotifyChannel(editingChannel.id, { ...payload, enabled: channelForm.enabled });
|
||||||
|
} else {
|
||||||
|
await alertApi.createNotifyChannel(payload);
|
||||||
|
}
|
||||||
|
resetChannelForm();
|
||||||
|
onChannelsChanged();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to save notify channel:', error);
|
||||||
|
} finally {
|
||||||
|
setChannelSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteChannel = async (id: any) => {
|
||||||
|
{ const ok = await _confirm({ title: '删除通知渠道', description: '确定删除此通知渠道?', confirmText: '删除', variant: 'destructive' }); if (!ok) return; }
|
||||||
|
try {
|
||||||
|
await alertApi.deleteNotifyChannel(id);
|
||||||
|
if (editingChannel && editingChannel.id === id) resetChannelForm();
|
||||||
|
onChannelsChanged();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete notify channel:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleChannel = async (ch: any) => {
|
||||||
|
try {
|
||||||
|
await alertApi.updateNotifyChannel(ch.id, { enabled: !ch.enabled });
|
||||||
|
onChannelsChanged();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to toggle notify channel:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTestChannel = async (id: any) => {
|
||||||
|
setChannelTesting(id);
|
||||||
|
try {
|
||||||
|
await alertApi.testNotifyChannel(id);
|
||||||
|
onChannelsChanged();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to test notify channel:', error);
|
||||||
|
} finally {
|
||||||
|
setChannelTesting(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-700 text-slate-100 max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100">通知渠道配置</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
管理告警通知渠道(钉钉/企业微信/邮件/短信/Webhook),配置后可在告警规则中引用
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 max-h-[65vh] overflow-y-auto pr-1">
|
||||||
|
{/* 渠道列表 */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-slate-300 text-sm">已配置渠道</Label>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
className="h-7 border-slate-700 text-slate-300 hover:bg-slate-800 text-xs"
|
||||||
|
onClick={resetChannelForm}
|
||||||
|
>
|
||||||
|
<Plus className="h-3 w-3 mr-1" />
|
||||||
|
新建
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{notifyChannels.length === 0 ? (
|
||||||
|
<div className="text-center py-8 text-sm text-slate-600 border border-dashed border-slate-800 rounded-lg">
|
||||||
|
暂无通知渠道,请在右侧添加
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{notifyChannels.map((ch) => (
|
||||||
|
<div
|
||||||
|
key={ch.id}
|
||||||
|
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
|
||||||
|
editingChannel && editingChannel.id === ch.id
|
||||||
|
? 'border-blue-500/50 bg-blue-500/5'
|
||||||
|
: 'border-slate-800 bg-slate-800/30 hover:border-slate-700'
|
||||||
|
}`}
|
||||||
|
onClick={() => openEditChannel(ch)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<span className="text-sm text-slate-200 truncate">{ch.name}</span>
|
||||||
|
<Badge variant="outline" className="border-slate-600 text-slate-400 text-[10px] py-0">
|
||||||
|
{getChannelTypeLabel(ch.type)}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={ch.enabled !== false}
|
||||||
|
onCheckedChange={() => handleToggleChannel(ch)}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
className="data-[state=checked]:bg-emerald-600 scale-90"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between mt-2">
|
||||||
|
{ch.test_status === 'success' ? (
|
||||||
|
<span className="text-[11px] text-emerald-400">测试通过</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px] text-slate-600">未测试</span>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-6 px-2 text-slate-400 hover:text-slate-200 hover:bg-slate-700 text-xs"
|
||||||
|
disabled={channelTesting === ch.id}
|
||||||
|
onClick={() => handleTestChannel(ch.id)}
|
||||||
|
>
|
||||||
|
{channelTesting === ch.id ? <Loader2 className="h-3 w-3 animate-spin" /> : '测试'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-6 px-2 text-red-400/70 hover:text-red-400 hover:bg-red-500/10 text-xs"
|
||||||
|
onClick={() => handleDeleteChannel(ch.id)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 渠道表单 */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Label className="text-slate-300 text-sm">
|
||||||
|
{editingChannel ? '编辑渠道' : '新建渠道'}
|
||||||
|
</Label>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-400 text-xs">渠道名称 <span className="text-red-400">*</span></Label>
|
||||||
|
<Input
|
||||||
|
value={channelForm.name}
|
||||||
|
onChange={(e) => setChannelForm({ ...channelForm, name: e.target.value })}
|
||||||
|
placeholder="如:运维告警群"
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 h-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-400 text-xs">渠道类型</Label>
|
||||||
|
<select
|
||||||
|
value={channelForm.type}
|
||||||
|
onChange={(e) => setChannelForm({ ...channelForm, type: e.target.value })}
|
||||||
|
className="w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
{CHANNEL_TYPES.map(({ key, label }) => (
|
||||||
|
<option key={key} value={key}>{label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-400 text-xs">配置(JSON)</Label>
|
||||||
|
<Textarea
|
||||||
|
value={channelForm.config}
|
||||||
|
onChange={(e) => setChannelForm({ ...channelForm, config: e.target.value })}
|
||||||
|
placeholder={CHANNEL_TYPES.find((t) => t.key === channelForm.type)?.placeholder || ''}
|
||||||
|
rows={5}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 font-mono text-xs resize-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{editingChannel && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Switch
|
||||||
|
checked={channelForm.enabled}
|
||||||
|
onCheckedChange={(v) => setChannelForm({ ...channelForm, enabled: v })}
|
||||||
|
className="data-[state=checked]:bg-emerald-600"
|
||||||
|
/>
|
||||||
|
<Label className="text-slate-400 text-xs">启用此渠道</Label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="border-slate-700 text-slate-300 hover:bg-slate-800"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
关闭
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
disabled={!channelForm.name.trim() || channelSaving}
|
||||||
|
onClick={handleSaveChannel}
|
||||||
|
>
|
||||||
|
{channelSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||||
|
{editingChannel ? '保存修改' : '添加渠道'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useConfirm } from '@/components/ui/confirm-dialog';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table';
|
||||||
|
import { Search, AlertTriangle, Bell, CheckCircle, Loader2 } from 'lucide-react';
|
||||||
|
import { alertApi } from '@/services/api';
|
||||||
|
|
||||||
|
export function AlertEventsTab({
|
||||||
|
alerts,
|
||||||
|
loading,
|
||||||
|
onReload,
|
||||||
|
}: {
|
||||||
|
alerts: any[];
|
||||||
|
loading: boolean;
|
||||||
|
onReload: () => void;
|
||||||
|
}) {
|
||||||
|
const _confirm = useConfirm();
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [severityFilter, setSeverityFilter] = useState<string>('all');
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||||
|
|
||||||
|
const filteredEvents = alerts.filter((event) => {
|
||||||
|
const matchesSearch =
|
||||||
|
((event.rule && event.rule.name) || event.message || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
(event.target || '').toLowerCase().includes(searchQuery.toLowerCase());
|
||||||
|
const matchesSeverity = severityFilter === 'all' || event.severity === severityFilter;
|
||||||
|
const matchesStatus = statusFilter === 'all' || event.status === statusFilter;
|
||||||
|
return matchesSearch && matchesSeverity && matchesStatus;
|
||||||
|
});
|
||||||
|
|
||||||
|
const getSeverityBadge = (severity: any) => {
|
||||||
|
switch (severity) {
|
||||||
|
case 'critical':
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10">
|
||||||
|
<AlertTriangle className="h-3 w-3 mr-1" />
|
||||||
|
严重
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
case 'warning':
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className="border-amber-500/30 text-amber-400 bg-amber-500/10">
|
||||||
|
<AlertTriangle className="h-3 w-3 mr-1" />
|
||||||
|
警告
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
case 'info':
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
|
||||||
|
<Bell className="h-3 w-3 mr-1" />
|
||||||
|
提示
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = (status: any) => {
|
||||||
|
switch (status) {
|
||||||
|
case 'firing':
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10 animate-pulse">
|
||||||
|
触发中
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
case 'resolved':
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
|
||||||
|
已恢复
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAcknowledge = async (id: any) => {
|
||||||
|
try {
|
||||||
|
await alertApi.acknowledge(id);
|
||||||
|
onReload();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to acknowledge alert:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-4 space-y-4">
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
|
<div className="relative w-64">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
|
||||||
|
<Input
|
||||||
|
placeholder="搜索告警名称或目标..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
value={severityFilter}
|
||||||
|
onChange={(e) => setSeverityFilter(e.target.value)}
|
||||||
|
className="h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
<option value="all">全部级别</option>
|
||||||
|
<option value="critical">严重</option>
|
||||||
|
<option value="warning">警告</option>
|
||||||
|
<option value="info">提示</option>
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
value={statusFilter}
|
||||||
|
onChange={(e) => setStatusFilter(e.target.value)}
|
||||||
|
className="h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
<option value="all">全部状态</option>
|
||||||
|
<option value="firing">触发中</option>
|
||||||
|
<option value="resolved">已恢复</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Events Table */}
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="border-t border-slate-800">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800 hover:bg-transparent">
|
||||||
|
<TableHead className="text-slate-400">级别</TableHead>
|
||||||
|
<TableHead className="text-slate-400">告警名称</TableHead>
|
||||||
|
<TableHead className="text-slate-400">状态</TableHead>
|
||||||
|
<TableHead className="text-slate-400">目标</TableHead>
|
||||||
|
<TableHead className="text-slate-400">当前值</TableHead>
|
||||||
|
<TableHead className="text-slate-400">阈值</TableHead>
|
||||||
|
<TableHead className="text-slate-400">开始时间</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{loading ? (
|
||||||
|
<TableRow className="border-slate-800">
|
||||||
|
<TableCell colSpan={8} className="text-center text-slate-500 py-8">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin inline mr-2" />
|
||||||
|
加载中...
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : filteredEvents.map((event) => (
|
||||||
|
<TableRow key={event.id} className="border-slate-800 hover:bg-slate-800/50">
|
||||||
|
<TableCell>{getSeverityBadge(event.severity)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm font-medium text-slate-200">
|
||||||
|
{(event.rule && event.rule.name) || event.message}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{getStatusBadge(event.status)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-300">{event.target}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-300">{event.value}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-500">{event.threshold}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-400">
|
||||||
|
{event.created_at ? new Date(event.created_at).toLocaleString() : '--'}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
{event.status === 'firing' && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 text-slate-400 hover:text-emerald-400"
|
||||||
|
onClick={() => handleAcknowledge(event.id)}
|
||||||
|
>
|
||||||
|
<CheckCircle className="h-4 w-4 mr-1" />
|
||||||
|
确认
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { alertApi } from '@/services/api';
|
||||||
|
import { parseChannels, getChannelIcon, getChannelTypeLabel } from './alertShared';
|
||||||
|
|
||||||
|
const emptyRuleForm = {
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
type: 'metric',
|
||||||
|
source: 'prometheus',
|
||||||
|
expression: '',
|
||||||
|
severity: 'warning',
|
||||||
|
duration: 300,
|
||||||
|
notify_channels: [] as string[],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AlertRuleDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
editingRule,
|
||||||
|
notifyChannels,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editingRule: any;
|
||||||
|
notifyChannels: any[];
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const [ruleForm, setRuleForm] = useState({ ...emptyRuleForm });
|
||||||
|
const [ruleSaving, setRuleSaving] = useState(false);
|
||||||
|
|
||||||
|
// 打开时同步表单(编辑时填充,新建时重置)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
if (editingRule) {
|
||||||
|
setRuleForm({
|
||||||
|
name: editingRule.name || '',
|
||||||
|
description: editingRule.description || '',
|
||||||
|
type: editingRule.type || 'metric',
|
||||||
|
source: editingRule.source || 'prometheus',
|
||||||
|
expression: editingRule.expression || '',
|
||||||
|
severity: editingRule.severity || 'warning',
|
||||||
|
duration: editingRule.duration || 300,
|
||||||
|
notify_channels: parseChannels(editingRule.notify_channels),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setRuleForm({ ...emptyRuleForm });
|
||||||
|
}
|
||||||
|
}, [open, editingRule]);
|
||||||
|
|
||||||
|
const toggleNotifyChannel = (channel: string) => {
|
||||||
|
setRuleForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
notify_channels: prev.notify_channels.includes(channel)
|
||||||
|
? prev.notify_channels.filter((c) => c !== channel)
|
||||||
|
: [...prev.notify_channels, channel],
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveRule = async () => {
|
||||||
|
if (!ruleForm.name.trim() || !ruleForm.expression.trim()) return;
|
||||||
|
setRuleSaving(true);
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
name: ruleForm.name.trim(),
|
||||||
|
description: ruleForm.description.trim(),
|
||||||
|
type: ruleForm.type,
|
||||||
|
source: ruleForm.source,
|
||||||
|
expression: ruleForm.expression.trim(),
|
||||||
|
severity: ruleForm.severity,
|
||||||
|
duration: Number(ruleForm.duration) || 0,
|
||||||
|
notify_channels: ruleForm.notify_channels,
|
||||||
|
};
|
||||||
|
if (editingRule) {
|
||||||
|
await alertApi.updateRule(editingRule.id, payload);
|
||||||
|
} else {
|
||||||
|
await alertApi.createRule(payload);
|
||||||
|
}
|
||||||
|
onOpenChange(false);
|
||||||
|
onSaved();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to save rule:', error);
|
||||||
|
} finally {
|
||||||
|
setRuleSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-700 text-slate-100 max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100">
|
||||||
|
{editingRule ? '编辑告警规则' : '新建告警规则'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
{editingRule ? '修改告警规则的触发条件和通知方式' : '配置监控指标的告警触发条件'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">规则名称 <span className="text-red-400">*</span></Label>
|
||||||
|
<Input
|
||||||
|
value={ruleForm.name}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, name: e.target.value })}
|
||||||
|
placeholder="如:CPU 使用率告警"
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">描述</Label>
|
||||||
|
<Textarea
|
||||||
|
value={ruleForm.description}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, description: e.target.value })}
|
||||||
|
placeholder="规则说明"
|
||||||
|
rows={2}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 resize-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">规则类型</Label>
|
||||||
|
<select
|
||||||
|
value={ruleForm.type}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, type: e.target.value })}
|
||||||
|
className="w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
<option value="metric">指标监控</option>
|
||||||
|
<option value="log">日志告警</option>
|
||||||
|
<option value="event">事件告警</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">数据源</Label>
|
||||||
|
<select
|
||||||
|
value={ruleForm.source}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, source: e.target.value })}
|
||||||
|
className="w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
<option value="prometheus">Prometheus</option>
|
||||||
|
<option value="zabbix">Zabbix</option>
|
||||||
|
<option value="custom">自定义</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">触发表达式 <span className="text-red-400">*</span></Label>
|
||||||
|
<Input
|
||||||
|
value={ruleForm.expression}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, expression: e.target.value })}
|
||||||
|
placeholder="如:cpu_usage > 80"
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 font-mono text-sm"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-slate-600">PromQL 或指标表达式,例如 cpu_usage > 80</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">告警级别</Label>
|
||||||
|
<select
|
||||||
|
value={ruleForm.severity}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, severity: e.target.value })}
|
||||||
|
className="w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm"
|
||||||
|
>
|
||||||
|
<option value="info">提示</option>
|
||||||
|
<option value="warning">警告</option>
|
||||||
|
<option value="critical">严重</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">持续时间(秒)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={ruleForm.duration}
|
||||||
|
onChange={(e) => setRuleForm({ ...ruleForm, duration: Number(e.target.value) })}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-slate-300">通知渠道</Label>
|
||||||
|
{notifyChannels.length === 0 ? (
|
||||||
|
<div className="text-xs text-amber-400/80 bg-amber-500/5 border border-amber-500/20 rounded-md px-3 py-2">
|
||||||
|
暂无已配置的通知渠道,请先在「通知渠道配置」中添加
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-wrap gap-3 pt-1">
|
||||||
|
{notifyChannels.map((ch) => {
|
||||||
|
const Icon = getChannelIcon(ch.type);
|
||||||
|
const checked = ruleForm.notify_channels.includes(String(ch.id));
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
key={ch.id}
|
||||||
|
className="flex items-center gap-2 cursor-pointer select-none text-sm text-slate-300"
|
||||||
|
>
|
||||||
|
<Switch
|
||||||
|
checked={checked}
|
||||||
|
onCheckedChange={() => toggleNotifyChannel(String(ch.id))}
|
||||||
|
className="data-[state=checked]:bg-blue-600"
|
||||||
|
/>
|
||||||
|
<Icon className="h-4 w-4 text-slate-400" />
|
||||||
|
<span>
|
||||||
|
{ch.name}
|
||||||
|
<span className="text-xs text-slate-500 ml-1">({getChannelTypeLabel(ch.type)})</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="border-slate-700 text-slate-300 hover:bg-slate-800"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
disabled={!ruleForm.name.trim() || !ruleForm.expression.trim() || ruleSaving}
|
||||||
|
onClick={handleSaveRule}
|
||||||
|
>
|
||||||
|
{ruleSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||||
|
{editingRule ? '保存修改' : '创建规则'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { useConfirm } from '@/components/ui/confirm-dialog';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table';
|
||||||
|
import { Settings, Trash2 } from 'lucide-react';
|
||||||
|
import { alertApi } from '@/services/api';
|
||||||
|
import { renderRuleChannels } from './alertShared';
|
||||||
|
|
||||||
|
export function AlertRulesTab({
|
||||||
|
rules,
|
||||||
|
notifyChannels,
|
||||||
|
onReload,
|
||||||
|
onEditRule,
|
||||||
|
}: {
|
||||||
|
rules: any[];
|
||||||
|
notifyChannels: any[];
|
||||||
|
onReload: () => void;
|
||||||
|
onEditRule: (rule: any) => void;
|
||||||
|
}) {
|
||||||
|
const _confirm = useConfirm();
|
||||||
|
|
||||||
|
const handleDeleteRule = async (id: any) => {
|
||||||
|
{ const ok = await _confirm({ title: '删除告警规则', description: '确定删除此告警规则?', confirmText: '删除', variant: 'destructive' }); if (!ok) return; }
|
||||||
|
try {
|
||||||
|
await alertApi.deleteRule(id);
|
||||||
|
onReload();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete rule:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleRule = async (id: any) => {
|
||||||
|
try {
|
||||||
|
await alertApi.toggleRule(id);
|
||||||
|
onReload();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to toggle rule:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-4">
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="border-t border-slate-800">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800 hover:bg-transparent">
|
||||||
|
<TableHead className="text-slate-400">规则名称</TableHead>
|
||||||
|
<TableHead className="text-slate-400">数据源</TableHead>
|
||||||
|
<TableHead className="text-slate-400">触发条件</TableHead>
|
||||||
|
<TableHead className="text-slate-400">级别</TableHead>
|
||||||
|
<TableHead className="text-slate-400">持续时间</TableHead>
|
||||||
|
<TableHead className="text-slate-400">通知渠道</TableHead>
|
||||||
|
<TableHead className="text-slate-400">状态</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{rules.map((rule) => (
|
||||||
|
<TableRow key={rule.id} className="border-slate-800 hover:bg-slate-800/50">
|
||||||
|
<TableCell>
|
||||||
|
<div>
|
||||||
|
<span className="text-sm font-medium text-slate-200">{rule.name}</span>
|
||||||
|
{rule.description && (
|
||||||
|
<p className="text-xs text-slate-500">{rule.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<code className="text-xs text-slate-300 bg-slate-800 px-2 py-0.5 rounded">
|
||||||
|
{rule.source || '--'}
|
||||||
|
</code>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<code className="text-xs text-blue-300">
|
||||||
|
{rule.expression || '--'}
|
||||||
|
</code>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{rule.severity === 'critical' ? (
|
||||||
|
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10">
|
||||||
|
严重
|
||||||
|
</Badge>
|
||||||
|
) : rule.severity === 'warning' ? (
|
||||||
|
<Badge variant="outline" className="border-amber-500/30 text-amber-400 bg-amber-500/10">
|
||||||
|
警告
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
|
||||||
|
提示
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-300">{(rule.duration || 0) / 60}分钟</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{renderRuleChannels(rule, notifyChannels)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Switch
|
||||||
|
checked={!!rule.enabled}
|
||||||
|
className="data-[state=checked]:bg-blue-600"
|
||||||
|
onCheckedChange={() => handleToggleRule(rule.id)}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-slate-100"
|
||||||
|
onClick={() => onEditRule(rule)}
|
||||||
|
>
|
||||||
|
<Settings className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-red-400"
|
||||||
|
onClick={() => handleDeleteRule(rule.id)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { Mail, Phone, MessageSquare, Bell } from 'lucide-react';
|
||||||
|
|
||||||
|
// 将 notify_channels (可能是数组/JSON字符串/逗号分隔) 解析为数组
|
||||||
|
export function parseChannels(notifyChannels: any): string[] {
|
||||||
|
if (!notifyChannels) return [];
|
||||||
|
if (Array.isArray(notifyChannels)) return notifyChannels;
|
||||||
|
if (typeof notifyChannels === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(notifyChannels);
|
||||||
|
if (Array.isArray(parsed)) return parsed;
|
||||||
|
} catch {
|
||||||
|
// 非JSON,尝试逗号分隔
|
||||||
|
}
|
||||||
|
return notifyChannels.split(',').map((s) => s.trim()).filter(Boolean);
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 已知的渠道类型(用于旧数据兼容 — 旧规则存储类型字符串而非渠道 ID)
|
||||||
|
export const KNOWN_CHANNEL_TYPES = ['email', 'sms', 'dingtalk', 'wechat', 'webhook'];
|
||||||
|
|
||||||
|
// 根据渠道类型获取图标组件名(用字符串映射,组件内用 getChannelIcon 返回实际组件)
|
||||||
|
export const CHANNEL_TYPE_LABELS: Record<string, string> = {
|
||||||
|
dingtalk: '钉钉',
|
||||||
|
wechat: '企业微信',
|
||||||
|
email: '邮件',
|
||||||
|
sms: '短信',
|
||||||
|
webhook: 'Webhook',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 解析单个 notify_channels 引用值 — 返回 {id?, type, name, isLegacy}
|
||||||
|
// 新格式存渠道 ID (string),旧格式存类型字符串 (email/dingtalk 等)
|
||||||
|
export function resolveChannelRef(value: string, channels: any[]): { type: string; name: string; isLegacy: boolean } | null {
|
||||||
|
if (!value) return null;
|
||||||
|
// 尝试按 ID 匹配已配置渠道
|
||||||
|
const ch = channels.find((c) => String(c.id) === String(value));
|
||||||
|
if (ch) return { type: ch.type || 'unknown', name: ch.name || ch.type || '未命名', isLegacy: false };
|
||||||
|
// 兼容旧格式:值本身是类型字符串
|
||||||
|
if (KNOWN_CHANNEL_TYPES.includes(value)) {
|
||||||
|
return { type: value, name: CHANNEL_TYPE_LABELS[value] || value, isLegacy: true };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 渠道类型选项(供下拉选择)
|
||||||
|
export const CHANNEL_TYPES: { key: string; label: string; placeholder: string }[] = [
|
||||||
|
{ key: 'dingtalk', label: '钉钉', placeholder: '{\n "webhook": "https://oapi.dingtalk.com/robot/send?access_token=***",\n "secret": "SECxxx"\n}' },
|
||||||
|
{ key: 'wechat', label: '企业微信', placeholder: '{\n "webhook": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***"\n}' },
|
||||||
|
{ key: 'email', label: '邮件', placeholder: '{\n "to": "ops@ezops.io",\n "subject": "告警通知"\n}' },
|
||||||
|
{ key: 'sms', label: '短信', placeholder: '{\n "phones": "13800138000",\n "sign": "EZOps"\n}' },
|
||||||
|
{ key: 'webhook', label: 'Webhook', placeholder: '{\n "url": "https://example.com/alert"\n}' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function getChannelTypeLabel(type: string) {
|
||||||
|
return CHANNEL_TYPES.find((t) => t.key === type)?.label || type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据渠道类型返回对应图标组件
|
||||||
|
export function getChannelIcon(type: string) {
|
||||||
|
switch (type) {
|
||||||
|
case 'email':
|
||||||
|
return Mail;
|
||||||
|
case 'sms':
|
||||||
|
return Phone;
|
||||||
|
case 'dingtalk':
|
||||||
|
case 'wechat':
|
||||||
|
return MessageSquare;
|
||||||
|
default:
|
||||||
|
return Bell;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 渲染规则的通知渠道引用列表(兼容新格式=渠道ID 和 旧格式=类型字符串)
|
||||||
|
export function renderRuleChannels(rule: any, notifyChannels: any[]) {
|
||||||
|
const refs = parseChannels(rule.notify_channels);
|
||||||
|
if (refs.length === 0) return <span className="text-xs text-slate-600">--</span>;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{refs.map((ref) => {
|
||||||
|
const resolved = resolveChannelRef(ref, notifyChannels);
|
||||||
|
if (!resolved) return null;
|
||||||
|
const Icon = getChannelIcon(resolved.type);
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
key={ref}
|
||||||
|
title={`${resolved.name} (${getChannelTypeLabel(resolved.type)})`}
|
||||||
|
className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-slate-800 text-slate-300"
|
||||||
|
>
|
||||||
|
<Icon className="h-3 w-3 text-slate-400" />
|
||||||
|
{resolved.name}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import {
|
||||||
|
Collapsible,
|
||||||
|
CollapsibleContent,
|
||||||
|
CollapsibleTrigger,
|
||||||
|
} from '@/components/ui/collapsible';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { Server, ChevronDown, Loader2, Save } from 'lucide-react';
|
||||||
|
|
||||||
|
// 表单数据结构 — 与后端 CreateServerRequest/UpdateServerRequest 字段对齐
|
||||||
|
export interface ServerFormData {
|
||||||
|
hostname: string;
|
||||||
|
ip: string;
|
||||||
|
public_ip: string;
|
||||||
|
port: string;
|
||||||
|
username: string;
|
||||||
|
auth_type: string; // password | key
|
||||||
|
password: string;
|
||||||
|
os: string;
|
||||||
|
cpu: string;
|
||||||
|
memory: string; // GB (表单) → MB (后端)
|
||||||
|
disk: string;
|
||||||
|
status: string;
|
||||||
|
tags: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_FORM: ServerFormData = {
|
||||||
|
hostname: '',
|
||||||
|
ip: '',
|
||||||
|
public_ip: '',
|
||||||
|
port: '22',
|
||||||
|
username: 'root',
|
||||||
|
auth_type: 'password',
|
||||||
|
password: '',
|
||||||
|
os: '',
|
||||||
|
cpu: '',
|
||||||
|
memory: '',
|
||||||
|
disk: '',
|
||||||
|
status: 'running',
|
||||||
|
tags: '',
|
||||||
|
description: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
interface ServerFormProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editingId: string | null;
|
||||||
|
formData: ServerFormData;
|
||||||
|
setFormData: React.Dispatch<React.SetStateAction<ServerFormData>>;
|
||||||
|
detailsOpen: boolean;
|
||||||
|
setDetailsOpen: (open: boolean) => void;
|
||||||
|
onSave: () => void;
|
||||||
|
formSaving: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ServerForm({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
editingId,
|
||||||
|
formData,
|
||||||
|
setFormData,
|
||||||
|
detailsOpen,
|
||||||
|
setDetailsOpen,
|
||||||
|
onSave,
|
||||||
|
formSaving,
|
||||||
|
}: ServerFormProps) {
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-2xl bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-h-[90vh] overflow-y-auto">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2">
|
||||||
|
<Server className="h-5 w-5 text-[var(--dg-blue)]" />
|
||||||
|
{editingId ? '编辑服务器' : '添加服务器'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-[var(--dg-text-muted)]">
|
||||||
|
{editingId ? '修改服务器资产信息' : '录入新的服务器资产到 CMDB'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4 py-2">
|
||||||
|
{/* 基础信息 */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">
|
||||||
|
主机名 <span className="text-red-400">*</span>
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="web-server-01"
|
||||||
|
value={formData.hostname}
|
||||||
|
onChange={(e) => setFormData({ ...formData, hostname: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">
|
||||||
|
IP地址 <span className="text-red-400">*</span>
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="10.0.0.1"
|
||||||
|
value={formData.ip}
|
||||||
|
onChange={(e) => setFormData({ ...formData, ip: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* SSH 连接配置 */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">公网IP</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="如 203.0.113.10"
|
||||||
|
value={formData.public_ip}
|
||||||
|
onChange={(e) => setFormData({ ...formData, public_ip: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">SSH端口</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="22"
|
||||||
|
value={formData.port}
|
||||||
|
onChange={(e) => setFormData({ ...formData, port: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">登录用户</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="root"
|
||||||
|
value={formData.username}
|
||||||
|
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">认证方式</Label>
|
||||||
|
<Select
|
||||||
|
value={formData.auth_type}
|
||||||
|
onValueChange={(v) => setFormData({ ...formData, auth_type: v })}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]">
|
||||||
|
<SelectItem value="password">密码认证</SelectItem>
|
||||||
|
<SelectItem value="key">密钥认证</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">
|
||||||
|
{formData.auth_type === 'key' ? 'SSH 私钥' : '登录密码'}
|
||||||
|
{!editingId && <span className="text-red-400 ml-1">*</span>}
|
||||||
|
{editingId && <span className="text-[var(--dg-text-muted)] ml-1 text-xs">(留空则不修改)</span>}
|
||||||
|
</Label>
|
||||||
|
<Textarea
|
||||||
|
placeholder={formData.auth_type === 'key' ? '粘贴 SSH 私钥内容...' : '输入登录密码...'}
|
||||||
|
value={formData.password}
|
||||||
|
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[50px] font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 更多详情 - 可折叠区域 */}
|
||||||
|
<Collapsible open={detailsOpen} onOpenChange={setDetailsOpen}>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full justify-between text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)]"
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Server className="h-4 w-4" />
|
||||||
|
更多详情(OS版本 / 运行状态 / CPU / 内存 / 磁盘 / 标签 / 描述)
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={cn('h-4 w-4 transition-transform', detailsOpen && 'rotate-180')} />
|
||||||
|
</Button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent className="space-y-4 pt-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">操作系统</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="如 CentOS 7.9"
|
||||||
|
value={formData.os}
|
||||||
|
onChange={(e) => setFormData({ ...formData, os: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">运行状态</Label>
|
||||||
|
<Select
|
||||||
|
value={formData.status}
|
||||||
|
onValueChange={(v) => setFormData({ ...formData, status: v })}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]">
|
||||||
|
<SelectItem value="running">运行中</SelectItem>
|
||||||
|
<SelectItem value="stopped">已停止</SelectItem>
|
||||||
|
<SelectItem value="maintenance">维护中</SelectItem>
|
||||||
|
<SelectItem value="offline">离线</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">CPU核数</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="4"
|
||||||
|
value={formData.cpu}
|
||||||
|
onChange={(e) => setFormData({ ...formData, cpu: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">内存 (GB)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="8"
|
||||||
|
value={formData.memory}
|
||||||
|
onChange={(e) => setFormData({ ...formData, memory: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">磁盘 (GB)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="100"
|
||||||
|
value={formData.disk}
|
||||||
|
onChange={(e) => setFormData({ ...formData, disk: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">标签</Label>
|
||||||
|
<Input
|
||||||
|
placeholder='JSON 格式,如 {"project":"web","team":"ops"}'
|
||||||
|
value={formData.tags}
|
||||||
|
onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
|
||||||
|
<Textarea
|
||||||
|
placeholder="补充说明..."
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||||
|
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[60px]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)] hover:text-[var(--dg-text-primary)]"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onSave}
|
||||||
|
disabled={!formData.hostname || !formData.ip || formSaving}
|
||||||
|
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
|
||||||
|
>
|
||||||
|
{formSaving ? (
|
||||||
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Save className="h-4 w-4 mr-2" />
|
||||||
|
)}
|
||||||
|
{editingId ? '保存修改' : '创建'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,15 +3,8 @@ import { cn } from '@/lib/utils';
|
|||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -28,14 +21,6 @@ import {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from '@/components/ui/table';
|
} from '@/components/ui/table';
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -59,49 +44,12 @@ import {
|
|||||||
Cloud,
|
Cloud,
|
||||||
FileSpreadsheet,
|
FileSpreadsheet,
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
ChevronDown,
|
|
||||||
Loader2,
|
|
||||||
Save,
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { serverApi } from '@/services/api';
|
import { serverApi } from '@/services/api';
|
||||||
import type { Server as ServerType } from '@/types';
|
import type { Server as ServerType } from '@/types';
|
||||||
import { CloudServerImport } from './CloudServerImport';
|
import { CloudServerImport } from './CloudServerImport';
|
||||||
import { ExcelServerImport } from './ExcelServerImport';
|
import { ExcelServerImport } from './ExcelServerImport';
|
||||||
|
import { ServerForm, EMPTY_FORM, type ServerFormData } from './ServerForm';
|
||||||
// 表单数据结构 — 与后端 CreateServerRequest/UpdateServerRequest 字段对齐
|
|
||||||
interface ServerFormData {
|
|
||||||
hostname: string;
|
|
||||||
ip: string;
|
|
||||||
public_ip: string;
|
|
||||||
port: string;
|
|
||||||
username: string;
|
|
||||||
auth_type: string; // password | key
|
|
||||||
password: string;
|
|
||||||
os: string;
|
|
||||||
cpu: string;
|
|
||||||
memory: string; // GB (表单) → MB (后端)
|
|
||||||
disk: string;
|
|
||||||
status: string;
|
|
||||||
tags: string;
|
|
||||||
description: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const EMPTY_FORM: ServerFormData = {
|
|
||||||
hostname: '',
|
|
||||||
ip: '',
|
|
||||||
public_ip: '',
|
|
||||||
port: '22',
|
|
||||||
username: 'root',
|
|
||||||
auth_type: 'password',
|
|
||||||
password: '',
|
|
||||||
os: '',
|
|
||||||
cpu: '',
|
|
||||||
memory: '',
|
|
||||||
disk: '',
|
|
||||||
status: 'running',
|
|
||||||
tags: '',
|
|
||||||
description: '',
|
|
||||||
};
|
|
||||||
|
|
||||||
export function ServerManager() {
|
export function ServerManager() {
|
||||||
const [servers, setServers] = useState<any[]>([]);
|
const [servers, setServers] = useState<any[]>([]);
|
||||||
@@ -660,230 +608,17 @@ export function ServerManager() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* 创建/编辑服务器 Dialog */}
|
{/* 创建/编辑服务器 Dialog */}
|
||||||
<Dialog open={formOpen} onOpenChange={setFormOpen}>
|
<ServerForm
|
||||||
<DialogContent className="max-w-2xl bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-h-[90vh] overflow-y-auto">
|
open={formOpen}
|
||||||
<DialogHeader>
|
onOpenChange={setFormOpen}
|
||||||
<DialogTitle className="text-[var(--dg-text-primary)] flex items-center gap-2">
|
editingId={editingId}
|
||||||
<Server className="h-5 w-5 text-[var(--dg-blue)]" />
|
formData={formData}
|
||||||
{editingId ? '编辑服务器' : '添加服务器'}
|
setFormData={setFormData}
|
||||||
</DialogTitle>
|
detailsOpen={detailsOpen}
|
||||||
<DialogDescription className="text-[var(--dg-text-muted)]">
|
setDetailsOpen={setDetailsOpen}
|
||||||
{editingId ? '修改服务器资产信息' : '录入新的服务器资产到 CMDB'}
|
onSave={handleSave}
|
||||||
</DialogDescription>
|
formSaving={formSaving}
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="space-y-4 py-2">
|
|
||||||
{/* 基础信息 */}
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">
|
|
||||||
主机名 <span className="text-red-400">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="web-server-01"
|
|
||||||
value={formData.hostname}
|
|
||||||
onChange={(e) => setFormData({ ...formData, hostname: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">
|
|
||||||
IP地址 <span className="text-red-400">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="10.0.0.1"
|
|
||||||
value={formData.ip}
|
|
||||||
onChange={(e) => setFormData({ ...formData, ip: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* SSH 连接配置 */}
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">公网IP</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="如 203.0.113.10"
|
|
||||||
value={formData.public_ip}
|
|
||||||
onChange={(e) => setFormData({ ...formData, public_ip: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">SSH端口</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="22"
|
|
||||||
value={formData.port}
|
|
||||||
onChange={(e) => setFormData({ ...formData, port: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">登录用户</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="root"
|
|
||||||
value={formData.username}
|
|
||||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">认证方式</Label>
|
|
||||||
<Select
|
|
||||||
value={formData.auth_type}
|
|
||||||
onValueChange={(v) => setFormData({ ...formData, auth_type: v })}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]">
|
|
||||||
<SelectItem value="password">密码认证</SelectItem>
|
|
||||||
<SelectItem value="key">密钥认证</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">
|
|
||||||
{formData.auth_type === 'key' ? 'SSH 私钥' : '登录密码'}
|
|
||||||
{!editingId && <span className="text-red-400 ml-1">*</span>}
|
|
||||||
{editingId && <span className="text-[var(--dg-text-muted)] ml-1 text-xs">(留空则不修改)</span>}
|
|
||||||
</Label>
|
|
||||||
<Textarea
|
|
||||||
placeholder={formData.auth_type === 'key' ? '粘贴 SSH 私钥内容...' : '输入登录密码...'}
|
|
||||||
value={formData.password}
|
|
||||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[50px] font-mono text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 更多详情 - 可折叠区域 */}
|
|
||||||
<Collapsible open={detailsOpen} onOpenChange={setDetailsOpen}>
|
|
||||||
<CollapsibleTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="w-full justify-between text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)]"
|
|
||||||
>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<Server className="h-4 w-4" />
|
|
||||||
更多详情(OS版本 / 运行状态 / CPU / 内存 / 磁盘 / 标签 / 描述)
|
|
||||||
</span>
|
|
||||||
<ChevronDown className={cn('h-4 w-4 transition-transform', detailsOpen && 'rotate-180')} />
|
|
||||||
</Button>
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
<CollapsibleContent className="space-y-4 pt-4">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">操作系统</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="如 CentOS 7.9"
|
|
||||||
value={formData.os}
|
|
||||||
onChange={(e) => setFormData({ ...formData, os: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">运行状态</Label>
|
|
||||||
<Select
|
|
||||||
value={formData.status}
|
|
||||||
onValueChange={(v) => setFormData({ ...formData, status: v })}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]">
|
|
||||||
<SelectItem value="running">运行中</SelectItem>
|
|
||||||
<SelectItem value="stopped">已停止</SelectItem>
|
|
||||||
<SelectItem value="maintenance">维护中</SelectItem>
|
|
||||||
<SelectItem value="offline">离线</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-3 gap-4">
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">CPU核数</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="4"
|
|
||||||
value={formData.cpu}
|
|
||||||
onChange={(e) => setFormData({ ...formData, cpu: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">内存 (GB)</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="8"
|
|
||||||
value={formData.memory}
|
|
||||||
onChange={(e) => setFormData({ ...formData, memory: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">磁盘 (GB)</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="100"
|
|
||||||
value={formData.disk}
|
|
||||||
onChange={(e) => setFormData({ ...formData, disk: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">标签</Label>
|
|
||||||
<Input
|
|
||||||
placeholder='JSON 格式,如 {"project":"web","team":"ops"}'
|
|
||||||
value={formData.tags}
|
|
||||||
onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
|
|
||||||
<Textarea
|
|
||||||
placeholder="补充说明..."
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
||||||
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[60px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<DialogFooter>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => setFormOpen(false)}
|
|
||||||
className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)] hover:text-[var(--dg-text-primary)]"
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={!formData.hostname || !formData.ip || formSaving}
|
|
||||||
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
|
|
||||||
>
|
|
||||||
{formSaving ? (
|
|
||||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Save className="h-4 w-4 mr-2" />
|
|
||||||
)}
|
|
||||||
{editingId ? '保存修改' : '创建'}
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* Import Dialogs */}
|
{/* Import Dialogs */}
|
||||||
<CloudServerImport
|
<CloudServerImport
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Search, RefreshCw } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table';
|
||||||
|
import { operationLogs } from '@/mocks/data';
|
||||||
|
import type { OperationLog } from '@/types';
|
||||||
|
|
||||||
|
interface SystemLogsTabProps {
|
||||||
|
searchQuery: string;
|
||||||
|
setSearchQuery: (v: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SystemLogsTab({ searchQuery, setSearchQuery }: SystemLogsTabProps) {
|
||||||
|
const filteredLogs = operationLogs.filter(
|
||||||
|
(log) =>
|
||||||
|
log.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
log.module.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
log.action.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const getLogResultBadge = (result: OperationLog['result']) => {
|
||||||
|
return result === 'success' ? (
|
||||||
|
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
|
||||||
|
成功
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10">
|
||||||
|
失败
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="relative w-64">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
|
||||||
|
<Input
|
||||||
|
placeholder="搜索操作日志..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800">
|
||||||
|
<RefreshCw className="h-4 w-4 mr-2" />
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Logs Table */}
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="border-t border-slate-800">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800 hover:bg-transparent">
|
||||||
|
<TableHead className="text-slate-400">时间</TableHead>
|
||||||
|
<TableHead className="text-slate-400">用户</TableHead>
|
||||||
|
<TableHead className="text-slate-400">模块</TableHead>
|
||||||
|
<TableHead className="text-slate-400">操作</TableHead>
|
||||||
|
<TableHead className="text-slate-400">资源</TableHead>
|
||||||
|
<TableHead className="text-slate-400">IP地址</TableHead>
|
||||||
|
<TableHead className="text-slate-400">结果</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{filteredLogs.map((log) => (
|
||||||
|
<TableRow key={log.id} className="border-slate-800 hover:bg-slate-800/50">
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-400">
|
||||||
|
{new Date(log.createdAt).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-200">{log.username}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-300">{log.module}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-300">{log.action}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<code className="text-xs text-slate-400 bg-slate-800 px-2 py-0.5 rounded">
|
||||||
|
{log.resource}
|
||||||
|
</code>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-400">{log.ip}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{getLogResultBadge(log.result)}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Plus, Shield, Edit, Eye } from 'lucide-react';
|
||||||
|
import { roles } from '@/mocks/data';
|
||||||
|
import type { Role } from '@/types';
|
||||||
|
|
||||||
|
interface SystemRolesTabProps {
|
||||||
|
selectedRole: Role | null;
|
||||||
|
setSelectedRole: (role: Role | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SystemRolesTab({ selectedRole, setSelectedRole }: SystemRolesTabProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex items-center justify-end">
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
新建角色
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
|
{roles.map((role) => (
|
||||||
|
<Card key={role.id} className="bg-slate-900 border-slate-800">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-lg bg-purple-500/10 flex items-center justify-center">
|
||||||
|
<Shield className="h-5 w-5 text-purple-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-base text-slate-100">{role.name}</CardTitle>
|
||||||
|
<CardDescription className="text-slate-500">{role.code}</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-slate-100"
|
||||||
|
onClick={() => setSelectedRole(role)}
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100">
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p className="text-sm text-slate-400 mb-3">{role.description}</p>
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{role.permissions.slice(0, 5).map((permission) => (
|
||||||
|
<Badge key={permission} variant="outline" className="border-slate-700 text-slate-400 text-xs">
|
||||||
|
{permission}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
{role.permissions.length > 5 && (
|
||||||
|
<Badge variant="outline" className="border-slate-700 text-slate-400 text-xs">
|
||||||
|
+{role.permissions.length - 5}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,588 @@
|
|||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
Plus,
|
||||||
|
Upload,
|
||||||
|
Network,
|
||||||
|
Mail,
|
||||||
|
Phone,
|
||||||
|
CheckCircle,
|
||||||
|
XCircle,
|
||||||
|
Eye,
|
||||||
|
Edit,
|
||||||
|
Trash2,
|
||||||
|
Download,
|
||||||
|
Key,
|
||||||
|
Loader2,
|
||||||
|
RefreshCw,
|
||||||
|
User as UserIcon,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { userApi } from '@/services/api';
|
||||||
|
import { UserFormDialog, type UserFormData } from './UserFormDialog';
|
||||||
|
|
||||||
|
interface SystemUserTabProps {
|
||||||
|
// Search
|
||||||
|
searchQuery: string;
|
||||||
|
setSearchQuery: (v: string) => void;
|
||||||
|
// Users
|
||||||
|
filteredUsers: any[];
|
||||||
|
loading: boolean;
|
||||||
|
selectedUser: any | null;
|
||||||
|
setSelectedUser: (u: any | null) => void;
|
||||||
|
getUserStatusBadge: (status: 'active' | 'inactive') => React.ReactNode;
|
||||||
|
// Create / Edit
|
||||||
|
dialogOpen: boolean;
|
||||||
|
setDialogOpen: (open: boolean) => void;
|
||||||
|
editingUser: any | null;
|
||||||
|
form: UserFormData;
|
||||||
|
setForm: React.Dispatch<React.SetStateAction<UserFormData>>;
|
||||||
|
saving: boolean;
|
||||||
|
handleSubmit: () => void;
|
||||||
|
openCreate: () => void;
|
||||||
|
openEdit: (user: any) => void;
|
||||||
|
handleDelete: (user: any) => void;
|
||||||
|
// CSV import
|
||||||
|
importDialogOpen: 'csv' | 'ldap' | null;
|
||||||
|
setImportDialogOpen: (v: 'csv' | 'ldap' | null) => void;
|
||||||
|
importPreview: any[];
|
||||||
|
setImportPreview: (p: any[]) => void;
|
||||||
|
importing: boolean;
|
||||||
|
importResult: any;
|
||||||
|
setImportResult: (r: any) => void;
|
||||||
|
handleCsvUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||||
|
handleBatchImport: () => void;
|
||||||
|
// LDAP import
|
||||||
|
ldapUsers: any[];
|
||||||
|
ldapSelected: Set<string>;
|
||||||
|
setLdapSelected: (s: Set<string>) => void;
|
||||||
|
ldapLoading: boolean;
|
||||||
|
ldapImportOUs: any[];
|
||||||
|
ldapImportOUDN: string;
|
||||||
|
setLdapImportOUDN: (v: string) => void;
|
||||||
|
loadLdapUsers: (ouDn?: string) => void;
|
||||||
|
handleLdapImport: () => void;
|
||||||
|
setLdapUsers: (u: any[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SystemUserTab({
|
||||||
|
searchQuery,
|
||||||
|
setSearchQuery,
|
||||||
|
filteredUsers,
|
||||||
|
loading,
|
||||||
|
selectedUser,
|
||||||
|
setSelectedUser,
|
||||||
|
getUserStatusBadge,
|
||||||
|
dialogOpen,
|
||||||
|
setDialogOpen,
|
||||||
|
editingUser,
|
||||||
|
form,
|
||||||
|
setForm,
|
||||||
|
saving,
|
||||||
|
handleSubmit,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
handleDelete,
|
||||||
|
importDialogOpen,
|
||||||
|
setImportDialogOpen,
|
||||||
|
importPreview,
|
||||||
|
setImportPreview,
|
||||||
|
importing,
|
||||||
|
importResult,
|
||||||
|
setImportResult,
|
||||||
|
handleCsvUpload,
|
||||||
|
handleBatchImport,
|
||||||
|
ldapUsers,
|
||||||
|
ldapSelected,
|
||||||
|
setLdapSelected,
|
||||||
|
ldapLoading,
|
||||||
|
ldapImportOUs,
|
||||||
|
ldapImportOUDN,
|
||||||
|
setLdapImportOUDN,
|
||||||
|
loadLdapUsers,
|
||||||
|
handleLdapImport,
|
||||||
|
setLdapUsers,
|
||||||
|
}: SystemUserTabProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="relative w-64">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
|
||||||
|
<Input
|
||||||
|
placeholder="搜索用户..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800" onClick={() => setImportDialogOpen('csv')}>
|
||||||
|
<Upload className="h-4 w-4 mr-2" />
|
||||||
|
批量导入
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800" onClick={() => setImportDialogOpen('ldap')}>
|
||||||
|
<Network className="h-4 w-4 mr-2" />
|
||||||
|
LDAP 导入
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={openCreate}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
新建用户
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Users Table */}
|
||||||
|
<Card className="bg-slate-900 border-slate-800">
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="border-t border-slate-800">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800 hover:bg-transparent">
|
||||||
|
<TableHead className="text-slate-400">用户信息</TableHead>
|
||||||
|
<TableHead className="text-slate-400">联系方式</TableHead>
|
||||||
|
<TableHead className="text-slate-400">角色</TableHead>
|
||||||
|
<TableHead className="text-slate-400">来源</TableHead>
|
||||||
|
<TableHead className="text-slate-400">状态</TableHead>
|
||||||
|
<TableHead className="text-slate-400">最后登录</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{loading ? (
|
||||||
|
<TableRow className="border-slate-800">
|
||||||
|
<TableCell colSpan={7} className="text-center py-12">
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
<div className="h-6 w-6 border-2 border-slate-700 border-t-blue-500 rounded-full animate-spin" />
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : filteredUsers.length === 0 ? (
|
||||||
|
<TableRow className="border-slate-800">
|
||||||
|
<TableCell colSpan={7} className="text-center py-12 text-sm text-slate-500">
|
||||||
|
暂无用户数据
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
filteredUsers.map((user) => (
|
||||||
|
<TableRow key={user.id} className="border-slate-800 hover:bg-slate-800/50">
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white text-sm font-medium">
|
||||||
|
{(user.nickname || user.username || '?').charAt(0)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-slate-200">{user.nickname || user.username}</p>
|
||||||
|
<p className="text-xs text-slate-500">@{user.username}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center gap-1 text-sm text-slate-400">
|
||||||
|
<Mail className="h-3.5 w-3.5" />
|
||||||
|
{user.email || '--'}
|
||||||
|
</div>
|
||||||
|
{user.phone && (
|
||||||
|
<div className="flex items-center gap-1 text-sm text-slate-400">
|
||||||
|
<Phone className="h-3.5 w-3.5" />
|
||||||
|
{user.phone}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{(user.roles || []).map((role: string) => (
|
||||||
|
<Badge key={role} variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{role}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{user.authSource === 'ldap' ? (
|
||||||
|
<Badge variant="outline" className="border-cyan-500/30 text-cyan-400 bg-cyan-500/10">
|
||||||
|
LDAP
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline" className="border-slate-600/30 text-slate-400 bg-slate-600/10">
|
||||||
|
本地
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{getUserStatusBadge(user.status)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm text-slate-400">
|
||||||
|
{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString() : '--'}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-slate-100"
|
||||||
|
onClick={() => setSelectedUser(user)}
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-slate-100"
|
||||||
|
onClick={() => openEdit(user)}
|
||||||
|
>
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-slate-400 hover:text-red-400"
|
||||||
|
onClick={() => handleDelete(user)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* User Detail Dialog */}
|
||||||
|
<Dialog open={!!selectedUser} onOpenChange={() => setSelectedUser(null)}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-800">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100 flex items-center gap-2">
|
||||||
|
<UserIcon className="h-5 w-5 text-blue-400" />
|
||||||
|
{selectedUser?.nickname}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
@{selectedUser?.username} · {selectedUser?.email}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4 p-4 rounded-lg bg-slate-800/50">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">用户名</p>
|
||||||
|
<p className="text-sm text-slate-200">{selectedUser?.username}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">昵称</p>
|
||||||
|
<p className="text-sm text-slate-200">{selectedUser?.nickname}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">邮箱</p>
|
||||||
|
<p className="text-sm text-slate-200">{selectedUser?.email}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">手机号</p>
|
||||||
|
<p className="text-sm text-slate-200">{selectedUser?.phone || '--'}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">状态</p>
|
||||||
|
<p className="text-sm text-slate-200">{selectedUser && getUserStatusBadge(selectedUser.status)}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-slate-500 mb-1">创建时间</p>
|
||||||
|
<p className="text-sm text-slate-200">
|
||||||
|
{selectedUser && selectedUser.createdAt ? new Date(selectedUser.createdAt).toLocaleDateString() : '--'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-medium text-slate-300 mb-2">角色</h4>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{selectedUser?.roles.map((role: string) => (
|
||||||
|
<Badge key={role} variant="outline" className="border-slate-700 text-slate-400">
|
||||||
|
{role}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300">
|
||||||
|
<Key className="h-4 w-4 mr-2" />
|
||||||
|
重置密码
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
onClick={() => {
|
||||||
|
if (selectedUser) {
|
||||||
|
setSelectedUser(null);
|
||||||
|
openEdit(selectedUser);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Edit className="h-4 w-4 mr-2" />
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Create / Edit User Dialog */}
|
||||||
|
<UserFormDialog
|
||||||
|
open={dialogOpen}
|
||||||
|
onOpenChange={setDialogOpen}
|
||||||
|
editingUser={editingUser}
|
||||||
|
form={form}
|
||||||
|
setForm={setForm}
|
||||||
|
saving={saving}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* CSV 批量导入 Dialog */}
|
||||||
|
<Dialog open={importDialogOpen === 'csv'} onOpenChange={(v) => !v && setImportDialogOpen(null)}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-800 max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100 flex items-center gap-2">
|
||||||
|
<Upload className="h-5 w-5 text-blue-400" />
|
||||||
|
批量导入用户(CSV)
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
上传 CSV 文件批量创建用户。请先下载模板,按格式填写后上传。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{!importResult ? (
|
||||||
|
<>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" className="border-slate-700 text-slate-300" onClick={() => userApi.downloadTemplate()}>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
下载模板
|
||||||
|
</Button>
|
||||||
|
<label className="inline-flex items-center px-3 py-1.5 rounded-md text-sm bg-slate-800 border border-slate-700 text-slate-200 cursor-pointer hover:bg-slate-700 transition-colors">
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
选择 CSV 文件
|
||||||
|
<input type="file" accept=".csv" className="hidden" onChange={handleCsvUpload} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{importPreview.length > 0 && (
|
||||||
|
<div className="rounded-lg border border-slate-800 overflow-hidden">
|
||||||
|
<div className="px-3 py-2 bg-slate-800/50 text-xs text-slate-400">
|
||||||
|
预览:{importPreview.length} 条数据
|
||||||
|
</div>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800">
|
||||||
|
<TableHead className="text-slate-400 text-xs">用户名</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">昵称</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">邮箱</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">手机</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{importPreview.slice(0, 5).map((u, i) => (
|
||||||
|
<TableRow key={i} className="border-slate-800">
|
||||||
|
<TableCell className="text-slate-200 text-xs">{u.username}</TableCell>
|
||||||
|
<TableCell className="text-slate-300 text-xs">{u.nickname}</TableCell>
|
||||||
|
<TableCell className="text-slate-400 text-xs">{u.email}</TableCell>
|
||||||
|
<TableCell className="text-slate-400 text-xs">{u.phone}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
{importPreview.length > 5 && (
|
||||||
|
<TableRow className="border-slate-800">
|
||||||
|
<TableCell colSpan={4} className="text-slate-500 text-xs text-center">
|
||||||
|
还有 {importPreview.length - 5} 条...
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => { setImportDialogOpen(null); setImportPreview([]); }}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={handleBatchImport} disabled={importing || importPreview.length === 0}>
|
||||||
|
{importing ? '导入中...' : `确认导入 (${importPreview.length})`}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4 py-2">
|
||||||
|
<div className={`flex items-center gap-3 p-4 rounded-lg ${importResult.code === 200 ? 'bg-emerald-500/10' : 'bg-red-500/10'}`}>
|
||||||
|
{importResult.code === 200 ? (
|
||||||
|
<CheckCircle className="h-6 w-6 text-emerald-400 shrink-0" />
|
||||||
|
) : (
|
||||||
|
<XCircle className="h-6 w-6 text-red-400 shrink-0" />
|
||||||
|
)}
|
||||||
|
<span className="text-sm text-slate-200">{importResult.message}</span>
|
||||||
|
</div>
|
||||||
|
{importResult.errors?.length > 0 && (
|
||||||
|
<div className="max-h-32 overflow-auto rounded-lg bg-slate-800/50 p-3 space-y-1">
|
||||||
|
{importResult.errors.map((err: string, i: number) => (
|
||||||
|
<div key={i} className="text-xs text-red-400">{err}</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<DialogFooter>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={() => { setImportDialogOpen(null); setImportPreview([]); setImportResult(null); }}>
|
||||||
|
完成
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* LDAP 导入 Dialog */}
|
||||||
|
<Dialog open={importDialogOpen === 'ldap'} onOpenChange={(v) => !v && setImportDialogOpen(null)}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-800 max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100 flex items-center gap-2">
|
||||||
|
<Network className="h-5 w-5 text-cyan-400" />
|
||||||
|
从 LDAP 导入用户
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
从 LDAP 服务器检索用户列表,选择需要导入的用户
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{!importResult ? (
|
||||||
|
<>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-slate-500 whitespace-nowrap">选择 OU</span>
|
||||||
|
<select
|
||||||
|
className="bg-slate-800 border border-slate-700 text-slate-200 text-xs rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||||
|
value={ldapImportOUDN}
|
||||||
|
onChange={(e) => {
|
||||||
|
setLdapImportOUDN(e.target.value);
|
||||||
|
loadLdapUsers(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">根 (全部)</option>
|
||||||
|
{ldapImportOUs.map((ou) => (
|
||||||
|
<option key={ou.dn} value={ou.dn}>{ou.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" className="border-slate-700 text-slate-300 ml-auto" onClick={() => loadLdapUsers(ldapImportOUDN)} disabled={ldapLoading}>
|
||||||
|
{ldapLoading ? <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> : <RefreshCw className="h-4 w-4 mr-1.5" />}
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs text-slate-500">
|
||||||
|
{ldapUsers.length > 0 ? `找到 ${ldapUsers.length} 个用户` : '选择 OU 或点击刷新获取用户列表'}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{ldapUsers.length > 0 && (
|
||||||
|
<div className="max-h-80 overflow-auto rounded-lg border border-slate-800">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow className="border-slate-800 sticky top-0 bg-slate-900">
|
||||||
|
<TableHead className="w-10 text-slate-400 text-xs">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="accent-blue-600"
|
||||||
|
checked={ldapSelected.size === ldapUsers.length && ldapUsers.length > 0}
|
||||||
|
onChange={(e) => {
|
||||||
|
if (e.target.checked) {
|
||||||
|
setLdapSelected(new Set(ldapUsers.map((u) => u.dn)));
|
||||||
|
} else {
|
||||||
|
setLdapSelected(new Set());
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">用户名</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">显示名</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">邮箱</TableHead>
|
||||||
|
<TableHead className="text-slate-400 text-xs">DN</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{ldapUsers.map((u) => (
|
||||||
|
<TableRow key={u.dn} className="border-slate-800 hover:bg-slate-800/50">
|
||||||
|
<TableCell>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="accent-blue-600"
|
||||||
|
checked={ldapSelected.has(u.dn)}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = new Set(ldapSelected);
|
||||||
|
if (e.target.checked) next.add(u.dn);
|
||||||
|
else next.delete(u.dn);
|
||||||
|
setLdapSelected(next);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-slate-200 text-xs">{u.uid}</TableCell>
|
||||||
|
<TableCell className="text-slate-300 text-xs">{u.cn}</TableCell>
|
||||||
|
<TableCell className="text-slate-400 text-xs">{u.mail}</TableCell>
|
||||||
|
<TableCell className="text-slate-500 text-xs font-mono truncate max-w-[200px]">{u.dn}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => { setImportDialogOpen(null); setLdapUsers([]); }}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={handleLdapImport} disabled={importing || ldapSelected.size === 0}>
|
||||||
|
{importing ? '导入中...' : `导入选中 (${ldapSelected.size})`}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4 py-2">
|
||||||
|
<div className={`flex items-center gap-3 p-4 rounded-lg ${importResult.code === 200 ? 'bg-emerald-500/10' : 'bg-red-500/10'}`}>
|
||||||
|
{importResult.code === 200 ? (
|
||||||
|
<CheckCircle className="h-6 w-6 text-emerald-400 shrink-0" />
|
||||||
|
) : (
|
||||||
|
<XCircle className="h-6 w-6 text-red-400 shrink-0" />
|
||||||
|
)}
|
||||||
|
<span className="text-sm text-slate-200">{importResult.message}</span>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={() => { setImportDialogOpen(null); setLdapUsers([]); setImportResult(null); }}>
|
||||||
|
完成
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { User } from 'lucide-react';
|
||||||
|
import { roles } from '@/mocks/data';
|
||||||
|
|
||||||
|
export interface UserFormData {
|
||||||
|
username: string;
|
||||||
|
nickname: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
role: string;
|
||||||
|
password: string;
|
||||||
|
status: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserFormDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editingUser: any | null;
|
||||||
|
form: UserFormData;
|
||||||
|
setForm: React.Dispatch<React.SetStateAction<UserFormData>>;
|
||||||
|
saving: boolean;
|
||||||
|
onSubmit: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserFormDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
editingUser,
|
||||||
|
form,
|
||||||
|
setForm,
|
||||||
|
saving,
|
||||||
|
onSubmit,
|
||||||
|
}: UserFormDialogProps) {
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="bg-slate-900 border-slate-800">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-slate-100 flex items-center gap-2">
|
||||||
|
<User className="h-5 w-5 text-blue-400" />
|
||||||
|
{editingUser ? '编辑用户' : '新建用户'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-slate-500">
|
||||||
|
{editingUser ? '修改用户信息' : '创建新的系统用户'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">用户名</label>
|
||||||
|
<Input
|
||||||
|
value={form.username}
|
||||||
|
onChange={(e) => setForm({ ...form, username: e.target.value })}
|
||||||
|
disabled={!!editingUser}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
placeholder="登录用户名"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">昵称</label>
|
||||||
|
<Input
|
||||||
|
value={form.nickname}
|
||||||
|
onChange={(e) => setForm({ ...form, nickname: e.target.value })}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
placeholder="显示昵称"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">邮箱</label>
|
||||||
|
<Input
|
||||||
|
value={form.email}
|
||||||
|
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
placeholder="user@example.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">手机号</label>
|
||||||
|
<Input
|
||||||
|
value={form.phone}
|
||||||
|
onChange={(e) => setForm({ ...form, phone: e.target.value })}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
placeholder="可选"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">角色</label>
|
||||||
|
<Select value={form.role} onValueChange={(v) => setForm({ ...form, role: v })}>
|
||||||
|
<SelectTrigger className="bg-slate-800/50 border-slate-700 text-slate-200">
|
||||||
|
<SelectValue placeholder="选择角色" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="bg-slate-800 border-slate-700">
|
||||||
|
{roles.map((role) => (
|
||||||
|
<SelectItem key={role.id} value={role.name}>
|
||||||
|
{role.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">状态</label>
|
||||||
|
<Select
|
||||||
|
value={String(form.status)}
|
||||||
|
onValueChange={(v) => setForm({ ...form, status: Number(v) })}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="bg-slate-800/50 border-slate-700 text-slate-200">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="bg-slate-800 border-slate-700">
|
||||||
|
<SelectItem value="1">正常</SelectItem>
|
||||||
|
<SelectItem value="0">禁用</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-xs text-slate-500">
|
||||||
|
密码{editingUser ? '(留空则不修改)' : ''}
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
value={form.password}
|
||||||
|
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||||
|
className="bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
|
||||||
|
placeholder={editingUser ? '留空则不修改' : '设置初始密码'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => onOpenChange(false)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white" onClick={onSubmit} disabled={saving}>
|
||||||
|
{saving ? '保存中...' : '保存'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user