F1 告警静默规则 [done]: - 后端 alert_silence.go: CRUD + Toggle (onetime/daily/weekly 三模式) - 告警引擎 isSilenced 集成 (alert_engine.go) - 前端 SilenceRuleTab + SilenceDialog - 路由 /alerts/silences 已注册 F2 审计日志导出 [done]: - 重写 ExportAuditLogs: 真正的 CSV 导出 (encoding/csv + UTF-8 BOM) - 支持 module/action/username/startTime/endTime 筛选 - 导出限制 10000 条防溢出,自动记录审计日志 - JSON 格式向后兼容 (format=json) - 前端 exportLogs 传递查询参数 同时包含累积的前期工作: - 目录重构 internal/ -> controller/model/router (v0.55-v0.57) - 后端分层架构 dto/repository/service/utils - 审计模块全功能 (终端审计/操作审计/登录日志) - asciicast v2 录制格式 - SFTP 文件浏览器 - StatStrip 紧凑统计条 - 在线会话自动刷新 - LiveMonitor WebSocket 诊断修复 验证: go build ✅ | npm run build ✅ | Docker 部署 ✅ | 10 回归端点 ✅ | CSV 导出 ✅ | 静默 CRUD ✅
308 lines
7.9 KiB
Go
308 lines
7.9 KiB
Go
package controller
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"sort"
|
|
"time"
|
|
|
|
"ezops/model"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// BillingHandler 云账单处理器
|
|
type BillingHandler struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewBillingHandler(db *gorm.DB) *BillingHandler {
|
|
return &BillingHandler{db: db}
|
|
}
|
|
|
|
// ListBillings 获取账单列表
|
|
func (h *BillingHandler) ListBillings(c *gin.Context) {
|
|
var billings []model.CloudBilling
|
|
|
|
query := h.db.Model(&model.CloudBilling{})
|
|
|
|
// 筛选
|
|
if provider := c.Query("provider"); provider != "" {
|
|
query = query.Where("provider = ?", provider)
|
|
}
|
|
if accountName := c.Query("account_name"); accountName != "" {
|
|
query = query.Where("account_name LIKE ?", "%"+accountName+"%")
|
|
}
|
|
if startDate := c.Query("start_date"); startDate != "" {
|
|
query = query.Where("billing_date >= ?", startDate)
|
|
}
|
|
if endDate := c.Query("end_date"); endDate != "" {
|
|
query = query.Where("billing_date <= ?", endDate)
|
|
}
|
|
|
|
// 排序
|
|
query = query.Order("billing_date DESC, id DESC")
|
|
|
|
// 分页
|
|
page := 1
|
|
pageSize := 50
|
|
if c.Query("page") != "" {
|
|
fmt.Sscanf(c.Query("page"), "%d", &page)
|
|
}
|
|
if c.Query("page_size") != "" {
|
|
fmt.Sscanf(c.Query("page_size"), "%d", &pageSize)
|
|
}
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 || pageSize > 500 {
|
|
pageSize = 50
|
|
}
|
|
|
|
var total int64
|
|
query.Count(&total)
|
|
query.Offset((page - 1) * pageSize).Limit(pageSize).Find(&billings)
|
|
|
|
c.JSON(http.StatusOK, model.Response{
|
|
Code: 200,
|
|
Message: "success",
|
|
Data: model.ListResponse{
|
|
List: billings,
|
|
Total: total,
|
|
},
|
|
})
|
|
}
|
|
|
|
// CreateBilling 创建账单记录
|
|
func (h *BillingHandler) CreateBilling(c *gin.Context) {
|
|
var req model.CreateBillingRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
|
|
return
|
|
}
|
|
|
|
billing := model.CloudBilling{
|
|
CloudAccountID: req.CloudAccountID,
|
|
AccountName: req.AccountName,
|
|
Provider: req.Provider,
|
|
BillingDate: req.BillingDate,
|
|
Cost: req.Cost,
|
|
Currency: req.Currency,
|
|
Service: req.Service,
|
|
Region: req.Region,
|
|
Description: req.Description,
|
|
}
|
|
if billing.Currency == "" {
|
|
billing.Currency = "CNY"
|
|
}
|
|
|
|
if err := h.db.Create(&billing).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, model.Response{
|
|
Code: 200,
|
|
Message: "创建成功",
|
|
Data: billing,
|
|
})
|
|
}
|
|
|
|
// BatchCreateBillings 批量创建账单
|
|
func (h *BillingHandler) BatchCreateBillings(c *gin.Context) {
|
|
var req struct {
|
|
Records []model.CreateBillingRequest `json:"records" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
|
|
return
|
|
}
|
|
|
|
created := 0
|
|
for _, r := range req.Records {
|
|
billing := model.CloudBilling{
|
|
CloudAccountID: r.CloudAccountID,
|
|
AccountName: r.AccountName,
|
|
Provider: r.Provider,
|
|
BillingDate: r.BillingDate,
|
|
Cost: r.Cost,
|
|
Currency: r.Currency,
|
|
Service: r.Service,
|
|
Region: r.Region,
|
|
Description: r.Description,
|
|
}
|
|
if billing.Currency == "" {
|
|
billing.Currency = "CNY"
|
|
}
|
|
if err := h.db.Create(&billing).Error; err == nil {
|
|
created++
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, model.Response{
|
|
Code: 200,
|
|
Message: fmt.Sprintf("成功导入 %d 条记录", created),
|
|
Data: gin.H{"created": created, "total": len(req.Records)},
|
|
})
|
|
}
|
|
|
|
// DeleteBilling 删除账单记录
|
|
func (h *BillingHandler) DeleteBilling(c *gin.Context) {
|
|
id := c.Param("id")
|
|
if err := h.db.Delete(&model.CloudBilling{}, id).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"})
|
|
}
|
|
|
|
// GetBillingStats 获取账单统计
|
|
func (h *BillingHandler) GetBillingStats(c *gin.Context) {
|
|
now := time.Now()
|
|
today := now.Format("2006-01-02")
|
|
yesterday := now.AddDate(0, 0, -1).Format("2006-01-02")
|
|
monthStart := now.Format("2006-01") + "-01"
|
|
yearStart := fmt.Sprintf("%d-01-01", now.Year())
|
|
|
|
stats := model.BillingStats{
|
|
MonthTrend: []model.DailyCost{},
|
|
ProviderDist: []model.ProviderCost{},
|
|
Alerts: []model.BillingAlert{},
|
|
}
|
|
|
|
// 今日成本
|
|
h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", today).
|
|
Select("COALESCE(SUM(cost), 0)").Scan(&stats.TodayCost)
|
|
|
|
// 昨日成本
|
|
h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", yesterday).
|
|
Select("COALESCE(SUM(cost), 0)").Scan(&stats.YesterdayCost)
|
|
|
|
// 本月成本
|
|
h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", monthStart).
|
|
Select("COALESCE(SUM(cost), 0)").Scan(&stats.MonthCost)
|
|
|
|
// 本年成本
|
|
h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", yearStart).
|
|
Select("COALESCE(SUM(cost), 0)").Scan(&stats.YearCost)
|
|
|
|
// 近30天趋势
|
|
type dayCost struct {
|
|
BillingDate string
|
|
Total float64
|
|
}
|
|
var trends []dayCost
|
|
h.db.Model(&model.CloudBilling{}).
|
|
Select("billing_date, SUM(cost) as total").
|
|
Where("billing_date >= ?", now.AddDate(0, 0, -29).Format("2006-01-02")).
|
|
Group("billing_date").
|
|
Order("billing_date ASC").
|
|
Scan(&trends)
|
|
|
|
for _, t := range trends {
|
|
stats.MonthTrend = append(stats.MonthTrend, model.DailyCost{Date: t.BillingDate, Cost: t.Total})
|
|
}
|
|
|
|
// 本月厂商成本分布
|
|
type provCost struct {
|
|
Provider string
|
|
Total float64
|
|
}
|
|
var provCosts []provCost
|
|
h.db.Model(&model.CloudBilling{}).
|
|
Select("provider, SUM(cost) as total").
|
|
Where("billing_date >= ?", monthStart).
|
|
Group("provider").
|
|
Scan(&provCosts)
|
|
|
|
var totalProviderCost float64
|
|
for _, p := range provCosts {
|
|
totalProviderCost += p.Total
|
|
}
|
|
for _, p := range provCosts {
|
|
percent := 0.0
|
|
if totalProviderCost > 0 {
|
|
percent = p.Total / totalProviderCost * 100
|
|
}
|
|
stats.ProviderDist = append(stats.ProviderDist, model.ProviderCost{
|
|
Provider: p.Provider,
|
|
Cost: p.Total,
|
|
Percent: percent,
|
|
})
|
|
}
|
|
sort.Slice(stats.ProviderDist, func(i, j int) bool {
|
|
return stats.ProviderDist[i].Cost > stats.ProviderDist[j].Cost
|
|
})
|
|
|
|
// 检查预警规则
|
|
h.checkBillingAlerts(&stats, now)
|
|
|
|
c.JSON(http.StatusOK, model.Response{
|
|
Code: 200,
|
|
Message: "success",
|
|
Data: stats,
|
|
})
|
|
}
|
|
|
|
// checkBillingAlerts 检查预警规则是否触发
|
|
func (h *BillingHandler) checkBillingAlerts(stats *model.BillingStats, now time.Time) {
|
|
var rules []model.BillingAlertRule
|
|
h.db.Where("enabled = ?", true).Find(&rules)
|
|
|
|
for _, rule := range rules {
|
|
var current float64
|
|
|
|
if rule.Metric == "daily" {
|
|
// 查今日该厂商/账号的成本
|
|
q := h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", now.Format("2006-01-02"))
|
|
if rule.Provider != "" {
|
|
q = q.Where("provider = ?", rule.Provider)
|
|
}
|
|
if rule.CloudAccountID != nil {
|
|
q = q.Where("cloud_account_id = ?", *rule.CloudAccountID)
|
|
}
|
|
q.Select("COALESCE(SUM(cost), 0)").Scan(¤t)
|
|
} else {
|
|
// monthly - 本月累计
|
|
q := h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", now.Format("2006-01")+"-01")
|
|
if rule.Provider != "" {
|
|
q = q.Where("provider = ?", rule.Provider)
|
|
}
|
|
if rule.CloudAccountID != nil {
|
|
q = q.Where("cloud_account_id = ?", *rule.CloudAccountID)
|
|
}
|
|
q.Select("COALESCE(SUM(cost), 0)").Scan(¤t)
|
|
}
|
|
|
|
// 检查阈值
|
|
triggered := false
|
|
switch rule.Operator {
|
|
case ">":
|
|
triggered = current > rule.Threshold
|
|
case ">=":
|
|
triggered = current >= rule.Threshold
|
|
case "<":
|
|
triggered = current < rule.Threshold
|
|
case "<=":
|
|
triggered = current <= rule.Threshold
|
|
}
|
|
|
|
if triggered {
|
|
providerLabel := rule.Provider
|
|
if providerLabel == "" {
|
|
providerLabel = "全部"
|
|
}
|
|
stats.Alerts = append(stats.Alerts, model.BillingAlert{
|
|
RuleID: rule.ID,
|
|
RuleName: rule.Name,
|
|
Provider: providerLabel,
|
|
Current: current,
|
|
Threshold: rule.Threshold,
|
|
Metric: rule.Metric,
|
|
Operator: rule.Operator,
|
|
})
|
|
}
|
|
}
|
|
}
|