feat: 更新多个模块以支持新的数据结构和日志格式

This commit is contained in:
TsMask
2025-02-20 10:08:27 +08:00
parent 045a2b6b01
commit f3c33b31ac
272 changed files with 13246 additions and 15885 deletions

BIN
src/assets/ip2region.xdb Normal file

Binary file not shown.

View File

@@ -155,6 +155,11 @@ gorm:
password: "<password>" password: "<password>"
database: "<database>" database: "<database>"
logging: false logging: false
# 内置轻量级数据库
lite:
type: "sqlite"
database: "<database path>"
logging: false
# 多个数据源时可以用这个指定默认的数据源 # 多个数据源时可以用这个指定默认的数据源
defaultDataSourceName: "default" defaultDataSourceName: "default"
@@ -190,9 +195,9 @@ user:
maxRetryCount: 5 maxRetryCount: 5
# 密码锁定时间,单位分钟默认10分钟 # 密码锁定时间,单位分钟默认10分钟
lockTime: 10 lockTime: 10
# 管理员列表 # 设定为系统管理员的用户ID
adminList: system:
- "1" - 1
# char 字符验证码配置 # char 字符验证码配置
charCaptcha: charCaptcha:

View File

@@ -5,9 +5,9 @@ import (
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/cron" "be.ems/src/framework/cron"
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/database/redis"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/redis"
) )
//go:embed config/*.yaml //go:embed config/*.yaml
@@ -19,11 +19,12 @@ var assetsDir embed.FS
// 配置中心初始加载 // 配置中心初始加载
func ConfigurationInit() { func ConfigurationInit() {
// 初始配置参数 // 初始配置参数
config.InitConfig(configDir, assetsDir) config.InitConfig(&configDir)
config.SetAssetsDirFS(&assetsDir)
// 初始程序日志 // 初始程序日志
logger.InitLogger() logger.InitLogger()
// 连接数据库实例 // 连接数据库实例
datasource.Connect() db.Connect()
// 连接Redis实例 // 连接Redis实例
redis.Connect() redis.Connect()
// 启动调度任务实例 // 启动调度任务实例
@@ -37,7 +38,7 @@ func ConfigurationClose() {
// 关闭Redis实例 // 关闭Redis实例
redis.Close() redis.Close()
// 关闭数据库实例 // 关闭数据库实例
datasource.Close() db.Close()
// 关闭程序日志 // 关闭程序日志
logger.Close() logger.Close()
} }

View File

@@ -1,12 +1,14 @@
package controller package controller
import ( import (
"fmt"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"be.ems/src/modules/chart/service" "be.ems/src/modules/chart/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 ChartGraphController 结构体 // 实例化控制层 ChartGraphController 结构体
@@ -36,7 +38,7 @@ type ChartGraphController struct {
// @Router /chart/graph/groups [get] // @Router /chart/graph/groups [get]
func (s *ChartGraphController) GroupNames(c *gin.Context) { func (s *ChartGraphController) GroupNames(c *gin.Context) {
data := s.chartGraphService.SelectGroup() data := s.chartGraphService.SelectGroup()
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// 获取关系图数据 // 获取关系图数据
@@ -47,25 +49,25 @@ func (s *ChartGraphController) GroupNames(c *gin.Context) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param group query string true "Group" // @Param group query string true "Group"
// @Param type query string true "Type" Enums(node, edge, combo) // @Param type query string false "Type" Enums(node, edge, combo)
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Getting Relationship Map Data // @Summary Getting Relationship Map Data
// @Description Getting Relationship Map Data // @Description Getting Relationship Map Data
// @Router /chart/graph [get] // @Router /chart/graph [get]
func (s *ChartGraphController) Load(c *gin.Context) { func (s *ChartGraphController) Load(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var querys struct { var querys struct {
Group string `form:"group" binding:"required"` Group string `form:"group" binding:"required"`
Type string `form:"type" binding:"omitempty,oneof=node edge combo"` Type string `form:"type" binding:"omitempty,oneof=node edge combo"`
} }
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
data := s.chartGraphService.LoadData(querys.Group, querys.Type) data := s.chartGraphService.LoadData(querys.Group, querys.Type)
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// 保存关系图数据 // 保存关系图数据
@@ -80,9 +82,8 @@ func (s *ChartGraphController) Load(c *gin.Context) {
// @Security TokenAuth // @Security TokenAuth
// @Summary Saving Relationship Diagram Data // @Summary Saving Relationship Diagram Data
// @Description Saving Relationship Diagram Data // @Description Saving Relationship Diagram Data
// @Router /chart/graph/ [post] // @Router /chart/graph [post]
func (s *ChartGraphController) Save(c *gin.Context) { func (s *ChartGraphController) Save(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var body struct { var body struct {
Group string `json:"group" binding:"required"` Group string `json:"group" binding:"required"`
Data struct { Data struct {
@@ -91,9 +92,9 @@ func (s *ChartGraphController) Save(c *gin.Context) {
Combos []map[string]any `json:"combos" binding:"required"` Combos []map[string]any `json:"combos" binding:"required"`
} `json:"data" binding:"required"` } `json:"data" binding:"required"`
} }
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
@@ -104,10 +105,10 @@ func (s *ChartGraphController) Save(c *gin.Context) {
} }
saveNum := s.chartGraphService.SaveData(body.Group, data) saveNum := s.chartGraphService.SaveData(body.Group, data)
if saveNum > 0 { if saveNum > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 删除关系图数据 // 删除关系图数据
@@ -124,17 +125,17 @@ func (s *ChartGraphController) Save(c *gin.Context) {
// @Description Deleting Relationship Diagram Data // @Description Deleting Relationship Diagram Data
// @Router /chart/graph/{group} [delete] // @Router /chart/graph/{group} [delete]
func (s *ChartGraphController) Delete(c *gin.Context) { func (s *ChartGraphController) Delete(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
group := c.Param("group") group := c.Param("group")
if group == "" { if group == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
deleteNum := s.chartGraphService.DeleteGroup(group) deleteNum := s.chartGraphService.DeleteGroup(group)
if deleteNum > 0 { if deleteNum > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }

View File

@@ -2,28 +2,28 @@ package model
// ChartGraph 图表-G6关系图数据对象 chart_graph // ChartGraph 图表-G6关系图数据对象 chart_graph
type ChartGraph struct { type ChartGraph struct {
RowID int64 `json:"rowId,omitempty" gorm:"column:row_id;primaryKey;autoIncrement"` // 记录ID RowId int64 `json:"rowId" gorm:"column:row_id;primaryKey;autoIncrement"` // 记录ID
RowType string `json:"rowType" gorm:"row_type"` // 记录类型 RowType string `json:"rowType" gorm:"column:row_type"` // 记录类型
RowGroup string `json:"rowGroup" gorm:"row_group"` // 记录组名 RowGroup string `json:"rowGroup" gorm:"column:row_group"` // 记录组名
ID string `json:"id" gorm:"id"` // 元素ID ID string `json:"id" gorm:"column:id"` // 元素ID
Type string `json:"type" gorm:"type"` // node/combo 类型 Type string `json:"type" gorm:"column:type"` // node/combo 类型
Depth int64 `json:"depth" gorm:"depth"` // node/combo 深度 Depth int64 `json:"depth" gorm:"column:depth"` // node/combo 深度
X float64 `json:"x" gorm:"x"` // node/combo 横向坐标 X float64 `json:"x" gorm:"column:x"` // node/combo 横向坐标
Y float64 `json:"y" gorm:"y"` // node/combo 纵向坐标 Y float64 `json:"y" gorm:"column:y"` // node/combo 纵向坐标
Size string `json:"size" gorm:"size"` // node/combo 大小-JSON数组 Size string `json:"size" gorm:"column:size"` // node/combo 大小-JSON数组
Icon string `json:"icon" gorm:"icon"` // node-部分类型支持图标JSON配置 Icon string `json:"icon" gorm:"column:icon"` // node-部分类型支持图标JSON配置
Img string `json:"img" gorm:"img"` // node-img 图片 Img string `json:"img" gorm:"column:img"` // node-img 图片
ClipCfg string `json:"clipCfg" gorm:"clip_cfg"` // node-img 图片裁剪JSON配置 ClipCfg string `json:"clipCfg" gorm:"column:clip_cfg"` // node-img 图片裁剪JSON配置
Direction string `json:"direction" gorm:"direction"` // node-triangle 三角形的方向 Direction string `json:"direction" gorm:"column:direction"` // node-triangle 三角形的方向
Source string `json:"source" gorm:"source"` // edge-边起始 Source string `json:"source" gorm:"column:source"` // edge-边起始
Target string `json:"target" gorm:"target"` // edge-边目标 Target string `json:"target" gorm:"column:target"` // edge-边目标
ComboId string `json:"comboId" gorm:"combo_id"` // combo-分组 ComboId string `json:"comboId" gorm:"column:combo_id"` // combo-分组
Padding string `json:"padding" gorm:"padding"` // combo-JSON分组内边距 Padding string `json:"padding" gorm:"column:padding"` // combo-JSON分组内边距
ParentId string `json:"parentId" gorm:"parent_id"` // combo-父级分组 ParentId string `json:"parentId" gorm:"column:parent_id"` // combo-父级分组
Children string `json:"children" gorm:"children"` // combo-JSON分组内含元素 Children string `json:"children" gorm:"column:children"` // combo-JSON分组内含元素
Style string `json:"style" gorm:"style"` // 元素样式-JONS配置 Style string `json:"style" gorm:"column:style"` // 元素样式-JONS配置
Label string `json:"label" gorm:"label"` // 标签文本 Label string `json:"label" gorm:"column:label"` // 标签文本
LabelCfg string `json:"labelCfg" gorm:"label_cfg"` // 标签文本-JSON配置 LabelCfg string `json:"labelCfg" gorm:"column:label_cfg"` // 标签文本-JSON配置
} }
// TableName 表名称 // TableName 表名称

View File

@@ -1,183 +1,83 @@
package repository package repository
import ( import (
"strings" "be.ems/src/framework/database/db"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/chart/model" "be.ems/src/modules/chart/model"
) )
// 实例化数据层 ChartGraph 结构体 // 实例化数据层 ChartGraph 结构体
var NewChartGraph = &ChartGraph{ var NewChartGraph = &ChartGraph{}
selectSql: `select
row_id, row_type, row_group,
id, type, depth, x, y, size, icon, img,
clip_cfg, direction,
source, target, combo_id,
padding, parent_id, children,
style, label, label_cfg
from chart_graph`,
resultMap: map[string]string{
"row_id": "RowID",
"row_type": "RowType",
"row_group": "RowGroup",
"id": "ID",
"type": "Type",
"depth": "Depth",
"x": "X",
"y": "Y",
"size": "Size",
"icon": "Icon",
"img": "Img",
"clip_cfg": "ClipCfg",
"direction": "Direction",
"source": "Source",
"target": "Target",
"combo_id": "ComboID",
"padding": "Padding",
"parent_id": "ParentID",
"children": "Children",
"style": "Style",
"label": "Label",
"label_cfg": "LabelCfg",
},
}
// ChartGraph G6关系图数据表 数据层处理 // ChartGraph G6关系图数据表 数据层处理
type ChartGraph struct { type ChartGraph struct{}
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
// convertResultRows 将结果记录转实体结果组 // SelectByPage 分页查询集合
func (r *ChartGraph) convertResultRows(rows []map[string]any) []model.ChartGraph { func (r ChartGraph) SelectByPage(query map[string]string) ([]model.ChartGraph, int64) {
arr := make([]model.ChartGraph, 0) tx := db.DB("").Model(&model.ChartGraph{})
for _, row := range rows {
item := model.ChartGraph{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *ChartGraph) SelectPage(query map[string]any) map[string]any {
// 查询条件拼接 // 查询条件拼接
var conditions []string
var params []any
if v, ok := query["rowType"]; ok && v != "" { if v, ok := query["rowType"]; ok && v != "" {
conditions = append(conditions, "row_type = ?") tx = tx.Where("row_type = ?", v)
params = append(params, strings.Trim(v.(string), " "))
} }
if v, ok := query["rowGroup"]; ok && v != "" { if v, ok := query["rowGroup"]; ok && v != "" {
conditions = append(conditions, "row_group = ?") tx = tx.Where("row_group = ?", v)
params = append(params, strings.Trim(v.(string), " "))
} }
// 构建查询条件语句 // 查询结果
whereSql := "" var total int64 = 0
if len(conditions) > 0 { rows := []model.ChartGraph{}
whereSql += " where " + strings.Join(conditions, " and ")
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
} }
result := map[string]any{ // 查询数据分页
"total": 0, pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
"rows": []model.ChartGraph{}, tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
} err := tx.Find(&rows).Error
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from chart_graph"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
if err != nil { if err != nil {
logger.Errorf("total err => %v", err) logger.Errorf("query find err => %v", err.Error())
return result return rows, total
} }
total := parse.Number(totalRows[0]["total"]) return rows, total
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
} }
// SelectList 根据实体查询 // Select 查询集合
func (r *ChartGraph) SelectList(graph model.ChartGraph) []model.ChartGraph { func (r ChartGraph) Select(param model.ChartGraph) []model.ChartGraph {
tx := db.DB("").Model(&model.ChartGraph{})
// 查询条件拼接 // 查询条件拼接
var conditions []string if param.RowType != "" {
var params []any tx = tx.Where("row_type = ?", param.RowType)
if graph.RowType != "" {
conditions = append(conditions, "row_type = ?")
params = append(params, graph.RowType)
} }
if graph.RowGroup != "" { if param.RowGroup != "" {
conditions = append(conditions, "row_group = ?") tx = tx.Where("row_group = ?", param.RowGroup)
params = append(params, graph.RowGroup)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} }
// 查询数据 // 查询数据
querySql := r.selectSql + whereSql + " order by depth asc " rows := []model.ChartGraph{}
results, err := datasource.RawDB("", querySql, params) if err := tx.Order("depth asc").Find(&rows).Error; err != nil {
if err != nil { logger.Errorf("query find err => %v", err.Error())
logger.Errorf("query err => %v", err) return rows
} }
return rows
// 转换实体
return r.convertResultRows(results)
} }
// SelectGroup 查询组名 // SelectGroup 查询组名
func (r *ChartGraph) SelectGroup() []string { func (r ChartGraph) SelectGroup() []string {
tx := db.DB("").Model(&model.ChartGraph{})
// 查询数据
rows := []string{} rows := []string{}
// 查询数量 长度为0直接返回 if err := tx.Select("row_group").Group("row_group").Find(&rows).Error; err != nil {
querySql := "select row_group as 'str' from chart_graph GROUP BY row_group" logger.Errorf("query find err => %v", err.Error())
strRows, err := datasource.RawDB("", querySql, nil)
if err != nil {
logger.Errorf("Query err => %v", err)
return rows return rows
} }
for _, v := range strRows {
rows = append(rows, v["str"].(string))
}
return rows return rows
} }
// Insert 批量添加 // Insert 批量添加
func (r *ChartGraph) Inserts(graphs []model.ChartGraph) int64 { func (r ChartGraph) Inserts(graphs []model.ChartGraph) int64 {
tx := datasource.DefaultDB().CreateInBatches(graphs, 2000) tx := db.DB("").CreateInBatches(graphs, 2000)
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err) logger.Errorf("CreateInBatches err => %v", err)
} }
@@ -185,8 +85,8 @@ func (r *ChartGraph) Inserts(graphs []model.ChartGraph) int64 {
} }
// Delete 删除组数据 // Delete 删除组数据
func (r *ChartGraph) DeleteGroup(rowGroup string) int64 { func (r ChartGraph) DeleteGroup(rowGroup string) int64 {
tx := datasource.DefaultDB().Where("row_group = ?", rowGroup).Delete(&model.ChartGraph{}) tx := db.DB("").Where("row_group = ?", rowGroup).Delete(&model.ChartGraph{})
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("Delete err => %v", err) logger.Errorf("Delete err => %v", err)
} }

View File

@@ -34,7 +34,7 @@ func (s *ChartGraph) LoadData(rowGroup, rowType string) map[string]any {
if rowType != "" { if rowType != "" {
graph.RowType = rowType graph.RowType = rowType
} }
data := s.graphRepository.SelectList(graph) data := s.graphRepository.Select(graph)
// 数据项 // 数据项
nodes := []map[string]any{} nodes := []map[string]any{}

View File

@@ -13,18 +13,17 @@ func Setup(router *gin.Engine) {
logger.Infof("开始加载 ====> common 模块路由") logger.Infof("开始加载 ====> common 模块路由")
// 路由主页 // 路由主页
indexGroup := router.Group("/") router.GET("/",
indexGroup.GET("", middleware.RateLimit(middleware.LimitOption{
// middleware.RateLimit(middleware.LimitOption{ Time: 300,
// Time: 300, Count: 10,
// Count: 10, Type: middleware.LIMIT_IP,
// Type: middleware.LIMIT_IP, }),
// }),
controller.NewIndex.Handler, controller.NewIndex.Handler,
) )
// 系统可暴露的配置信息 // 系统可暴露的配置信息
indexGroup.GET("/sys-conf", controller.NewCommont.SysConfig) router.GET("/sys-conf", controller.NewCommon.SysConfig)
// 系统引导初始化 // 系统引导初始化
guideGroup := router.Group("/bootloader") guideGroup := router.Group("/bootloader")
{ {
@@ -34,47 +33,47 @@ func Setup(router *gin.Engine) {
guideGroup.PUT("/account", middleware.PreAuthorize(nil), controller.NewBootloader.Account) guideGroup.PUT("/account", middleware.PreAuthorize(nil), controller.NewBootloader.Account)
} }
// 验证码操作处理 // 验证码操作
indexGroup.GET("/captchaImage", router.GET("/captcha-image",
// middleware.RateLimit(middleware.LimitOption{ middleware.RateLimit(middleware.LimitOption{
// Time: 300, Time: 300,
// Count: 60, Count: 60,
// Type: middleware.LIMIT_IP, Type: middleware.LIMIT_IP,
// }), }),
controller.NewCaptcha.Image, controller.NewCaptcha.Image,
) )
// 账号身份操作处理 // 账号身份操作处理
{ {
indexGroup.POST("/login", router.POST("/login",
// middleware.RateLimit(middleware.LimitOption{ middleware.RateLimit(middleware.LimitOption{
// Time: 300, Time: 180,
// Count: 10, Count: 15,
// Type: middleware.LIMIT_IP, Type: middleware.LIMIT_IP,
// }), }),
middleware.CryptoApi(true, true), middleware.CryptoApi(true, true),
controller.NewAccount.Login, controller.NewAccount.Login,
) )
indexGroup.GET("/getInfo", middleware.PreAuthorize(nil), controller.NewAccount.Info) router.GET("/me", middleware.PreAuthorize(nil), controller.NewAccount.Me)
indexGroup.GET("/getRouters", middleware.PreAuthorize(nil), controller.NewAccount.Router) router.GET("/router", middleware.PreAuthorize(nil), controller.NewAccount.Router)
indexGroup.POST("/logout", router.POST("/logout",
middleware.RateLimit(middleware.LimitOption{ middleware.RateLimit(middleware.LimitOption{
Time: 300, Time: 120,
Count: 5, Count: 15,
Type: middleware.LIMIT_IP, Type: middleware.LIMIT_IP,
}), }),
controller.NewAccount.Logout, controller.NewAccount.Logout,
) )
} }
// 账号注册操作处理 // 账号注册操作
{ {
indexGroup.POST("/register", router.POST("/register",
// middleware.RateLimit(middleware.LimitOption{ middleware.RateLimit(middleware.LimitOption{
// Time: 300, Time: 300,
// Count: 10, Count: 10,
// Type: middleware.LIMIT_IP, Type: middleware.LIMIT_IP,
// }), }),
middleware.CryptoApi(true, true), middleware.CryptoApi(true, true),
controller.NewRegister.Register, controller.NewRegister.Register,
) )
@@ -83,8 +82,8 @@ func Setup(router *gin.Engine) {
// 通用请求 // 通用请求
commonGroup := router.Group("/common") commonGroup := router.Group("/common")
{ {
commonGroup.POST("/hash", middleware.PreAuthorize(nil), controller.NewCommont.Hash) commonGroup.POST("/hash", middleware.PreAuthorize(nil), controller.NewCommon.Hash)
commonGroup.GET("/i18n", controller.NewCommont.I18n) commonGroup.GET("/i18n", controller.NewCommon.I18n)
} }
// 文件操作处理 // 文件操作处理
@@ -95,6 +94,6 @@ func Setup(router *gin.Engine) {
fileGroup.POST("/chunkCheck", middleware.PreAuthorize(nil), controller.NewFile.ChunkCheck) fileGroup.POST("/chunkCheck", middleware.PreAuthorize(nil), controller.NewFile.ChunkCheck)
fileGroup.POST("/chunkUpload", middleware.PreAuthorize(nil), controller.NewFile.ChunkUpload) fileGroup.POST("/chunkUpload", middleware.PreAuthorize(nil), controller.NewFile.ChunkUpload)
fileGroup.POST("/chunkMerge", middleware.PreAuthorize(nil), controller.NewFile.ChunkMerge) fileGroup.POST("/chunkMerge", middleware.PreAuthorize(nil), controller.NewFile.ChunkMerge)
fileGroup.POST("/transferStaticFile", middleware.PreAuthorize(nil), controller.NewCommont.TransferStaticFile) fileGroup.POST("/transferStaticFile", middleware.PreAuthorize(nil), controller.NewFile.TransferStaticFile)
} }
} }

View File

@@ -1,36 +1,38 @@
package controller package controller
import ( import (
"fmt"
"strings"
"be.ems/src/framework/config" "be.ems/src/framework/config"
commonConstants "be.ems/src/framework/constants/common" "be.ems/src/framework/constants"
tokenConstants "be.ems/src/framework/constants/token"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
tokenUtils "be.ems/src/framework/utils/token" "be.ems/src/framework/resp"
"be.ems/src/framework/vo" "be.ems/src/framework/token"
"be.ems/src/framework/vo/result" "be.ems/src/modules/common/model"
commonModel "be.ems/src/modules/common/model" "be.ems/src/modules/common/service"
commonService "be.ems/src/modules/common/service" systemModelVO "be.ems/src/modules/system/model/vo"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 AccountController 结构体 // 实例化控制层 AccountController 结构体
var NewAccount = &AccountController{ var NewAccount = &AccountController{
accountService: commonService.NewAccount, accountService: service.NewAccount,
sysLogLoginService: systemService.NewSysLogLoginImpl, sysLogLoginService: systemService.NewSysLogLogin,
} }
// 账号身份操作处理 // 账号身份操作处理
// //
// PATH / // PATH /
type AccountController struct { type AccountController struct {
accountService *commonService.Account // 账号身份操作服务 accountService *service.Account // 账号身份操作服务
// 系统登录访问 sysLogLoginService *systemService.SysLogLogin // 系统登录访问
sysLogLoginService systemService.ISysLogLogin
} }
// 系统登录 // Login 系统登录
// //
// POST /login // POST /login
// //
@@ -42,62 +44,62 @@ type AccountController struct {
// @Summary System Login // @Summary System Login
// @Description System Login // @Description System Login
// @Router /login [post] // @Router /login [post]
func (s *AccountController) Login(c *gin.Context) { func (s AccountController) Login(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var loginBody commonModel.LoginBody var body model.LoginBody
if err := c.ShouldBindJSON(&loginBody); err != nil { if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 当前请求信息 // 当前请求信息
ipaddr, location := ctx.IPAddrLocation(c) ipaddr, location := reqctx.IPAddrLocation(c)
os, browser := ctx.UaOsBrowser(c) os, browser := reqctx.UaOsBrowser(c)
// 校验验证码 // 校验验证码 根据错误信息,创建系统访问记录
err := s.accountService.ValidateCaptcha( if err := s.accountService.ValidateCaptcha(body.Code, body.UUID); err != nil {
loginBody.Code, msg := fmt.Sprintf("%s code: %s", err.Error(), body.Code)
loginBody.UUID, s.sysLogLoginService.Insert(
) body.Username, constants.STATUS_NO, msg,
// 根据错误信息,创建系统访问记录 [4]string{ipaddr, location, os, browser},
if err != nil {
s.sysLogLoginService.CreateSysLogLogin(
loginBody.Username, commonConstants.STATUS_NO, err.Error(),
ipaddr, location, os, browser,
) )
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(400, resp.CodeMsg(40012, i18n.TKey(language, err.Error())))
return return
} }
// 登录用户信息 // 登录用户信息
loginUser, err := s.accountService.LoginByUsername(loginBody.Username, loginBody.Password) loginUser, err := s.accountService.ByUsername(body.Username, body.Password)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
// 生成令牌,创建系统访问记录 // 生成令牌,创建系统访问记录
tokenStr := tokenUtils.Create(&loginUser, ipaddr, location, os, browser) tokenStr := token.Create(&loginUser, [4]string{ipaddr, location, os, browser})
if tokenStr == "" { if tokenStr == "" {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} else { } else {
s.accountService.UpdateLoginDateAndIP(&loginUser) s.accountService.UpdateLoginDateAndIP(loginUser)
// 登录成功 // 登录成功
s.sysLogLoginService.CreateSysLogLogin( s.sysLogLoginService.Insert(
loginBody.Username, commonConstants.STATUS_YES, "app.common.loginSuccess", body.Username, constants.STATUS_YES, "app.common.loginSuccess",
ipaddr, location, os, browser, [4]string{ipaddr, location, os, browser},
) )
} }
c.JSON(200, result.OkData(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
tokenConstants.RESPONSE_FIELD: tokenStr, "accessToken": tokenStr,
"tokenType": strings.TrimRight(constants.HEADER_PREFIX, " "),
"expiresIn": (loginUser.ExpireTime - loginUser.LoginTime) / 1000,
"userId": loginUser.UserId,
})) }))
} }
// 登录用户信息 // Me 登录用户信息
// //
// GET /getInfo // GET /me
// //
// @Tags common/authorization // @Tags common/authorization
// @Accept json // @Accept json
@@ -106,35 +108,35 @@ func (s *AccountController) Login(c *gin.Context) {
// @Security TokenAuth // @Security TokenAuth
// @Summary Login User Information // @Summary Login User Information
// @Description Login User Information // @Description Login User Information
// @Router /getInfo [get] // @Router /me [get]
func (s *AccountController) Info(c *gin.Context) { func (s AccountController) Me(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
loginUser, err := ctx.LoginUser(c) info, err := reqctx.LoginUser(c)
if err != nil { if err != nil {
c.JSON(401, result.CodeMsg(401, i18n.TKey(language, err.Error()))) c.JSON(401, resp.CodeMsg(40003, err.Error()))
return return
} }
// 角色权限集合,管理员拥有所有权限 // 角色权限集合,系统管理员拥有所有权限
isAdmin := config.IsAdmin(loginUser.UserID) isSystemUser := config.IsSystemUser(info.UserId)
roles, perms := s.accountService.RoleAndMenuPerms(loginUser.UserID, isAdmin) roles, perms := s.accountService.RoleAndMenuPerms(info.UserId, isSystemUser)
loginUser.User.NickName = i18n.TKey(language, loginUser.User.NickName) info.User.NickName = i18n.TKey(language, info.User.NickName)
loginUser.User.Remark = i18n.TKey(language, loginUser.User.Remark) info.User.Remark = i18n.TKey(language, info.User.Remark)
loginUser.User.Dept.DeptName = i18n.TKey(language, loginUser.User.Dept.DeptName) info.User.Dept.DeptName = i18n.TKey(language, info.User.Dept.DeptName)
for ri := range loginUser.User.Roles { for ri := range info.User.Roles {
loginUser.User.Roles[ri].RoleName = i18n.TKey(language, loginUser.User.Roles[ri].RoleName) info.User.Roles[ri].RoleName = i18n.TKey(language, info.User.Roles[ri].RoleName)
} }
c.JSON(200, result.OkData(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
"user": loginUser.User, "user": info.User,
"roles": roles, "roles": roles,
"permissions": perms, "permissions": perms,
})) }))
} }
// 登录用户路由信息 // Router 登录用户路由信息
// //
// GET /getRouters // GET /router
// //
// @Tags common/authorization // @Tags common/authorization
// @Accept json // @Accept json
@@ -143,18 +145,18 @@ func (s *AccountController) Info(c *gin.Context) {
// @Security TokenAuth // @Security TokenAuth
// @Summary Login User Routing Information // @Summary Login User Routing Information
// @Description Login User Routing Information // @Description Login User Routing Information
// @Router /getRouters [get] // @Router /router [get]
func (s *AccountController) Router(c *gin.Context) { func (s AccountController) Router(c *gin.Context) {
userID := ctx.LoginUserToUserID(c) userId := reqctx.LoginUserToUserID(c)
// 前端路由,管理员拥有所有 // 前端路由,系统管理员拥有所有
isAdmin := config.IsAdmin(userID) isSystemUser := config.IsSystemUser(userId)
buildMenus := s.accountService.RouteMenus(userID, isAdmin) buildMenus := s.accountService.RouteMenus(userId, isSystemUser)
// 闭包函数处理多语言 // 闭包函数处理多语言
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var converI18n func(language string, arr *[]vo.Router) var converI18n func(language string, arr *[]systemModelVO.Router)
converI18n = func(language string, arr *[]vo.Router) { converI18n = func(language string, arr *[]systemModelVO.Router) {
for i := range *arr { for i := range *arr {
(*arr)[i].Meta.Title = i18n.TKey(language, (*arr)[i].Meta.Title) (*arr)[i].Meta.Title = i18n.TKey(language, (*arr)[i].Meta.Title)
if len((*arr)[i].Children) > 0 { if len((*arr)[i].Children) > 0 {
@@ -164,10 +166,10 @@ func (s *AccountController) Router(c *gin.Context) {
} }
converI18n(language, &buildMenus) converI18n(language, &buildMenus)
c.JSON(200, result.OkData(buildMenus)) c.JSON(200, resp.OkData(buildMenus))
} }
// 系统登出 // Logout 系统登出
// //
// POST /logout // POST /logout
// //
@@ -179,25 +181,23 @@ func (s *AccountController) Router(c *gin.Context) {
// @Summary System Logout // @Summary System Logout
// @Description System Logout // @Description System Logout
// @Router /logout [post] // @Router /logout [post]
func (s *AccountController) Logout(c *gin.Context) { func (s AccountController) Logout(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
tokenStr := ctx.Authorization(c) tokenStr := reqctx.Authorization(c)
if tokenStr != "" { if tokenStr != "" {
// 存在token时记录退出信息 // 存在token时记录退出信息
userName := tokenUtils.Remove(tokenStr) userName := token.Remove(tokenStr)
if userName != "" { if userName != "" {
// 当前请求信息 // 当前请求信息
ipaddr, location := ctx.IPAddrLocation(c) ipaddr, location := reqctx.IPAddrLocation(c)
os, browser := ctx.UaOsBrowser(c) os, browser := reqctx.UaOsBrowser(c)
// 创建系统访问记录
// 创建系统访问记录 退出成功 s.sysLogLoginService.Insert(
userName, constants.STATUS_YES, "app.common.logoutSuccess",
s.sysLogLoginService.CreateSysLogLogin( [4]string{ipaddr, location, os, browser},
userName, commonConstants.STATUS_YES, "app.common.logoutSuccess",
ipaddr, location, os, browser,
) )
} }
} }
c.JSON(200, result.OkMsg(i18n.TKey(language, "app.common.logoutSuccess"))) c.JSON(200, resp.OkMsg(i18n.TKey(language, "app.common.logoutSuccess")))
} }

View File

@@ -1,34 +1,33 @@
package controller package controller
import ( import (
adminConstants "be.ems/src/framework/constants/admin" "strings"
"be.ems/src/framework/constants/common"
tokenConstants "be.ems/src/framework/constants/token" "be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/token"
"be.ems/src/framework/utils/machine" "be.ems/src/framework/utils/machine"
"be.ems/src/framework/utils/regular" "be.ems/src/framework/utils/regular"
tokenUtils "be.ems/src/framework/utils/token" "be.ems/src/modules/common/service"
"be.ems/src/framework/vo"
"be.ems/src/framework/vo/result"
commonService "be.ems/src/modules/common/service"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 BootloaderController 结构体 // 实例化控制层 BootloaderController 结构体
var NewBootloader = &BootloaderController{ var NewBootloader = &BootloaderController{
accountService: commonService.NewAccount, accountService: service.NewAccount,
sysUserService: systemService.NewSysUserImpl, sysUserService: systemService.NewSysUser,
} }
// 系统引导初始化 // 系统引导初始化
// //
// PATH /bootloader // PATH /bootloader
type BootloaderController struct { type BootloaderController struct {
accountService *commonService.Account // 账号身份操作服务 accountService *service.Account // 账号身份操作服务
// 用户信息服务 sysUserService *systemService.SysUser // 用户信息服务
sysUserService systemService.ISysUser
} }
// 首次引导开始 // 首次引导开始
@@ -38,44 +37,47 @@ func (s *BootloaderController) Start(c *gin.Context) {
// 是否完成引导 // 是否完成引导
launchInfo := machine.LaunchInfo launchInfo := machine.LaunchInfo
if launchInfo == nil { if launchInfo == nil {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
if v, ok := launchInfo[common.LAUNCH_BOOTLOADER]; ok && !v.(bool) { if v, ok := launchInfo[constants.LAUNCH_BOOTLOADER]; ok && !v.(bool) {
c.JSON(200, result.ErrMsg("bootloader done")) c.JSON(200, resp.ErrMsg("bootloader done"))
return return
} }
// 查询用户登录账号 // 查询用户登录账号
sysUser := s.sysUserService.SelectUserById("1") sysUser := s.sysUserService.FindById(1)
if sysUser.UserID != "1" { if sysUser.UserId != 1 {
c.JSON(200, result.ErrMsg("not found user data")) c.JSON(200, resp.ErrMsg("not found user data"))
return return
} }
// 登录用户信息 // 登录用户信息
loginUser := vo.LoginUser{ loginUser := token.TokenInfo{
UserID: sysUser.UserID, UserId: sysUser.UserId,
DeptID: sysUser.DeptID, DeptId: sysUser.DeptId,
User: sysUser, User: sysUser,
Permissions: []string{adminConstants.PERMISSION}, Permissions: []string{constants.SYS_PERMISSION_SYSTEM},
} }
// 当前请求信息 // 当前请求信息
ipaddr, location := ctx.IPAddrLocation(c) ipaddr, location := reqctx.IPAddrLocation(c)
os, browser := ctx.UaOsBrowser(c) os, browser := reqctx.UaOsBrowser(c)
// 生成令牌,创建系统访问记录 // 生成令牌,创建系统访问记录
tokenStr := tokenUtils.Create(&loginUser, ipaddr, location, os, browser) tokenStr := token.Create(&loginUser, [4]string{ipaddr, location, os, browser})
if tokenStr == "" { if tokenStr == "" {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} else { } else {
s.accountService.UpdateLoginDateAndIP(&loginUser) s.accountService.UpdateLoginDateAndIP(loginUser)
} }
c.JSON(200, result.OkData(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
tokenConstants.RESPONSE_FIELD: tokenStr, "accessToken": tokenStr,
"tokenType": strings.TrimRight(constants.HEADER_PREFIX, " "),
"expiresIn": (loginUser.ExpireTime - loginUser.LoginTime) / 1000,
"userId": loginUser.UserId,
})) }))
} }
@@ -86,23 +88,23 @@ func (s *BootloaderController) Done(c *gin.Context) {
// 是否完成引导 // 是否完成引导
launchInfo := machine.LaunchInfo launchInfo := machine.LaunchInfo
if launchInfo == nil { if launchInfo == nil {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
if v, ok := launchInfo[common.LAUNCH_BOOTLOADER]; ok && !v.(bool) { if v, ok := launchInfo[constants.LAUNCH_BOOTLOADER]; ok && !v.(bool) {
c.JSON(200, result.ErrMsg("bootloader done")) c.JSON(200, resp.ErrMsg("bootloader done"))
return return
} }
// 标记引导完成 // 标记引导完成
if err := machine.Bootloader(false); err != nil { if err := machine.Bootloader(false); err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
// 清除授权信息 // 清除授权信息
tokenUtils.Remove(ctx.Authorization(c)) token.Remove(reqctx.Authorization(c))
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
} }
// 引导系统数据重置 // 引导系统数据重置
@@ -112,69 +114,69 @@ func (s *BootloaderController) Reset(c *gin.Context) {
// 是否完成引导 // 是否完成引导
launchInfo := machine.LaunchInfo launchInfo := machine.LaunchInfo
if launchInfo == nil { if launchInfo == nil {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
if v, ok := launchInfo[common.LAUNCH_BOOTLOADER]; ok && v.(bool) { if v, ok := launchInfo[constants.LAUNCH_BOOTLOADER]; ok && v.(bool) {
c.JSON(200, result.ErrMsg("bootloader not done")) c.JSON(200, resp.ErrMsg("bootloader not done"))
return return
} }
if err := machine.Reset(); err != nil { if err := machine.Reset(); err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
// 清除授权信息 // 清除授权信息
tokenUtils.Remove(ctx.Authorization(c)) token.Remove(reqctx.Authorization(c))
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
} }
// 账号变更 // 账号变更
// //
// PUT /account // PUT /account
func (s *BootloaderController) Account(c *gin.Context) { func (s *BootloaderController) Account(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
UserName string `json:"username" binding:"required"` UserName string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"` Password string `json:"password" binding:"required"`
} }
if err := c.ShouldBindJSON(&body); err != nil { if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
if !regular.ValidPassword(body.Password) { if !regular.ValidPassword(body.Password) {
// 登录密码至少包含大小写字母、数字、特殊符号且不少于6位 // 登录密码至少包含大小写字母、数字、特殊符号且不少于6位
c.JSON(200, result.ErrMsg(i18n.TKey(language, "user.errPasswd"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "user.errPasswd")))
return return
} }
// 是否完成引导 // 是否完成引导
launchInfo := machine.LaunchInfo launchInfo := machine.LaunchInfo
if launchInfo == nil { if launchInfo == nil {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
if v, ok := launchInfo[common.LAUNCH_BOOTLOADER]; ok && !v.(bool) { if v, ok := launchInfo[constants.LAUNCH_BOOTLOADER]; ok && !v.(bool) {
c.JSON(200, result.ErrMsg("bootloader done")) c.JSON(200, resp.ErrMsg("bootloader done"))
return return
} }
// 查询用户登录账号 // 查询用户登录账号
sysUser := s.sysUserService.SelectUserById("2") sysUser := s.sysUserService.FindById(2)
if sysUser.UserID != "2" { if sysUser.UserId != 2 {
c.JSON(200, result.ErrMsg("not found user data")) c.JSON(200, resp.ErrMsg("not found user data"))
return return
} }
sysUser.UserName = body.UserName sysUser.UserName = body.UserName
sysUser.NickName = body.UserName sysUser.NickName = body.UserName
sysUser.Password = body.Password sysUser.Password = body.Password
sysUser.UpdateBy = ctx.LoginUserToUserName(c) sysUser.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.sysUserService.UpdateUser(sysUser) rows := s.sysUserService.Update(sysUser)
if rows > 0 { if rows > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }

View File

@@ -4,12 +4,11 @@ import (
"time" "time"
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/constants/cachekey" "be.ems/src/framework/constants"
"be.ems/src/framework/constants/captcha" "be.ems/src/framework/database/redis"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/redis" "be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -18,15 +17,14 @@ import (
// 实例化控制层 CaptchaController 结构体 // 实例化控制层 CaptchaController 结构体
var NewCaptcha = &CaptchaController{ var NewCaptcha = &CaptchaController{
sysConfigService: systemService.NewSysConfigImpl, sysConfigService: systemService.NewSysConfig,
} }
// 验证码操作处理 // 验证码操作处理
// //
// PATH / // PATH /
type CaptchaController struct { type CaptchaController struct {
// 参数配置服务 sysConfigService *systemService.SysConfig // 参数配置服务
sysConfigService systemService.ISysConfig
} }
// 获取验证码 // 获取验证码
@@ -43,10 +41,10 @@ type CaptchaController struct {
// @Router /captchaImage [get] // @Router /captchaImage [get]
func (s *CaptchaController) Image(c *gin.Context) { func (s *CaptchaController) Image(c *gin.Context) {
// 从数据库配置获取验证码开关 true开启false关闭 // 从数据库配置获取验证码开关 true开启false关闭
captchaEnabledStr := s.sysConfigService.SelectConfigValueByKey("sys.account.captchaEnabled") captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
captchaEnabled := parse.Boolean(captchaEnabledStr) captchaEnabled := parse.Boolean(captchaEnabledStr)
if !captchaEnabled { if !captchaEnabled {
c.JSON(200, result.Ok(map[string]any{ c.JSON(200, resp.Ok(map[string]any{
"captchaEnabled": captchaEnabled, "captchaEnabled": captchaEnabled,
})) }))
return return
@@ -61,8 +59,8 @@ func (s *CaptchaController) Image(c *gin.Context) {
} }
// 从数据库配置获取验证码类型 math 数值计算 char 字符验证 // 从数据库配置获取验证码类型 math 数值计算 char 字符验证
captchaType := s.sysConfigService.SelectConfigValueByKey("sys.account.captchaType") captchaType := s.sysConfigService.FindValueByKey("sys.account.captchaType")
if captchaType == captcha.TYPE_MATH { if captchaType == constants.CAPTCHA_TYPE_MATH {
math := config.Get("mathCaptcha").(map[string]any) math := config.Get("mathCaptcha").(map[string]any)
driverCaptcha := &base64Captcha.DriverMath{ driverCaptcha := &base64Captcha.DriverMath{
//Height png height in pixel. //Height png height in pixel.
@@ -87,12 +85,12 @@ func (s *CaptchaController) Image(c *gin.Context) {
} else { } else {
data["uuid"] = id data["uuid"] = id
data["img"] = item.EncodeB64string() data["img"] = item.EncodeB64string()
expiration := captcha.EXPIRATION * time.Second expiration := constants.CAPTCHA_EXPIRATION * time.Second
verifyKey = cachekey.CAPTCHA_CODE_KEY + id verifyKey = constants.CACHE_CAPTCHA_CODE + ":" + id
redis.SetByExpire("", verifyKey, answer, expiration) redis.SetByExpire("", verifyKey, answer, expiration)
} }
} }
if captchaType == captcha.TYPE_CHAR { if captchaType == constants.CAPTCHA_TYPE_CHAR {
char := config.Get("charCaptcha").(map[string]any) char := config.Get("charCaptcha").(map[string]any)
driverCaptcha := &base64Captcha.DriverString{ driverCaptcha := &base64Captcha.DriverString{
//Height png height in pixel. //Height png height in pixel.
@@ -121,8 +119,8 @@ func (s *CaptchaController) Image(c *gin.Context) {
} else { } else {
data["uuid"] = id data["uuid"] = id
data["img"] = item.EncodeB64string() data["img"] = item.EncodeB64string()
expiration := captcha.EXPIRATION * time.Second expiration := constants.CAPTCHA_EXPIRATION * time.Second
verifyKey = cachekey.CAPTCHA_CODE_KEY + id verifyKey = constants.CACHE_CAPTCHA_CODE + ":" + id
redis.SetByExpire("", verifyKey, answer, expiration) redis.SetByExpire("", verifyKey, answer, expiration)
} }
} }
@@ -131,8 +129,8 @@ func (s *CaptchaController) Image(c *gin.Context) {
if config.Env() == "local" { if config.Env() == "local" {
text, _ := redis.Get("", verifyKey) text, _ := redis.Get("", verifyKey)
data["text"] = text data["text"] = text
c.JSON(200, result.Ok(data)) c.JSON(200, resp.Ok(data))
return return
} }
c.JSON(200, result.Ok(data)) c.JSON(200, resp.Ok(data))
} }

View File

@@ -1,37 +1,92 @@
package controller package controller
import ( import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
commonService "be.ems/src/modules/common/service" commonService "be.ems/src/modules/common/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 CommontController 结构体 // 实例化控制层 CommonController 结构体
var NewCommont = &CommontController{ var NewCommon = &CommonController{
commontService: commonService.NewCommont, commontService: commonService.NewCommont,
} }
// 通用请求 // 通用请求
// //
// PATH / // PATH /
type CommontController struct { type CommonController struct {
commontService *commonService.Commont // 通用请求服务 commontService *commonService.Commont // 通用请求服务
} }
// 哈希加密 // Hash 哈希编码
// //
// POST /hash // POST /hash
func (s *CommontController) Hash(c *gin.Context) { func (s CommonController) Hash(c *gin.Context) {
c.String(200, "commont Hash") var body struct {
Type string `json:"type" binding:"required,oneof=sha1 sha256 sha512 md5"`
Str string `json:"str" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(200, gin.H{
"code": 400,
"msg": "参数错误",
})
return
}
var h hash.Hash
var err error
switch body.Type {
case "sha1":
h = sha1.New()
case "sha256":
h = sha256.New()
case "sha512":
h = sha512.New()
case "md5":
h = md5.New()
default:
c.JSON(200, gin.H{
"code": 400,
"msg": fmt.Sprintf("不支持的哈希算法: %s", body.Type),
})
return
}
// 写入需要哈希的数据
if _, err = h.Write([]byte(body.Str)); err != nil {
c.JSON(500, gin.H{
"code": 500,
"msg": "哈希写入错误",
})
return
}
// 计算哈希值的16进制表示
hashed := h.Sum(nil)
text := hex.EncodeToString(hashed)
c.JSON(200, gin.H{
"code": 200,
"msg": "success",
"data": text,
})
} }
// 多语言处理 // 多语言处理
// //
// GET /i18n // GET /i18n
func (s *CommontController) I18n(c *gin.Context) { func (s *CommonController) I18n(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
i18nLang := i18n.TKey(language, "i18n") i18nLang := i18n.TKey(language, "i18n")
hello := i18n.TKey(language, "hello") hello := i18n.TKey(language, "hello")
@@ -57,11 +112,11 @@ func (s *CommontController) I18n(c *gin.Context) {
// @Summary Configuration information for the system // @Summary Configuration information for the system
// @Description Configuration information for the system // @Description Configuration information for the system
// @Router /sys-conf [get] // @Router /sys-conf [get]
func (s *CommontController) SysConfig(c *gin.Context) { func (s CommonController) SysConfig(c *gin.Context) {
data := s.commontService.SystemConfigInfo() data := s.commontService.SystemConfigInfo()
// 闭包函数处理多语言 // 闭包函数处理多语言
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
converI18n := func(language string, arr *map[string]string) { converI18n := func(language string, arr *map[string]string) {
for k, v := range *arr { for k, v := range *arr {
(*arr)[k] = i18n.TKey(language, v) (*arr)[k] = i18n.TKey(language, v)
@@ -69,5 +124,5 @@ func (s *CommontController) SysConfig(c *gin.Context) {
} }
converI18n(language, &data) converI18n(language, &data)
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -8,14 +8,13 @@ import (
"strings" "strings"
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/constants/uploadsubpath" "be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/vo/result"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 FileController 结构体 // 实例化控制层 FileController 结构体
@@ -30,16 +29,16 @@ type FileController struct{}
// //
// GET /download/:filePath // GET /download/:filePath
func (s *FileController) Download(c *gin.Context) { func (s *FileController) Download(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
filePath := c.Param("filePath") filePath := c.Param("filePath")
if len(filePath) < 8 { if len(filePath) < 8 {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// base64解析出地址 // base64解析出地址
decodedBytes, err := base64.StdEncoding.DecodeString(filePath) decodedBytes, err := base64.StdEncoding.DecodeString(filePath)
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, err.Error())) c.JSON(400, resp.CodeMsg(400, err.Error()))
return return
} }
routerPath := string(decodedBytes) routerPath := string(decodedBytes)
@@ -48,7 +47,7 @@ func (s *FileController) Download(c *gin.Context) {
headerRange := c.GetHeader("Range") headerRange := c.GetHeader("Range")
resultMap, err := file.ReadUploadFileStream(routerPath, headerRange) resultMap, err := file.ReadUploadFileStream(routerPath, headerRange)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -83,29 +82,29 @@ func (s *FileController) Download(c *gin.Context) {
// @Description Upload a file, interface param use <fileName> // @Description Upload a file, interface param use <fileName>
// @Router /file/upload [post] // @Router /file/upload [post]
func (s *FileController) Upload(c *gin.Context) { func (s *FileController) Upload(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 上传的文件 // 上传的文件
formFile, err := c.FormFile("file") formFile, err := c.FormFile("file")
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 子路径 // 子路径
subPath := c.PostForm("subPath") subPath := c.PostForm("subPath")
if _, ok := uploadsubpath.UploadSubpath[subPath]; !ok { if _, ok := constants.UPLOAD_SUB_PATH[subPath]; !ok {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 上传文件转存 // 上传文件转存
upFilePath, err := file.TransferUploadFile(formFile, subPath, nil) upFilePath, err := file.TransferUploadFile(formFile, subPath, nil)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
newFileName := upFilePath[strings.LastIndex(upFilePath, "/")+1:] newFileName := upFilePath[strings.LastIndex(upFilePath, "/")+1:]
c.JSON(200, result.OkData(map[string]string{ c.JSON(200, resp.OkData(map[string]string{
"url": "//" + c.Request.Host + upFilePath, "url": "//" + c.Request.Host + upFilePath,
"fileName": upFilePath, "fileName": upFilePath,
"newFileName": newFileName, "newFileName": newFileName,
@@ -127,7 +126,7 @@ func (s *FileController) Upload(c *gin.Context) {
// @Description Slice file checking // @Description Slice file checking
// @Router /file/chunkCheck [post] // @Router /file/chunkCheck [post]
func (s *FileController) ChunkCheck(c *gin.Context) { func (s *FileController) ChunkCheck(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
// 唯一标识 // 唯一标识
Identifier string `json:"identifier" binding:"required"` Identifier string `json:"identifier" binding:"required"`
@@ -136,17 +135,17 @@ func (s *FileController) ChunkCheck(c *gin.Context) {
} }
err := c.ShouldBindJSON(&body) err := c.ShouldBindJSON(&body)
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 读取标识目录 // 读取标识目录
chunks, err := file.ChunkCheckFile(body.Identifier, body.FileName) chunks, err := file.ChunkCheckFile(body.Identifier, body.FileName)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(chunks)) c.JSON(200, resp.OkData(chunks))
} }
// 切片文件合并 // 切片文件合并
@@ -163,7 +162,7 @@ func (s *FileController) ChunkCheck(c *gin.Context) {
// @Description Slice file merge // @Description Slice file merge
// @Router /file/chunkMerge [post] // @Router /file/chunkMerge [post]
func (s *FileController) ChunkMerge(c *gin.Context) { func (s *FileController) ChunkMerge(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
// 唯一标识 // 唯一标识
Identifier string `json:"identifier" binding:"required"` Identifier string `json:"identifier" binding:"required"`
@@ -174,23 +173,23 @@ func (s *FileController) ChunkMerge(c *gin.Context) {
} }
err := c.ShouldBindJSON(&body) err := c.ShouldBindJSON(&body)
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
if _, ok := uploadsubpath.UploadSubpath[body.SubPath]; !ok { if _, ok := constants.UPLOAD_SUB_PATH[body.SubPath]; !ok {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 切片文件合并 // 切片文件合并
mergeFilePath, err := file.ChunkMergeFile(body.Identifier, body.FileName, body.SubPath) mergeFilePath, err := file.ChunkMergeFile(body.Identifier, body.FileName, body.SubPath)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
newFileName := mergeFilePath[strings.LastIndex(mergeFilePath, "/")+1:] newFileName := mergeFilePath[strings.LastIndex(mergeFilePath, "/")+1:]
c.JSON(200, result.OkData(map[string]string{ c.JSON(200, resp.OkData(map[string]string{
"url": "//" + c.Request.Host + mergeFilePath, "url": "//" + c.Request.Host + mergeFilePath,
"fileName": mergeFilePath, "fileName": mergeFilePath,
"newFileName": newFileName, "newFileName": newFileName,
@@ -214,7 +213,7 @@ func (s *FileController) ChunkMerge(c *gin.Context) {
// @Description Sliced file upload // @Description Sliced file upload
// @Router /file/chunkUpload [post] // @Router /file/chunkUpload [post]
func (s *FileController) ChunkUpload(c *gin.Context) { func (s *FileController) ChunkUpload(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 切片编号 // 切片编号
index := c.PostForm("index") index := c.PostForm("index")
// 切片唯一标识 // 切片唯一标识
@@ -222,31 +221,31 @@ func (s *FileController) ChunkUpload(c *gin.Context) {
// 上传的文件 // 上传的文件
formFile, err := c.FormFile("file") formFile, err := c.FormFile("file")
if index == "" || identifier == "" || err != nil { if index == "" || identifier == "" || err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 上传文件转存 // 上传文件转存
chunkFilePath, err := file.TransferChunkUploadFile(formFile, index, identifier) chunkFilePath, err := file.TransferChunkUploadFile(formFile, index, identifier)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(206, result.OkData(chunkFilePath)) c.JSON(206, resp.OkData(chunkFilePath))
} }
// 转存指定对应文件到静态目录 // 转存指定对应文件到静态目录
// //
// POST /transferStaticFile // POST /transferStaticFile
func (s *CommontController) TransferStaticFile(c *gin.Context) { func (s *FileController) TransferStaticFile(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var body struct { var body struct {
UploadPath string `json:"uploadPath" binding:"required"` UploadPath string `json:"uploadPath" binding:"required"`
StaticPath string `json:"staticPath" binding:"required"` StaticPath string `json:"staticPath" binding:"required"`
Language string `json:"language" binding:"required"` Language string `json:"language" binding:"required"`
} }
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil { if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
@@ -257,7 +256,7 @@ func (s *CommontController) TransferStaticFile(c *gin.Context) {
static := config.Get("staticFile.default").(map[string]any) static := config.Get("staticFile.default").(map[string]any)
dir, err := filepath.Abs(static["dir"].(string)) dir, err := filepath.Abs(static["dir"].(string))
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, err.Error())) c.JSON(400, resp.CodeMsg(400, err.Error()))
return return
} }
@@ -267,10 +266,10 @@ func (s *CommontController) TransferStaticFile(c *gin.Context) {
err = file.CopyUploadFile(body.UploadPath, newFile) err = file.CopyUploadFile(body.UploadPath, newFile)
if err != nil { if err != nil {
c.JSON(400, result.CodeMsg(400, err.Error())) c.JSON(400, resp.CodeMsg(400, err.Error()))
return return
} }
urlPath := strings.Replace(newFile, dir, static["prefix"].(string), 1) urlPath := strings.Replace(newFile, dir, static["prefix"].(string), 1)
c.JSON(200, result.OkData(filepath.ToSlash(urlPath))) c.JSON(200, resp.OkData(filepath.ToSlash(urlPath)))
} }

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
libGlobal "be.ems/lib/global" libGlobal "be.ems/lib/global"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -32,6 +32,6 @@ func (s *IndexController) Handler(c *gin.Context) {
name := "OMC" name := "OMC"
version := libGlobal.Version version := libGlobal.Version
// str := "欢迎使用%s核心网管理平台当前版本%s请通过前台地址访问。" // str := "欢迎使用%s核心网管理平台当前版本%s请通过前台地址访问。"
str := "Welcome to the %s Core Network Management Platform, current version: %s, please access via the frontend address." str := "%s Core Network Management, current version: %s"
c.JSON(200, result.OkMsg(fmt.Sprintf(str, name, version))) c.JSON(200, resp.OkMsg(fmt.Sprintf(str, name, version)))
} }

View File

@@ -1,13 +1,15 @@
package controller package controller
import ( import (
commonConstants "be.ems/src/framework/constants/common" "fmt"
"be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/regular" "be.ems/src/framework/utils/regular"
"be.ems/src/framework/vo/result" "be.ems/src/modules/common/model"
commonModel "be.ems/src/modules/common/model" "be.ems/src/modules/common/service"
commonService "be.ems/src/modules/common/service"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -15,77 +17,77 @@ import (
// 实例化控制层 RegisterController 结构体 // 实例化控制层 RegisterController 结构体
var NewRegister = &RegisterController{ var NewRegister = &RegisterController{
registerService: commonService.NewRegisterImpl, registerService: service.NewRegister,
sysLogLoginService: systemService.NewSysLogLoginImpl, sysLogLoginService: systemService.NewSysLogLogin,
} }
// 账号注册操作处理 // 账号注册操作处理
// //
// PATH / // PATH /
type RegisterController struct { type RegisterController struct {
// 账号注册操作服务 registerService *service.Register // 账号注册操作服务
registerService commonService.IRegister sysLogLoginService *systemService.SysLogLogin // 系统登录访问服务
// 系统登录访问
sysLogLoginService systemService.ISysLogLogin
} }
// 账号注册 // 账号注册
// //
// GET /register // GET /register
func (s *RegisterController) Register(c *gin.Context) { func (s *RegisterController) Register(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var registerBody commonModel.RegisterBody var body model.RegisterBody
if err := c.ShouldBindJSON(&registerBody); err != nil { if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 判断必传参数 // 判断必传参数
if !regular.ValidUsername(registerBody.Username) { if !regular.ValidUsername(body.Username) {
// 账号不能以数字开头可包含大写小写字母数字且不少于5位 // 账号不能以数字开头可包含大写小写字母数字且不少于5位
c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errUsername"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "register.errUsername")))
return return
} }
if !regular.ValidPassword(registerBody.Password) { if !regular.ValidPassword(body.Password) {
// 登录密码至少包含大小写字母、数字、特殊符号且不少于6位 // 登录密码至少包含大小写字母、数字、特殊符号且不少于6位
c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errPasswd"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "register.errPasswd")))
return return
} }
if registerBody.Password != registerBody.ConfirmPassword { if body.Password != body.ConfirmPassword {
// 用户确认输入密码不一致 // 用户确认输入密码不一致
c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errPasswdNotEq"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "register.errPasswdNotEq")))
return return
} }
// 当前请求信息 // 当前请求信息
ipaddr, location := ctx.IPAddrLocation(c) ipaddr, location := reqctx.IPAddrLocation(c)
os, browser := ctx.UaOsBrowser(c) os, browser := reqctx.UaOsBrowser(c)
// 校验验证码 // 校验验证码
err := s.registerService.ValidateCaptcha( err := s.registerService.ValidateCaptcha(
registerBody.Code, body.Code,
registerBody.UUID, body.UUID,
) )
// 根据错误信息,创建系统访问记录 // 根据错误信息,创建系统访问记录
if err != nil { if err != nil {
s.sysLogLoginService.CreateSysLogLogin( msg := err.Error() + " code: " + body.Code
registerBody.Username, commonConstants.STATUS_NO, err.Error(), s.sysLogLoginService.Insert(
ipaddr, location, os, browser, body.Username, constants.STATUS_NO, msg,
[4]string{ipaddr, location, os, browser},
) )
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
userID, err := s.registerService.ByUserName(registerBody.Username, registerBody.Password, registerBody.UserType) userId, err := s.registerService.ByUserName(body.Username, body.Password)
if err == nil { if err == nil {
msg := i18n.TTemplate(language, "register.successMsg", map[string]any{"name": registerBody.Username, "id": userID}) msg := i18n.TTemplate(language, "register.successMsg", map[string]any{"name": body.Username, "id": userId})
s.sysLogLoginService.CreateSysLogLogin( s.sysLogLoginService.Insert(
registerBody.Username, commonConstants.STATUS_YES, msg, body.Username, constants.STATUS_YES, msg,
ipaddr, location, os, browser, [4]string{ipaddr, location, os, browser},
) )
// 注册成功 // 注册成功
c.JSON(200, result.OkMsg(i18n.TKey(language, "register.success"))) c.JSON(200, resp.OkMsg(i18n.TKey(language, "register.success")))
return return
} }
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
} }

View File

@@ -5,41 +5,35 @@ import (
"time" "time"
"be.ems/src/framework/config" "be.ems/src/framework/config"
adminConstants "be.ems/src/framework/constants/admin" "be.ems/src/framework/constants"
"be.ems/src/framework/constants/cachekey" "be.ems/src/framework/database/redis"
"be.ems/src/framework/constants/common" "be.ems/src/framework/token"
"be.ems/src/framework/redis"
"be.ems/src/framework/utils/crypto" "be.ems/src/framework/utils/crypto"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo" systemModelVO "be.ems/src/modules/system/model/vo"
"be.ems/src/modules/system/model"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
) )
// 实例化服务层 Account 结构体 // 实例化服务层 Account 结构体
var NewAccount = &Account{ var NewAccount = &Account{
sysUserService: systemService.NewSysUserImpl, sysUserService: systemService.NewSysUser,
sysConfigService: systemService.NewSysConfigImpl, sysConfigService: systemService.NewSysConfig,
sysRoleService: systemService.NewSysRoleImpl, sysRoleService: systemService.NewSysRole,
sysMenuService: systemService.NewSysMenuImpl, sysMenuService: systemService.NewSysMenu,
} }
// 账号身份操作服务 服务层处理 // 账号身份操作服务 服务层处理
type Account struct { type Account struct {
// 用户信息服务 sysUserService *systemService.SysUser // 用户信息服务
sysUserService systemService.ISysUser sysConfigService *systemService.SysConfig // 参数配置服务
// 参数配置服务 sysRoleService *systemService.SysRole // 角色服务
sysConfigService systemService.ISysConfig sysMenuService *systemService.SysMenu // 菜单服务
// 角色服务
sysRoleService systemService.ISysRole
// 菜单服务
sysMenuService systemService.ISysMenu
} }
// ValidateCaptcha 校验验证码 // ValidateCaptcha 校验验证码
func (s *Account) ValidateCaptcha(code, uuid string) error { func (s *Account) ValidateCaptcha(code, uuid string) error {
// 验证码检查,从数据库配置获取验证码开关 true开启false关闭 // 验证码检查,从数据库配置获取验证码开关 true开启false关闭
captchaEnabledStr := s.sysConfigService.SelectConfigValueByKey("sys.account.captchaEnabled") captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
if !parse.Boolean(captchaEnabledStr) { if !parse.Boolean(captchaEnabledStr) {
return nil return nil
} }
@@ -47,13 +41,13 @@ func (s *Account) ValidateCaptcha(code, uuid string) error {
// 验证码信息错误 // 验证码信息错误
return fmt.Errorf("captcha.err") return fmt.Errorf("captcha.err")
} }
verifyKey := cachekey.CAPTCHA_CODE_KEY + uuid verifyKey := constants.CACHE_CAPTCHA_CODE + ":" + uuid
captcha, _ := redis.Get("", verifyKey) captcha, _ := redis.Get("", verifyKey)
if captcha == "" { if captcha == "" {
// 验证码已失效 // 验证码已失效
return fmt.Errorf("captcha.errValid") return fmt.Errorf("captcha.errValid")
} }
redis.Del("", verifyKey) _ = redis.Del("", verifyKey)
if captcha != code { if captcha != code {
// 验证码错误 // 验证码错误
return fmt.Errorf("captcha.err") return fmt.Errorf("captcha.err")
@@ -61,133 +55,122 @@ func (s *Account) ValidateCaptcha(code, uuid string) error {
return nil return nil
} }
// LoginByUsername 登录创建用户信息 // ByUsername 登录创建用户信息
func (s *Account) LoginByUsername(username, password string) (vo.LoginUser, error) { func (s Account) ByUsername(username, password string) (token.TokenInfo, error) {
loginUser := vo.LoginUser{} tokenInfo := token.TokenInfo{}
// 检查密码重试次数 // 检查密码重试次数
retrykey, retryCount, lockTime, err := s.passwordRetryCount(username) retryKey, retryCount, lockTime, err := s.passwordRetryCount(username)
if err != nil { if err != nil {
return loginUser, err return tokenInfo, err
} }
// 查询用户登录账号 // 查询用户登录账号
sysUser := s.sysUserService.SelectUserByUserName(username) sysUser := s.sysUserService.FindByUserName(username)
if sysUser.UserName != username { if sysUser.UserName != username {
return loginUser, fmt.Errorf("login.errNameOrPasswd") return tokenInfo, fmt.Errorf("login.errNameOrPasswd")
} }
if sysUser.DelFlag == common.STATUS_YES { if sysUser.DelFlag == constants.STATUS_YES {
// 对不起,您的账号已被删除 return tokenInfo, fmt.Errorf("login.errDelFlag")
return loginUser, fmt.Errorf("login.errDelFlag")
} }
if sysUser.Status == common.STATUS_NO { if sysUser.StatusFlag == constants.STATUS_NO {
return loginUser, fmt.Errorf("login.errStatus") return tokenInfo, fmt.Errorf("login.errStatus")
} }
// 检验用户密码 // 检验用户密码
compareBool := crypto.BcryptCompare(password, sysUser.Password) compareBool := crypto.BcryptCompare(password, sysUser.Password)
if !compareBool { if compareBool {
redis.SetByExpire("", retrykey, retryCount+1, lockTime) s.CleanLoginRecordCache(sysUser.UserName) // 清除错误记录次数
// 用户不存在或密码错误
return loginUser, fmt.Errorf("login.errNameOrPasswd")
} else { } else {
// 清除错误记录次数 _ = redis.SetByExpire("", retryKey, retryCount+1, lockTime)
s.ClearLoginRecordCache(username) return tokenInfo, fmt.Errorf("login.errNameOrPasswd")
} }
// 登录用户信息 // 登录用户信息
loginUser.UserID = sysUser.UserID tokenInfo.UserId = sysUser.UserId
loginUser.DeptID = sysUser.DeptID tokenInfo.DeptId = sysUser.DeptId
loginUser.User = sysUser tokenInfo.User = sysUser
// 用户权限组标识 // 用户权限组标识
isAdmin := config.IsAdmin(sysUser.UserID) if config.IsSystemUser(sysUser.UserId) {
if isAdmin { tokenInfo.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
loginUser.Permissions = []string{adminConstants.PERMISSION}
} else { } else {
perms := s.sysMenuService.SelectMenuPermsByUserId(sysUser.UserID) perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
loginUser.Permissions = parse.RemoveDuplicates(perms) tokenInfo.Permissions = parse.RemoveDuplicates(perms)
} }
return loginUser, nil return tokenInfo, nil
} }
// UpdateLoginDateAndIP 更新登录时间和IP // UpdateLoginDateAndIP 更新登录时间和IP
func (s *Account) UpdateLoginDateAndIP(loginUser *vo.LoginUser) bool { func (s Account) UpdateLoginDateAndIP(tokenInfo token.TokenInfo) bool {
sysUser := loginUser.User user := s.sysUserService.FindById(tokenInfo.UserId)
userInfo := model.SysUser{ user.Password = "" // 密码不更新
UserID: sysUser.UserID, user.LoginIp = tokenInfo.LoginIp
LoginIP: sysUser.LoginIP, user.LoginTime = tokenInfo.LoginTime
LoginDate: sysUser.LoginDate, return s.sysUserService.Update(user) > 0
UpdateBy: sysUser.UserName,
Sex: sysUser.Sex,
PhoneNumber: sysUser.PhoneNumber,
Email: sysUser.Email,
Remark: sysUser.Remark,
}
rows := s.sysUserService.UpdateUser(userInfo)
return rows > 0
} }
// ClearLoginRecordCache 清除错误记录次数 // CleanLoginRecordCache 清除错误记录次数
func (s *Account) ClearLoginRecordCache(username string) bool { func (s Account) CleanLoginRecordCache(userName string) bool {
cacheKey := cachekey.PWD_ERR_CNT_KEY + username cacheKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
hasKey, _ := redis.Has("", cacheKey) hasKey, err := redis.Has("", cacheKey)
if hasKey { if hasKey > 0 && err == nil {
delOk, _ := redis.Del("", cacheKey) return redis.Del("", cacheKey) == nil
return delOk
} }
return false return false
} }
// passwordRetryCount 密码重试次数 // passwordRetryCount 密码重试次数
func (s *Account) passwordRetryCount(username string) (string, int64, time.Duration, error) { func (s Account) passwordRetryCount(userName string) (string, int64, time.Duration, error) {
// 从数据库配置获取登录次数和错误锁定时间 // 从数据库配置获取登录次数和错误锁定时间
maxRetryCountStr := s.sysConfigService.SelectConfigValueByKey("sys.user.maxRetryCount") maxRetryCountStr := s.sysConfigService.FindValueByKey("sys.user.maxRetryCount")
lockTimeStr := s.sysConfigService.SelectConfigValueByKey("sys.user.lockTime") lockTimeStr := s.sysConfigService.FindValueByKey("sys.user.lockTime")
// 验证登录次数和错误锁定时间 // 验证登录次数和错误锁定时间
maxRetryCount := parse.Number(maxRetryCountStr) maxRetryCount := parse.Number(maxRetryCountStr)
lockTime := parse.Number(lockTimeStr) lockTime := parse.Number(lockTimeStr)
// 验证登录次数和错误锁定时间
// maxRetryCount := config.Get("user.password.maxRetryCount").(int)
// lockTime := config.Get("user.password.lockTime").(int)
// 验证缓存记录次数 // 验证缓存记录次数
retrykey := cachekey.PWD_ERR_CNT_KEY + username retryKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
retryCount, err := redis.Get("", retrykey) retryCount, err := redis.Get("", retryKey)
if retryCount == "" || err != nil { if retryCount == "" || err != nil {
retryCount = "0" retryCount = "0"
} }
// 是否超过错误值 // 是否超过错误值
retryCountInt64 := parse.Number(retryCount) retryCountInt64 := parse.Number(retryCount)
if retryCountInt64 >= maxRetryCount { if retryCountInt64 >= int64(maxRetryCount) {
// 密码输入错误多次,帐户已被锁定 // msg := fmt.Sprintf("密码输入错误 %d 次,帐户锁定 %d 分钟", maxRetryCount, lockTime)
errorMsg := fmt.Errorf("login.errRetryPasswd") msg := fmt.Errorf("login.errRetryPasswd") // 密码输入错误多次,帐户已被锁定
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, errorMsg return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, fmt.Errorf("%s", msg)
} }
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil
} }
// RoleAndMenuPerms 角色和菜单数据权限 // RoleAndMenuPerms 角色和菜单数据权限
func (s *Account) RoleAndMenuPerms(userId string, isAdmin bool) ([]string, []string) { func (s Account) RoleAndMenuPerms(userId int64, isSystemUser bool) ([]string, []string) {
if isAdmin { if isSystemUser {
return []string{adminConstants.ROLE_KEY}, []string{adminConstants.PERMISSION} return []string{constants.SYS_ROLE_SYSTEM_KEY}, []string{constants.SYS_PERMISSION_SYSTEM}
} else {
// 角色key
roleGroup := []string{}
roles := s.sysRoleService.SelectRoleListByUserId(userId)
for _, role := range roles {
roleGroup = append(roleGroup, role.RoleKey)
}
// 菜单权限key
perms := s.sysMenuService.SelectMenuPermsByUserId(userId)
return parse.RemoveDuplicates(roleGroup), parse.RemoveDuplicates(perms)
} }
// 角色key
var roleGroup []string
roles := s.sysRoleService.FindByUserId(userId)
for _, role := range roles {
roleGroup = append(roleGroup, role.RoleKey)
}
// 菜单权限key
perms := s.sysMenuService.FindPermsByUserId(userId)
return parse.RemoveDuplicates(roleGroup), parse.RemoveDuplicates(perms)
} }
// RouteMenus 前端路由所需要的菜单 // RouteMenus 前端路由所需要的菜单
func (s *Account) RouteMenus(userId string, isAdmin bool) []vo.Router { func (s Account) RouteMenus(userId int64, isSystemUser bool) []systemModelVO.Router {
var buildMenus []vo.Router var buildMenus []systemModelVO.Router
if isAdmin { if isSystemUser {
menus := s.sysMenuService.SelectMenuTreeByUserId("*") menus := s.sysMenuService.BuildTreeMenusByUserId(0)
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "") buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
} else { } else {
menus := s.sysMenuService.SelectMenuTreeByUserId(userId) menus := s.sysMenuService.BuildTreeMenusByUserId(userId)
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "") buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
} }
return buildMenus return buildMenus

View File

@@ -5,23 +5,21 @@ import (
"be.ems/lib/global" "be.ems/lib/global"
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/constants/common" "be.ems/src/framework/constants"
"be.ems/src/framework/utils/machine" "be.ems/src/framework/utils/machine"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
) )
// 实例化服务层 Commont 结构体 // 实例化服务层 Commont 结构体
var NewCommont = &Commont{ var NewCommont = &Commont{
sysUserService: systemService.NewSysUserImpl, sysUserService: systemService.NewSysUser,
sysConfigService: systemService.NewSysConfigImpl, sysConfigService: systemService.NewSysConfig,
} }
// 通用请求 服务层处理 // 通用请求 服务层处理
type Commont struct { type Commont struct {
// 用户信息服务 sysUserService *systemService.SysUser // 用户信息服务
sysUserService systemService.ISysUser sysConfigService *systemService.SysConfig // 参数配置服务
// 参数配置服务
sysConfigService systemService.ISysConfig
} }
// SystemConfigInfo 系统配置信息 // SystemConfigInfo 系统配置信息
@@ -33,13 +31,13 @@ func (s *Commont) SystemConfigInfo() map[string]string {
// 系统首次使用标记 // 系统首次使用标记
launchInfo := machine.LaunchInfo launchInfo := machine.LaunchInfo
if launchInfo != nil { if launchInfo != nil {
if v, ok := launchInfo[common.LAUNCH_BOOTLOADER]; ok { if v, ok := launchInfo[constants.LAUNCH_BOOTLOADER]; ok {
infoMap[common.LAUNCH_BOOTLOADER] = fmt.Sprint(v) infoMap[constants.LAUNCH_BOOTLOADER] = fmt.Sprint(v)
} else { } else {
infoMap[common.LAUNCH_BOOTLOADER] = "true" infoMap[constants.LAUNCH_BOOTLOADER] = "true"
} }
} else { } else {
infoMap[common.LAUNCH_BOOTLOADER] = "true" infoMap[constants.LAUNCH_BOOTLOADER] = "true"
} }
// 用户登录认证 // 用户登录认证
infoMap["loginAuth"] = fmt.Sprint(config.Get("user.loginAuth")) infoMap["loginAuth"] = fmt.Sprint(config.Get("user.loginAuth"))
@@ -48,36 +46,36 @@ func (s *Commont) SystemConfigInfo() map[string]string {
// 序列号 // 序列号
infoMap["serialNum"] = fmt.Sprint(config.Get("omc.sn")) infoMap["serialNum"] = fmt.Sprint(config.Get("omc.sn"))
// 获取LOGO类型 // 获取LOGO类型
logoType := s.sysConfigService.SelectConfigValueByKey("sys.logo.type") logoType := s.sysConfigService.FindValueByKey("sys.logo.type")
infoMap["logoType"] = logoType infoMap["logoType"] = logoType
// 获取LOGO文件 // 获取LOGO文件
filePathIcon := s.sysConfigService.SelectConfigValueByKey("sys.logo.filePathIcon") filePathIcon := s.sysConfigService.FindValueByKey("sys.logo.filePathIcon")
infoMap["filePathIcon"] = filePathIcon infoMap["filePathIcon"] = filePathIcon
filePathBrand := s.sysConfigService.SelectConfigValueByKey("sys.logo.filePathBrand") filePathBrand := s.sysConfigService.FindValueByKey("sys.logo.filePathBrand")
infoMap["filePathBrand"] = filePathBrand infoMap["filePathBrand"] = filePathBrand
// 获取系统名称 // 获取系统名称
title := s.sysConfigService.SelectConfigValueByKey("sys.title") title := s.sysConfigService.FindValueByKey("sys.title")
infoMap["title"] = title infoMap["title"] = title
// 获取版权声明 // 获取版权声明
copyright := s.sysConfigService.SelectConfigValueByKey("sys.copyright") copyright := s.sysConfigService.FindValueByKey("sys.copyright")
infoMap["copyright"] = copyright infoMap["copyright"] = copyright
// 获取是否开启用户注册功能 // 获取是否开启用户注册功能
registerUser := s.sysConfigService.SelectConfigValueByKey("sys.account.registerUser") registerUser := s.sysConfigService.FindValueByKey("sys.account.registerUser")
infoMap["registerUser"] = registerUser infoMap["registerUser"] = registerUser
// 获取登录界面背景 // 获取登录界面背景
loginBackground := s.sysConfigService.SelectConfigValueByKey("sys.loginBackground") loginBackground := s.sysConfigService.FindValueByKey("sys.loginBackground")
infoMap["loginBackground"] = loginBackground infoMap["loginBackground"] = loginBackground
// 系统设置-官网网址 // 系统设置-官网网址
officialUrl := s.sysConfigService.SelectConfigValueByKey("sys.officialUrl") officialUrl := s.sysConfigService.FindValueByKey("sys.officialUrl")
infoMap["officialUrl"] = officialUrl infoMap["officialUrl"] = officialUrl
// 系统设置-系统使用文档 // 系统设置-系统使用文档
helpDoc := s.sysConfigService.SelectConfigValueByKey("sys.helpDoc") helpDoc := s.sysConfigService.FindValueByKey("sys.helpDoc")
infoMap["helpDoc"] = helpDoc infoMap["helpDoc"] = helpDoc
// 国际化切换 // 国际化切换
i18nOpen := s.sysConfigService.SelectConfigValueByKey("sys.i18n.open") i18nOpen := s.sysConfigService.FindValueByKey("sys.i18n.open")
infoMap["i18nOpen"] = i18nOpen infoMap["i18nOpen"] = i18nOpen
// 国际化默认语言 // 国际化默认语言
i18nDefault := s.sysConfigService.SelectConfigValueByKey("sys.i18n.default") i18nDefault := s.sysConfigService.FindValueByKey("sys.i18n.default")
infoMap["i18nDefault"] = i18nDefault infoMap["i18nDefault"] = i18nDefault
return infoMap return infoMap
} }

View File

@@ -1,10 +1,92 @@
package service package service
// 账号注册操作处理 服务层接口 import (
type IRegister interface { "fmt"
// ValidateCaptcha 校验验证码
ValidateCaptcha(code, uuid string) error
// ByUserName 账号注册 "be.ems/src/framework/constants"
ByUserName(username, password, userType string) (string, error) "be.ems/src/framework/database/redis"
"be.ems/src/framework/utils/parse"
systemModel "be.ems/src/modules/system/model"
systemService "be.ems/src/modules/system/service"
)
// 实例化服务层 Register 结构体
var NewRegister = &Register{
sysUserService: systemService.NewSysUser,
sysConfigService: systemService.NewSysConfig,
}
// 账号注册操作处理 服务层处理
type Register struct {
sysUserService *systemService.SysUser // 用户信息服务
sysConfigService *systemService.SysConfig // 参数配置服务
}
// ValidateCaptcha 校验验证码
func (s Register) ValidateCaptcha(code, uuid string) error {
// 验证码检查,从数据库配置获取验证码开关 true开启false关闭
captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
if !parse.Boolean(captchaEnabledStr) {
return nil
}
if code == "" || uuid == "" {
return fmt.Errorf("verification code information error")
}
verifyKey := constants.CACHE_CAPTCHA_CODE + ":" + uuid
captcha, err := redis.Get("", verifyKey)
if err != nil {
return fmt.Errorf("the verification code has expired")
}
redis.Del("", verifyKey)
if captcha != code {
return fmt.Errorf("verification code error")
}
return nil
}
// ByUserName 账号注册
func (s Register) ByUserName(username, password string) (int64, error) {
// 是否开启用户注册功能 true开启false关闭
registerUserStr := s.sysConfigService.FindValueByKey("sys.account.registerUser")
captchaEnabled := parse.Boolean(registerUserStr)
if !captchaEnabled {
return 0, fmt.Errorf("failed to register user [%s]. Sorry, the system has closed the external user registration channel", username)
}
// 检查用户登录账号是否唯一
uniqueUserName := s.sysUserService.CheckUniqueByUserName(username, 0)
if !uniqueUserName {
return 0, fmt.Errorf("failed to register user [%s], registered account already exists", username)
}
sysUser := systemModel.SysUser{
UserName: username,
NickName: username, // 昵称使用名称账号
Password: password, // 原始密码
Sex: "0", // 性别未选择
StatusFlag: constants.STATUS_YES, // 账号状态激活
DeptId: 100, // 归属部门为根节点
CreateBy: "register", // 创建来源
}
// 新增用户的角色管理
sysUser.RoleIds = s.registerRoleInit()
// 新增用户的岗位管理
sysUser.PostIds = s.registerPostInit()
insertId := s.sysUserService.Insert(sysUser)
if insertId > 0 {
return insertId, nil
}
return 0, fmt.Errorf("failed to register user [%s]. Please contact the system administrator", username)
}
// registerRoleInit 注册初始角色
func (s Register) registerRoleInit() []int64 {
return []int64{}
}
// registerPostInit 注册初始岗位
func (s Register) registerPostInit() []int64 {
return []int64{}
} }

View File

@@ -1,106 +0,0 @@
package service
import (
"fmt"
"be.ems/src/framework/constants/cachekey"
"be.ems/src/framework/constants/common"
"be.ems/src/framework/redis"
"be.ems/src/framework/utils/parse"
systemModel "be.ems/src/modules/system/model"
systemService "be.ems/src/modules/system/service"
)
// 实例化服务层 RegisterImpl 结构体
var NewRegisterImpl = &RegisterImpl{
sysUserService: systemService.NewSysUserImpl,
sysConfigService: systemService.NewSysConfigImpl,
sysRoleService: systemService.NewSysRoleImpl,
}
// 账号注册操作处理 服务层处理
type RegisterImpl struct {
// 用户信息服务
sysUserService systemService.ISysUser
// 参数配置服务
sysConfigService systemService.ISysConfig
// 角色服务
sysRoleService systemService.ISysRole
}
// ValidateCaptcha 校验验证码
func (s *RegisterImpl) ValidateCaptcha(code, uuid string) error {
// 验证码检查,从数据库配置获取验证码开关 true开启false关闭
captchaEnabledStr := s.sysConfigService.SelectConfigValueByKey("sys.account.captchaEnabled")
if !parse.Boolean(captchaEnabledStr) {
return nil
}
if code == "" || uuid == "" {
return fmt.Errorf("verification code information error")
}
verifyKey := cachekey.CAPTCHA_CODE_KEY + uuid
captcha, err := redis.Get("", verifyKey)
if err != nil {
return fmt.Errorf("the verification code has expired")
}
redis.Del("", verifyKey)
if captcha != code {
return fmt.Errorf("verification code error")
}
return nil
}
// ByUserName 账号注册
func (s *RegisterImpl) ByUserName(username, password, userType string) (string, error) {
// 是否开启用户注册功能 true开启false关闭
registerUserStr := s.sysConfigService.SelectConfigValueByKey("sys.account.registerUser")
captchaEnabled := parse.Boolean(registerUserStr)
if !captchaEnabled {
return "", fmt.Errorf("failed to register user [%s]. Sorry, the system has closed the external user registration channel", username)
}
// 检查用户登录账号是否唯一
uniqueUserName := s.sysUserService.CheckUniqueUserName(username, "")
if !uniqueUserName {
return "", fmt.Errorf("failed to register user [%s], registered account already exists", username)
}
sysUser := systemModel.SysUser{
UserName: username,
NickName: username, // 昵称使用名称账号
Password: password, // 原始密码
Status: common.STATUS_YES, // 账号状态激活
DeptID: "100", // 归属部门为根节点
CreateBy: "register", // 创建来源
}
// 标记用户类型
if userType == "" {
sysUser.UserType = "sys"
}
// 新增用户的角色管理
sysUser.RoleIDs = s.registerRoleInit(userType)
// 新增用户的岗位管理
sysUser.PostIDs = s.registerPostInit(userType)
insertId := s.sysUserService.InsertUser(sysUser)
if insertId != "" {
return insertId, nil
}
return "", fmt.Errorf("failed to register user [%s]. Please contact the system administrator", username)
}
// registerRoleInit 注册初始角色
func (s *RegisterImpl) registerRoleInit(userType string) []string {
if userType == "sys" {
return []string{}
}
return []string{}
}
// registerPostInit 注册初始岗位
func (s *RegisterImpl) registerPostInit(userType string) []string {
if userType == "sys" {
return []string{}
}
return []string{}
}

View File

@@ -46,7 +46,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
// return nil, err // return nil, err
// } // }
log.Infof("Repeat %v Job ID %s", options.Repeat, sysJob.JobID) log.Infof("Repeat %v Job ID %d", options.Repeat, sysJob.JobId)
var nes []dborm.NeInfo var nes []dborm.NeInfo
_, err := dborm.XormGetAllNeInfo(&nes) _, err := dborm.XormGetAllNeInfo(&nes)

View File

@@ -39,7 +39,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
if err == nil { if err == nil {
duration = params.Duration duration = params.Duration
} }
log.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) log.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// // 实现任务处理逻辑 // // 实现任务处理逻辑
// i := 0 // i := 0

View File

@@ -44,7 +44,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
} }
//duration = params.Duration //duration = params.Duration
log.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) log.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// // 实现任务处理逻辑 // // 实现任务处理逻辑
// i := 0 // i := 0

View File

@@ -15,10 +15,9 @@ import (
"be.ems/src/framework/config" "be.ems/src/framework/config"
"be.ems/src/framework/cron" "be.ems/src/framework/cron"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/crypto" "be.ems/src/framework/utils/crypto"
"be.ems/src/framework/utils/ssh"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/jlaffaye/ftp"
) )
var NewProcessor = &BarProcessor{ var NewProcessor = &BarProcessor{
@@ -177,11 +176,11 @@ func (s BarProcessor) putFTP(filePath, fileName string) {
Username string `json:"username" binding:"required"` Username string `json:"username" binding:"required"`
ToIp string `json:"toIp" binding:"required"` ToIp string `json:"toIp" binding:"required"`
ToPort int64 `json:"toPort" binding:"required"` ToPort int64 `json:"toPort" binding:"required"`
Protocol string `json:"protocol" binding:"required,oneof=ssh ftp"` Enable bool `json:"enable"`
Dir string `json:"dir" binding:"required"` Dir string `json:"dir" binding:"required"`
} }
cfg := systemService.NewSysConfigImpl.SelectConfigByKey("sys.exportTable") cfg := systemService.NewSysConfig.FindByKey("sys.exportTable")
if cfg.ConfigID != "" { if cfg.ConfigId > 0 {
// 解密body // 解密body
appKey := config.Get("aes.appKey").(string) appKey := config.Get("aes.appKey").(string)
bodyDe, err := crypto.AESDecryptBase64(cfg.ConfigValue, appKey) bodyDe, err := crypto.AESDecryptBase64(cfg.ConfigValue, appKey)
@@ -195,68 +194,37 @@ func (s BarProcessor) putFTP(filePath, fileName string) {
return return
} }
} }
if !cfgData.Enable {
return
}
localFilePath := filepath.Join(filePath, fileName) localFilePath := filepath.Join(filePath, fileName)
if cfgData.Protocol == "ssh" { connSSH := ssh.ConnSSH{
connSSH := ssh.ConnSSH{ User: cfgData.Username,
User: cfgData.Username, Password: cfgData.Password,
Password: cfgData.Password, Addr: cfgData.ToIp,
Addr: cfgData.ToIp, Port: cfgData.ToPort,
Port: cfgData.ToPort, AuthMode: "0",
AuthMode: "0",
}
sshClient, err := connSSH.NewClient()
if err != nil {
logger.Errorf("putFTP ssh error: %v", err)
return
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
logger.Errorf("putFTP sftp error: %v", err)
return
}
defer sftpClient.Close()
// 远程文件
remotePath := filepath.Join(cfgData.Dir, path.Base(filePath), fileName)
// 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, remotePath); err != nil {
logger.Errorf("putFTP uploading error: %v", err)
return
}
} }
sshClient, err := connSSH.NewClient()
if cfgData.Protocol == "ftp" { if err != nil {
// 连接到 FTP 服务器 logger.Errorf("putFTP ssh error: %v", err)
addr := fmt.Sprintf("%s:%d", cfgData.ToIp, cfgData.ToPort) return
ftpComm, err := ftp.Dial(addr, ftp.DialWithTimeout(15*time.Second)) }
if err != nil { defer sshClient.Close()
logger.Errorf("putFTP ftp error: %v", err) // 网元主机的SSH客户端进行文件传输
return sftpClient, err := sshClient.NewClientSFTP()
} if err != nil {
// 登录到 FTP 服务器 logger.Errorf("putFTP sftp error: %v", err)
err = ftpComm.Login(cfgData.Username, cfgData.Password) return
if err != nil { }
logger.Errorf("putFTP login error: %v", err) defer sftpClient.Close()
return // 远程文件
} remotePath := filepath.Join(cfgData.Dir, path.Base(filePath), fileName)
defer ftpComm.Quit() // 复制到远程
// 打开本地文件 if err = sftpClient.CopyFileLocalToRemote(localFilePath, remotePath); err != nil {
file, err := os.Open(localFilePath) logger.Errorf("putFTP uploading error: %v", err)
if err != nil { return
logger.Errorf("putFTP open error: %v", err)
return
}
defer file.Close()
// 远程文件
remotePath := filepath.Join(cfgData.Dir, path.Base(filePath), fileName)
// 上传文件到 FTP 服务器
err = ftpComm.Stor(remotePath, file)
if err != nil {
logger.Errorf("putFTP uploading error: %v", err)
return
}
} }
} }

View File

@@ -10,20 +10,27 @@ import (
"be.ems/features/fm" "be.ems/features/fm"
"be.ems/lib/config" "be.ems/lib/config"
"be.ems/lib/dborm"
"be.ems/lib/global" "be.ems/lib/global"
"be.ems/lib/log" "be.ems/lib/log"
"be.ems/src/framework/cron" "be.ems/src/framework/cron"
"be.ems/src/framework/database/db"
"be.ems/src/framework/utils/date"
neDataModel "be.ems/src/modules/network_data/model"
neModel "be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/go-resty/resty/v2" "github.com/go-resty/resty/v2"
) )
var NewProcessor = &BarProcessor{ var NewProcessor = &BarProcessor{
progress: 0, neInfoService: neService.NewNeInfo,
count: 0, progress: 0,
count: 0,
} }
// bar 队列任务处理 // bar 队列任务处理
type BarProcessor struct { type BarProcessor struct {
neInfoService *neService.NeInfo // 网元信息服务
// 任务进度 // 任务进度
progress int progress int
// 执行次数 // 执行次数
@@ -31,7 +38,7 @@ type BarProcessor struct {
} }
type BarParams struct { type BarParams struct {
AlarmID string `json:"alarmID"` AlarmID string `json:"alarmID"`
AlarmCode int `json:"alarmCode"` AlarmCode int64 `json:"alarmCode"`
AlarmTitle string `json:"alarmTitle"` AlarmTitle string `json:"alarmTitle"`
AlarmType string `json:"alarmType"` AlarmType string `json:"alarmType"`
OrigSeverity string `json:"origSeverity"` OrigSeverity string `json:"origSeverity"`
@@ -44,38 +51,6 @@ type BarParams struct {
Threshold int64 `json:"threshold"` Threshold int64 `json:"threshold"`
} }
// type BarParams struct {
// Duration int `json:"duration"`
// }
type Alarm struct {
Id int `json:"-" xorm:"pk 'id' autoincr"`
AlarmSeq int `json:"alarmSeq"`
AlarmId string `json:"alarmId" xorm:"alarm_id"`
NeId string `json:"neId"`
AlarmCode int `json:"alarmCode"`
AlarmTitle string `json:"alarmTitle"`
EventTime string `json:"eventTime"`
AlarmType string `json:"alarmType"`
OrigSeverity string `json:"origSeverity"`
PerceivedSeverity string `json:"perceivedSeverity"`
PVFlag string `json:"pvFlag" xorm:"pv_flag"`
NeName string `json:"neName"`
NeType string `json:"neType"`
ObjectUid string `json:"objectUid" xorm:"object_uid"`
ObjectName string `json:"objectName" xorm:"object_name"`
ObjectType string `json:"objectType" xorm:"object_type"`
LocationInfo string `json:"locationInfo"`
Province string `json:"province"`
AlarmStatus int `json:"alarmStatus" xorm:"alarm_status"`
SpecificProblem string `json:"specificProblem"`
SpecificProblemID string `json:"specificProblemID" xorm:"specific_problem_id"`
AddInfo string `json:"addInfo"`
// ClearType int `json:"-" xorm:"clear_type"` // 0: Unclear, 1: Auto clear, 2: Manual clear
// ClearTime sql.NullTime `json:"-" xorm:"clear_time"`
}
var client = resty.New() var client = resty.New()
func init() { func init() {
@@ -97,29 +72,23 @@ func (s *BarProcessor) Execute(data any) (any, error) {
return nil, err return nil, err
} }
var nes []dborm.NeInfo
_, err = dborm.XormGetAllNeInfo(&nes)
if err != nil {
log.Error("Failed to get all ne info:", err)
return nil, err
}
succActiveAlarmNum := 0 succActiveAlarmNum := 0
failActiveAlarmNum := 0 failActiveAlarmNum := 0
succClearAlarmNum := 0 succClearAlarmNum := 0
failClearAlarmNum := 0 failClearAlarmNum := 0
for _, ne := range nes { neList := s.neInfoService.Find(neModel.NeInfo{}, false, false)
for _, neInfo := range neList {
//log.Debug("ne:", ne) //log.Debug("ne:", ne)
sql := fmt.Sprintf("select * from ne_state where ne_type='%s' and ne_id='%s' order by `timestamp` desc limit 1", ne.NeType, ne.NeId) sql := fmt.Sprintf("select * from ne_state where ne_type='%s' and ne_id='%s' order by `timestamp` desc limit 1", neInfo.NeType, neInfo.NeId)
log.Debug("SQL:", sql) log.Debug("SQL:", sql)
neState, err := dborm.XormGetDataBySQL(sql) neState, err := db.RawDB("", sql, nil)
if err != nil { if err != nil {
log.Error("Failed to get ne_state:", err) log.Error("Failed to get ne_state:", err)
continue continue
} }
if len(*neState) == 0 { if len(neState) == 0 {
log.Warn("Not found record in ne_state:") log.Warn("Not found record in ne_state:")
//continue //continue
} }
@@ -139,8 +108,8 @@ func (s *BarProcessor) Execute(data any) (any, error) {
// log.Debug("alarmDefine:", alarmDefine) // log.Debug("alarmDefine:", alarmDefine)
sql = fmt.Sprintf("select * from alarm where alarm_id = '%s' and ne_type='%s' and ne_id = '%s' order by event_time desc limit 1", sql = fmt.Sprintf("select * from alarm where alarm_id = '%s' and ne_type='%s' and ne_id = '%s' order by event_time desc limit 1",
alarmDefine.AlarmID, ne.NeType, ne.RmUID) alarmDefine.AlarmID, neInfo.NeType, neInfo.RmUID)
alarm, err := dborm.XormGetDataBySQL(sql) alarm, err := db.RawDB("", sql, nil)
if err != nil { if err != nil {
log.Error("Failed to get alarm:", err) log.Error("Failed to get alarm:", err)
continue continue
@@ -148,11 +117,11 @@ func (s *BarProcessor) Execute(data any) (any, error) {
//log.Debug("alarm:", *alarm) //log.Debug("alarm:", *alarm)
var timestamp string var timestamp string
if len(*neState) == 0 { if len(neState) == 0 {
log.Infof("Not found ne_state neType:%s, neId:%s", ne.NeType, ne.NeId) log.Infof("Not found ne_state neType:%s, neId:%s", neInfo.NeType, neInfo.NeId)
timestamp = ne.UpdateTime.Format(time.DateTime) timestamp = date.ParseDateToStr(neInfo.UpdateTime, date.YYYYMMDDHHMMSS)
} else { } else {
timestamp = (*neState)[0]["timestamp"] timestamp = fmt.Sprint(neState[0]["timestamp"])
} }
// 解析日期时间字符串为时间对象 // 解析日期时间字符串为时间对象
@@ -164,44 +133,44 @@ func (s *BarProcessor) Execute(data any) (any, error) {
log.Debugf("timestamp:%s seconds:%d", timestamp, seconds) log.Debugf("timestamp:%s seconds:%d", timestamp, seconds)
if seconds <= alarmDefine.Threshold { if seconds <= alarmDefine.Threshold {
if len(*alarm) == 0 || (*alarm)[0]["alarm_status"] == fm.AlarmStatusClearString { if len(alarm) == 0 || alarm[0]["alarm_status"] == fm.AlarmStatusClearString {
continue continue
} }
// clear alarm, todo // clear alarm, todo
var alarmSeq int = 1 var alarmSeq int64 = 1
threshold := strconv.FormatInt(alarmDefine.Threshold, 10) threshold := strconv.FormatInt(alarmDefine.Threshold, 10)
SpecificProblem := strings.ReplaceAll(alarmDefine.SpecificProblem, "{threshold}", threshold) SpecificProblem := strings.ReplaceAll(alarmDefine.SpecificProblem, "{threshold}", threshold)
locationInfo := fmt.Sprintf("SystemManagement.State: NE heartbeat timestamp=%sthreshold=%v", timestamp, alarmDefine.Threshold) locationInfo := fmt.Sprintf("SystemManagement.State: NE heartbeat timestamp=%sthreshold=%v", timestamp, alarmDefine.Threshold)
alarmData := &Alarm{ alarmData := &neDataModel.Alarm{
AlarmSeq: alarmSeq, AlarmSeq: alarmSeq,
AlarmId: alarmDefine.AlarmID, AlarmId: alarmDefine.AlarmID,
NeId: ne.RmUID, NeId: neInfo.RmUID,
NeType: ne.NeType, NeType: neInfo.NeType,
NeName: ne.NeName, NeName: neInfo.NeName,
Province: ne.Province, Province: neInfo.Province,
PVFlag: ne.PvFlag, PvFlag: neInfo.PvFlag,
AlarmCode: alarmDefine.AlarmCode, AlarmCode: alarmDefine.AlarmCode,
AlarmTitle: alarmDefine.AlarmTitle, AlarmTitle: alarmDefine.AlarmTitle,
AlarmType: alarmDefine.AlarmType, AlarmType: alarmDefine.AlarmType,
AlarmStatus: fm.AlarmStatusClear, AlarmStatus: "0",
OrigSeverity: alarmDefine.OrigSeverity, OrigSeverity: alarmDefine.OrigSeverity,
ObjectUid: alarmDefine.ObjectUID, ObjectUid: alarmDefine.ObjectUID,
ObjectName: alarmDefine.ObjectName, ObjectName: alarmDefine.ObjectName,
ObjectType: alarmDefine.ObjectType, ObjectType: alarmDefine.ObjectType,
LocationInfo: locationInfo, LocationInfo: locationInfo,
SpecificProblem: SpecificProblem, SpecificProblem: SpecificProblem,
SpecificProblemID: alarmDefine.SpecificProblemID, SpecificProblemId: alarmDefine.SpecificProblemID,
AddInfo: alarmDefine.AddInfo, AddInfo: alarmDefine.AddInfo,
EventTime: time.Now().Local().Format(time.RFC3339), EventTime: time.Now().UnixMilli(),
} }
alarmArray := &[]Alarm{*alarmData} alarmArray := &[]neDataModel.Alarm{*alarmData}
body, _ := json.Marshal(alarmArray) body, _ := json.Marshal(alarmArray)
//log.Debug("body: ", string(body)) //log.Debug("body: ", string(body))
var response *resty.Response var response *resty.Response
requestURI := fmt.Sprintf("/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", ne.NeType) requestURI := fmt.Sprintf("/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", neInfo.NeType)
//restHost := fmt.Sprintf("http://127.0.0.1:%d", config.GetYamlConfig().Rest[0].Port) //restHost := fmt.Sprintf("http://127.0.0.1:%d", config.GetYamlConfig().Rest[0].Port)
restHost := config.GetOMCHostUrl() restHost := config.GetOMCHostUrl()
requestURL := fmt.Sprintf("%s%s", restHost, requestURI) requestURL := fmt.Sprintf("%s%s", restHost, requestURI)
@@ -233,8 +202,8 @@ func (s *BarProcessor) Execute(data any) (any, error) {
failClearAlarmNum++ failClearAlarmNum++
} }
} else { } else {
var alarmSeq int = 1 var alarmSeq int64 = 1
if len(*alarm) > 0 && (*alarm)[0]["alarm_status"] == fm.AlarmStatusActiveString { if len(alarm) > 0 && alarm[0]["alarm_status"] == fm.AlarmStatusActiveString {
log.Info("System state alarm has exist") log.Info("System state alarm has exist")
continue continue
} }
@@ -242,35 +211,35 @@ func (s *BarProcessor) Execute(data any) (any, error) {
threshold := strconv.FormatInt(alarmDefine.Threshold, 10) threshold := strconv.FormatInt(alarmDefine.Threshold, 10)
SpecificProblem := strings.ReplaceAll(alarmDefine.SpecificProblem, "{threshold}", threshold) SpecificProblem := strings.ReplaceAll(alarmDefine.SpecificProblem, "{threshold}", threshold)
locationInfo := fmt.Sprintf("SystemManagement.State: NE heartbeat timestamp=%sthreshold=%v", timestamp, alarmDefine.Threshold) locationInfo := fmt.Sprintf("SystemManagement.State: NE heartbeat timestamp=%sthreshold=%v", timestamp, alarmDefine.Threshold)
alarmData := &Alarm{ alarmData := &neDataModel.Alarm{
AlarmSeq: alarmSeq, AlarmSeq: alarmSeq,
AlarmId: alarmDefine.AlarmID, AlarmId: alarmDefine.AlarmID,
NeId: ne.RmUID, NeId: neInfo.RmUID,
NeType: ne.NeType, NeType: neInfo.NeType,
NeName: ne.NeName, NeName: neInfo.NeName,
Province: ne.Province, Province: neInfo.Province,
PVFlag: ne.PvFlag, PvFlag: neInfo.PvFlag,
AlarmCode: alarmDefine.AlarmCode, AlarmCode: alarmDefine.AlarmCode,
AlarmTitle: alarmDefine.AlarmTitle, AlarmTitle: alarmDefine.AlarmTitle,
AlarmType: alarmDefine.AlarmType, AlarmType: alarmDefine.AlarmType,
AlarmStatus: fm.AlarmStatusActive, AlarmStatus: "1",
OrigSeverity: alarmDefine.OrigSeverity, OrigSeverity: alarmDefine.OrigSeverity,
ObjectUid: alarmDefine.ObjectUID, ObjectUid: alarmDefine.ObjectUID,
ObjectName: alarmDefine.ObjectName, ObjectName: alarmDefine.ObjectName,
ObjectType: alarmDefine.ObjectType, ObjectType: alarmDefine.ObjectType,
LocationInfo: locationInfo, LocationInfo: locationInfo,
SpecificProblem: SpecificProblem, SpecificProblem: SpecificProblem,
SpecificProblemID: alarmDefine.SpecificProblemID, SpecificProblemId: alarmDefine.SpecificProblemID,
AddInfo: alarmDefine.AddInfo, AddInfo: alarmDefine.AddInfo,
EventTime: time.Now().Local().Format(time.RFC3339), EventTime: time.Now().UnixMilli(),
} }
alarmArray := &[]Alarm{*alarmData} alarmArray := &[]neDataModel.Alarm{*alarmData}
body, _ := json.Marshal(alarmArray) body, _ := json.Marshal(alarmArray)
//log.Debug("body: ", string(body)) //log.Debug("body: ", string(body))
var response *resty.Response var response *resty.Response
requestURI := fmt.Sprintf("/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", ne.NeType) requestURI := fmt.Sprintf("/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", neInfo.NeType)
//restHost := fmt.Sprintf("http://127.0.0.1:%d", config.GetYamlConfig().Rest[0].Port) //restHost := fmt.Sprintf("http://127.0.0.1:%d", config.GetYamlConfig().Rest[0].Port)
restHost := config.GetOMCHostUrl() restHost := config.GetOMCHostUrl()
requestURL := fmt.Sprintf("%s%s", restHost, requestURI) requestURL := fmt.Sprintf("%s%s", restHost, requestURI)

View File

@@ -29,7 +29,7 @@ func (s *MonitorSysResourceProcessor) Execute(data any) (any, error) {
s.count++ // 执行次数加一 s.count++ // 执行次数加一
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 读取参数值 // 读取参数值
var params struct { var params struct {

View File

@@ -27,17 +27,17 @@ func (s *NeConfigBackupProcessor) Execute(data any) (any, error) {
s.count++ // 执行次数加一 s.count++ // 执行次数加一
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 返回结果,用于记录执行结果 // 返回结果,用于记录执行结果
result := map[string]any{ result := map[string]any{
"count": s.count, "count": s.count,
} }
neList := s.neInfoService.SelectList(neModel.NeInfo{}, false, false) neList := s.neInfoService.Find(neModel.NeInfo{}, false, false)
for _, neInfo := range neList { for _, neInfo := range neList {
neTypeAndId := fmt.Sprintf("%s_%s", neInfo.NeType, neInfo.NeId) neTypeAndId := fmt.Sprintf("%s_%s", neInfo.NeType, neInfo.NeId)
// 将网元文件备份到本地 // 将网元文件备份到本地
zipFilePath, err := s.neConfigBackupService.NeConfigNeToLocal(neInfo) zipFilePath, err := s.neConfigBackupService.FileNeToLocal(neInfo)
if err != nil { if err != nil {
result[neTypeAndId] = err.Error() result[neTypeAndId] = err.Error()
continue continue

View File

@@ -29,13 +29,13 @@ func (s *NeDataUDM) Execute(data any) (any, error) {
s.count++ // 执行次数加一 s.count++ // 执行次数加一
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 返回结果,用于记录执行结果 // 返回结果,用于记录执行结果
result := map[string]any{ result := map[string]any{
"count": s.count, "count": s.count,
} }
neList := s.neInfoService.SelectList(neModel.NeInfo{NeType: "UDM"}, false, false) neList := s.neInfoService.Find(neModel.NeInfo{NeType: "UDM"}, false, false)
for _, neInfo := range neList { for _, neInfo := range neList {
result[fmt.Sprintf("AuthNumber_%s", neInfo.NeId)] = s.udmAuthService.ResetData(neInfo.NeId) result[fmt.Sprintf("AuthNumber_%s", neInfo.NeId)] = s.udmAuthService.ResetData(neInfo.NeId)
result[fmt.Sprintf("SubNumber_%s", neInfo.NeId)] = s.udmSubService.ResetData(neInfo.NeId) result[fmt.Sprintf("SubNumber_%s", neInfo.NeId)] = s.udmSubService.ResetData(neInfo.NeId)

View File

@@ -1,9 +1,9 @@
package controller package controller
import ( import (
"be.ems/src/framework/i18n" "fmt"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"be.ems/src/modules/monitor/service" "be.ems/src/modules/monitor/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -29,39 +29,39 @@ type MonitorController struct {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param type query string true "Data Type" Enums(all,load,cpu,memory,io,network) default(all) // @Param type query string true "Data Type" Enums(all,load,cpu,memory,io,network) default(all)
// @Param startTime query number true "StartTime, timestamp milliseconds" default(1738771200000) // @Param beginTime query number true "BeginTime, timestamp milliseconds" default(1738771200000)
// @Param endTime query number true "EndTime, timestamp milliseconds" default(1738810051253) // @Param endTime query number true "EndTime, timestamp milliseconds" default(1738810051253)
// @Param neType query string false "NE Type, Currently none Default #" default(#) // @Param neType query string false "NE Type, Currently none Default #" default(#)
// @Param neId query string false "NE ID, Currently none Default #" default(#) // @Param neId query string false "NE ID, Currently none Default #" default(#)
// @Param name query string false "Name, Data Type valid for networ and io" // @Param name query string false "Name, Data Type valid for networ and io"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Resource monitoring information loading // @Summary Load Resource Utilization Information
// @Description Resource monitoring information loading // @Description Load Resource Utilization Information
// @Router /monitor/load [get] // @Router /monitor/load [get]
func (s *MonitorController) Load(c *gin.Context) { func (s *MonitorController) Load(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var querys struct { var querys struct {
Type string `form:"type" binding:"required,oneof=all load cpu memory io network"` // 数据类型all/load/cpu/memory/io/network Type string `form:"type" binding:"required,oneof=all load cpu memory io network"` // 数据类型all/load/cpu/memory/io/network
StartTime int64 `form:"startTime" binding:"required"` // 开始时间 BeginTime int64 `form:"beginTime" binding:"required"` // 开始时间
EndTime int64 `form:"endTime" binding:"required"` // 结束时间 EndTime int64 `form:"endTime" binding:"required"` // 结束时间
NeType string `form:"neType"` // 网元类型 NeType string `form:"neType"` // 网元类型
NeID string `form:"neId"` // 网元ID NeID string `form:"neId"` // 网元ID
Name string `form:"name"` // 名称networ和io时有效 Name string `form:"name"` // 名称networ和io时有效
} }
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询数据 // 查询数据
data := s.monitorService.SelectMonitorInfo(map[string]any{ data := s.monitorService.FindInfo(map[string]any{
"type": querys.Type, "type": querys.Type,
"startTime": querys.StartTime, "beginTime": querys.BeginTime,
"endTime": querys.EndTime, "endTime": querys.EndTime,
"neType": querys.NeType, "neType": querys.NeType,
"neId": querys.NeID, "neId": querys.NeID,
"name": querys.Name, "name": querys.Name,
}) })
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -1,11 +1,13 @@
package controller package controller
import ( import (
"be.ems/src/framework/constants/cachekey" "fmt"
"be.ems/src/framework/constants"
"be.ems/src/framework/database/redis"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/redis" "be.ems/src/framework/reqctx"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/resp"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -32,138 +34,148 @@ type SysCacheController struct{}
// @Description Cache Service Information // @Description Cache Service Information
// @Router /monitor/cache [get] // @Router /monitor/cache [get]
func (s *SysCacheController) Info(c *gin.Context) { func (s *SysCacheController) Info(c *gin.Context) {
c.JSON(200, result.OkData(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
"info": redis.Info(""), "info": redis.Info(""),
"dbSize": redis.KeySize(""), "dbSize": redis.KeySize(""),
"commandStats": redis.CommandStats(""), "commandStats": redis.CommandStats(""),
})) }))
} }
// 缓存名称列表 // Names 缓存名称列表
// //
// GET /getNames // GET /names
func (s *SysCacheController) Names(c *gin.Context) { func (s SysCacheController) Names(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
caches := []model.SysCache{ caches := []model.SysCache{
model.NewSysCacheNames(i18n.TKey(language, "cache.name.user"), cachekey.LOGIN_TOKEN_KEY), model.NewNames(i18n.TKey(language, "cache.name.user"), constants.CACHE_LOGIN_TOKEN),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.sys_config"), cachekey.SYS_CONFIG_KEY), model.NewNames(i18n.TKey(language, "cache.name.sys_config"), constants.CACHE_SYS_CONFIG),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.sys_dict"), cachekey.SYS_DICT_KEY), model.NewNames(i18n.TKey(language, "cache.name.sys_dict"), constants.CACHE_SYS_DICT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.captcha_codes"), cachekey.CAPTCHA_CODE_KEY), model.NewNames(i18n.TKey(language, "cache.name.captcha_codes"), constants.CACHE_CAPTCHA_CODE),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.repeat_submit"), cachekey.REPEAT_SUBMIT_KEY), model.NewNames(i18n.TKey(language, "cache.name.repeat_submit"), constants.CACHE_REPEAT_SUBMIT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.rate_limit"), cachekey.RATE_LIMIT_KEY), model.NewNames(i18n.TKey(language, "cache.name.rate_limit"), constants.CACHE_RATE_LIMIT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.pwd_err_cnt"), cachekey.PWD_ERR_CNT_KEY), model.NewNames(i18n.TKey(language, "cache.name.pwd_err_cnt"), constants.CACHE_PWD_ERR_COUNT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.ne_info"), cachekey.NE_KEY), model.NewNames(i18n.TKey(language, "cache.name.ne_info"), constants.CACHE_NE_INFO),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.ne_data"), cachekey.NE_DATA_KEY), model.NewNames(i18n.TKey(language, "cache.name.ne_data"), constants.CACHE_NE_DATA),
} }
c.JSON(200, result.OkData(caches)) c.JSON(200, resp.OkData(caches))
} }
// 缓存名称下键名列表 // Keys 缓存名称下键名列表
// //
// GET /getKeys/:cacheName // GET /keys?cacheName=xxx
func (s *SysCacheController) Keys(c *gin.Context) { func (s SysCacheController) Keys(c *gin.Context) {
language := ctx.AcceptLanguage(c) var query struct {
cacheName := c.Param("cacheName") CacheName string `form:"cacheName" binding:"required"` // 键名列表中得到的缓存名称
if cacheName == "" { }
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) if err := c.ShouldBindQuery(&query); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
caches := []model.SysCache{} caches := []model.SysCache{}
cacheKeys, _ := redis.GetKeys("", query.CacheName+":*")
// 遍历组装
cacheKeys, _ := redis.GetKeys("", cacheName+":*")
for _, key := range cacheKeys { for _, key := range cacheKeys {
caches = append(caches, model.NewSysCacheKeys(cacheName, key)) caches = append(caches, model.NewKeys(query.CacheName, key))
} }
c.JSON(200, result.OkData(caches)) c.JSON(200, resp.OkData(caches))
} }
// 缓存内容 // Value 缓存内容信息
// //
// GET /getValue/:cacheName/:cacheKey // GET /value?cacheName=xxx&cacheKey=xxx
func (s *SysCacheController) Value(c *gin.Context) { func (s SysCacheController) Value(c *gin.Context) {
language := ctx.AcceptLanguage(c) var query struct {
cacheName := c.Param("cacheName") CacheName string `form:"cacheName" binding:"required"` // 键名列表中得到的缓存名称
cacheKey := c.Param("cacheKey") CacheKey string `form:"cacheKey" binding:"required"` // 键名列表中得到的缓存键名
if cacheName == "" || cacheKey == "" { }
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) if err := c.ShouldBindQuery(&query); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
cacheValue, err := redis.Get("", cacheName+":"+cacheKey) cacheValue, err := redis.Get("", query.CacheName+":"+query.CacheKey)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
sysCache := model.NewSysCacheValue(cacheName, cacheKey, cacheValue) sysCache := model.NewValue(query.CacheName, query.CacheKey, cacheValue)
c.JSON(200, result.OkData(sysCache)) c.JSON(200, resp.OkData(sysCache))
} }
// 删除缓存名称下键名列表 // CleanNames 缓存名称列表安全删除
// //
// DELETE /clearCacheName/:cacheName // DELETE /names
func (s *SysCacheController) ClearCacheName(c *gin.Context) { func (s SysCacheController) CleanNames(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
cacheName := c.Param("cacheName")
if cacheName == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
cacheKeys, err := redis.GetKeys("", cacheName+":*")
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
return
}
ok, _ := redis.DelKeys("", cacheKeys)
if ok {
c.JSON(200, result.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
}
// 删除缓存键名
//
// DELETE /clearCacheKey/:cacheName/:cacheKey
func (s *SysCacheController) ClearCacheKey(c *gin.Context) {
language := ctx.AcceptLanguage(c)
cacheName := c.Param("cacheName")
cacheKey := c.Param("cacheKey")
if cacheName == "" || cacheKey == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
ok, _ := redis.Del("", cacheName+":"+cacheKey)
if ok {
c.JSON(200, result.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
}
// 安全清理缓存名称
//
// DELETE /clearCacheSafe
func (s *SysCacheController) ClearCacheSafe(c *gin.Context) {
language := ctx.AcceptLanguage(c)
caches := []model.SysCache{ caches := []model.SysCache{
model.NewSysCacheNames(i18n.TKey(language, "cache.name.sys_config"), cachekey.SYS_CONFIG_KEY), model.NewNames(i18n.TKey(language, "cache.name.sys_config"), constants.CACHE_SYS_CONFIG),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.sys_dict"), cachekey.SYS_DICT_KEY), model.NewNames(i18n.TKey(language, "cache.name.sys_dict"), constants.CACHE_SYS_DICT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.repeat_submit"), cachekey.REPEAT_SUBMIT_KEY), model.NewNames(i18n.TKey(language, "cache.name.repeat_submit"), constants.CACHE_REPEAT_SUBMIT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.rate_limit"), cachekey.RATE_LIMIT_KEY), model.NewNames(i18n.TKey(language, "cache.name.rate_limit"), constants.CACHE_RATE_LIMIT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.pwd_err_cnt"), cachekey.PWD_ERR_CNT_KEY), model.NewNames(i18n.TKey(language, "cache.name.pwd_err_cnt"), constants.CACHE_PWD_ERR_COUNT),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.ne_info"), cachekey.NE_KEY), model.NewNames(i18n.TKey(language, "cache.name.ne_info"), constants.CACHE_NE_INFO),
model.NewSysCacheNames(i18n.TKey(language, "cache.name.ne_data"), cachekey.NE_DATA_KEY), model.NewNames(i18n.TKey(language, "cache.name.ne_data"), constants.CACHE_NE_DATA),
} }
for _, v := range caches { for _, v := range caches {
cacheKeys, err := redis.GetKeys("", v.CacheName+":*") cacheKeys, err := redis.GetKeys("", v.CacheName+":*")
if err != nil { if err != nil {
continue continue
} }
redis.DelKeys("", cacheKeys) _ = redis.DelKeys("", cacheKeys)
} }
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
}
// CleanKeys 缓存名称下键名删除
//
// DELETE /keys?cacheName=xxx
func (s SysCacheController) CleanKeys(c *gin.Context) {
var query struct {
CacheName string `form:"cacheName" binding:"required"` // 键名列表中得到的缓存名称
}
if err := c.ShouldBindQuery(&query); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if constants.CACHE_LOGIN_TOKEN == query.CacheName {
c.JSON(200, resp.ErrMsg("Cannot delete user information cache"))
return
}
cacheKeys, err := redis.GetKeys("", query.CacheName+":*")
if err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
if err = redis.DelKeys("", cacheKeys); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, resp.Ok(nil))
}
// CleanValue 缓存内容删除
//
// DELETE /value?cacheName=xxx&cacheKey=xxx
func (s SysCacheController) CleanValue(c *gin.Context) {
var query struct {
CacheName string `form:"cacheName" binding:"required"` // 键名列表中得到的缓存名称
CacheKey string `form:"cacheKey" binding:"required"` // 键名列表中得到的缓存键名
}
if err := c.ShouldBindQuery(&query); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if err := redis.Del("", query.CacheName+":"+query.CacheKey); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, resp.Ok(nil))
} }

View File

@@ -4,20 +4,18 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strconv" "strconv"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/service" "be.ems/src/modules/monitor/service"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 SysJobLogController 结构体 // 实例化控制层 SysJobLogController 结构体
@@ -38,15 +36,14 @@ type SysJobController struct {
// //
// GET /list // GET /list
func (s *SysJobController) List(c *gin.Context) { func (s *SysJobController) List(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
querys := ctx.QueryMap(c) query := reqctx.QueryMap(c)
// 多语言值转key查询 // 多语言值转key查询
if v, ok := querys["jobName"]; ok && v != "" { if v, ok := query["jobName"]; ok && v != "" {
querys["jobName"] = i18n.TFindKeyPrefix(language, "job", v.(string)) query["jobName"] = i18n.TFindKeyPrefix(language, "job", v)
} }
data := s.sysJobService.SelectJobPage(querys) rows, total := s.sysJobService.FindByPage(query)
rows := data["rows"].([]model.SysJob)
// 闭包函数处理多语言 // 闭包函数处理多语言
converI18n := func(language string, arr *[]model.SysJob) { converI18n := func(language string, arr *[]model.SysJob) {
@@ -57,40 +54,44 @@ func (s *SysJobController) List(c *gin.Context) {
} }
converI18n(language, &rows) converI18n(language, &rows)
c.JSON(200, result.Ok(data)) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// 调度任务信息 // 调度任务信息
// //
// GET /:jobId // GET /:jobId
func (s *SysJobController) Info(c *gin.Context) { func (s *SysJobController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
jobId := c.Param("jobId") jobId := parse.Number(c.Param("jobId"))
if jobId == "" { if jobId <= 0 {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: jobId is empty"))
return return
} }
data := s.sysJobService.SelectJobById(jobId) data := s.sysJobService.FindById(jobId)
if data.JobID == jobId { if data.JobId == jobId {
// 处理多语言 // 处理多语言
data.JobName = i18n.TKey(language, data.JobName) data.JobName = i18n.TKey(language, data.JobName)
data.Remark = i18n.TKey(language, data.Remark) data.Remark = i18n.TKey(language, data.Remark)
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务新增 // 调度任务新增
// //
// POST / // POST /
func (s *SysJobController) Add(c *gin.Context) { func (s *SysJobController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body model.SysJob var body model.SysJob
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil || body.JobID != "" { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.JobId > 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: jobId not is empty"))
return return
} }
@@ -98,7 +99,7 @@ func (s *SysJobController) Add(c *gin.Context) {
if parse.CronExpression(body.CronExpression) == 0 { if parse.CronExpression(body.CronExpression) == 0 {
// 调度任务新增【%s】失败Cron表达式不正确 // 调度任务新增【%s】失败Cron表达式不正确
msg := i18n.TTemplate(language, "job.errCronExpression", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errCronExpression", map[string]any{"name": body.JobName})
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
@@ -107,42 +108,46 @@ func (s *SysJobController) Add(c *gin.Context) {
// 调度任务新增【%s】失败任务传入参数json字符串不正确 // 调度任务新增【%s】失败任务传入参数json字符串不正确
msg := i18n.TTemplate(language, "job.errTargetParams", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errTargetParams", map[string]any{"name": body.JobName})
if len(body.TargetParams) < 7 { if len(body.TargetParams) < 7 {
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
if !json.Valid([]byte(body.TargetParams)) { if !json.Valid([]byte(body.TargetParams)) {
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
} }
// 检查属性值唯一 // 检查属性值唯一
uniqueJob := s.sysJobService.CheckUniqueJobName(body.JobName, body.JobGroup, "") uniqueJob := s.sysJobService.CheckUniqueByJobName(body.JobName, body.JobGroup, 0)
if !uniqueJob { if !uniqueJob {
// 调度任务新增【%s】失败同任务组内有相同任务名称 // 调度任务新增【%s】失败同任务组内有相同任务名称
msg := i18n.TTemplate(language, "job.errJobExists", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errJobExists", map[string]any{"name": body.JobName})
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
body.CreateBy = ctx.LoginUserToUserName(c) body.CreateBy = reqctx.LoginUserToUserName(c)
insertId := s.sysJobService.InsertJob(body) insertId := s.sysJobService.Insert(body)
if insertId != "" { if insertId > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务修改 // 调度任务修改
// //
// PUT / // PUT /
func (s *SysJobController) Edit(c *gin.Context) { func (s *SysJobController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body model.SysJob var body model.SysJob
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil || body.JobID == "" { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.JobId <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: jobId is empty"))
return return
} }
@@ -150,7 +155,7 @@ func (s *SysJobController) Edit(c *gin.Context) {
if parse.CronExpression(body.CronExpression) == 0 { if parse.CronExpression(body.CronExpression) == 0 {
// 调度任务修改【%s】失败Cron表达式不正确 // 调度任务修改【%s】失败Cron表达式不正确
msg := i18n.TTemplate(language, "job.errCronExpression", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errCronExpression", map[string]any{"name": body.JobName})
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
@@ -159,179 +164,188 @@ func (s *SysJobController) Edit(c *gin.Context) {
// 调度任务修改【%s】失败任务传入参数json字符串不正确 // 调度任务修改【%s】失败任务传入参数json字符串不正确
msg := i18n.TTemplate(language, "job.errTargetParams", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errTargetParams", map[string]any{"name": body.JobName})
if len(body.TargetParams) < 7 { if len(body.TargetParams) < 7 {
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
if !json.Valid([]byte(body.TargetParams)) { if !json.Valid([]byte(body.TargetParams)) {
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
} }
// 检查是否存在 // 检查是否存在
job := s.sysJobService.SelectJobById(body.JobID) jobInfo := s.sysJobService.FindById(body.JobId)
if job.JobID != body.JobID { if jobInfo.JobId != body.JobId {
// 没有可访问调度任务数据! // 没有可访问调度任务数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "job.noData"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "job.noData")))
return return
} }
// 检查属性值唯一 // 检查属性值唯一
uniqueJob := s.sysJobService.CheckUniqueJobName(body.JobName, body.JobGroup, body.JobID) uniqueJob := s.sysJobService.CheckUniqueByJobName(body.JobName, body.JobGroup, body.JobId)
if !uniqueJob { if !uniqueJob {
// 调度任务修改【%s】失败同任务组内有相同任务名称 // 调度任务修改【%s】失败同任务组内有相同任务名称
msg := i18n.TTemplate(language, "job.errJobExists", map[string]any{"name": body.JobName}) msg := i18n.TTemplate(language, "job.errJobExists", map[string]any{"name": body.JobName})
c.JSON(200, result.ErrMsg(msg)) c.JSON(200, resp.ErrMsg(msg))
return return
} }
// 多语言非原始值 // 多语言非原始值
i18nValue := i18n.TKey(language, job.JobName) i18nValue := i18n.TKey(language, jobInfo.JobName)
if i18nValue != job.JobName { if i18nValue != jobInfo.JobName {
i18n.UpdateKeyValue(language, job.JobName, body.JobName) systemService.NewSysI18n.UpdateKeyValue(language, jobInfo.JobName, body.JobName)
body.JobName = job.JobName body.JobName = jobInfo.JobName
} }
// 多语言非原始值 // 多语言非原始值
i18nValue2 := i18n.TKey(language, job.Remark) i18nValue2 := i18n.TKey(language, jobInfo.Remark)
if i18nValue2 != job.Remark { if i18nValue2 != jobInfo.Remark {
i18n.UpdateKeyValue(language, job.Remark, body.Remark) systemService.NewSysI18n.UpdateKeyValue(language, jobInfo.Remark, body.Remark)
body.Remark = job.Remark body.Remark = jobInfo.Remark
} }
body.UpdateBy = ctx.LoginUserToUserName(c) jobInfo.JobName = body.JobName
rows := s.sysJobService.UpdateJob(body) jobInfo.JobGroup = body.JobGroup
jobInfo.InvokeTarget = body.InvokeTarget
jobInfo.TargetParams = body.TargetParams
jobInfo.CronExpression = body.CronExpression
jobInfo.MisfirePolicy = body.MisfirePolicy
jobInfo.Concurrent = body.Concurrent
jobInfo.StatusFlag = body.StatusFlag
jobInfo.SaveLog = body.SaveLog
jobInfo.Remark = body.Remark
jobInfo.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.sysJobService.Update(jobInfo)
if rows > 0 { if rows > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务删除 // 调度任务删除
// //
// DELETE /:jobIds // DELETE /:jobId
func (s *SysJobController) Remove(c *gin.Context) { func (s *SysJobController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
jobIds := c.Param("jobIds") jobId := c.Param("jobId")
if jobIds == "" { if jobId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: jobId is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(jobIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(jobId, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.sysJobService.DeleteJobByIds(uniqueIDs)
rows, err := s.sysJobService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// 调度任务修改状态 // 调度任务修改状态
// //
// PUT /changeStatus // PUT /changeStatus
func (s *SysJobController) Status(c *gin.Context) { func (s *SysJobController) Status(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
// 任务ID JobId int64 `json:"jobId" binding:"required"`
JobId string `json:"jobId" binding:"required"` StatusFlag string `json:"statusFlag" binding:"required,oneof=0 1 2"`
// 状态
Status string `json:"status" binding:"required"`
} }
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 检查是否存在 // 检查是否存在
job := s.sysJobService.SelectJobById(body.JobId) // 检查是否存在
if job.JobID != body.JobId { jobInfo := s.sysJobService.FindById(body.JobId)
if jobInfo.JobId != body.JobId {
// 没有可访问调度任务数据! // 没有可访问调度任务数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "job.noData"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "job.noData")))
return return
} }
// 与旧值相等不变更 // 与旧值相等不变更
if job.Status == body.Status { if jobInfo.StatusFlag == body.StatusFlag {
// 变更状态与旧值相等! // 变更状态与旧值相等!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "job.statusEq"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "job.statusEq")))
return return
} }
// 更新状态 // 更新状态
job.Status = body.Status jobInfo.StatusFlag = body.StatusFlag
job.UpdateBy = ctx.LoginUserToUserName(c) jobInfo.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.sysJobService.UpdateJob(job) rows := s.sysJobService.Update(jobInfo)
if rows > 0 { if rows > 0 {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务立即执行一次 // 调度任务立即执行一次
// //
// PUT /run/:jobId // PUT /run/:jobId
func (s *SysJobController) Run(c *gin.Context) { func (s *SysJobController) Run(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
jobId := c.Param("jobId") jobId := parse.Number(c.Param("jobId"))
if jobId == "" { if jobId <= 0 {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: jobId is empty"))
return return
} }
// 检查是否存在 // 检查是否存在
job := s.sysJobService.SelectJobById(jobId) job := s.sysJobService.FindById(jobId)
if job.JobID != jobId { if job.JobId != jobId {
// 没有可访问调度任务数据! // 没有可访问调度任务数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "job.noData"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "job.noData")))
return return
} }
ok := s.sysJobService.RunQueueJob(job) ok := s.sysJobService.Run(job)
if ok { if ok {
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务重置刷新队列 // 调度任务重置刷新队列
// //
// PUT /resetQueueJob // PUT /resetQueueJob
func (s *SysJobController) ResetQueueJob(c *gin.Context) { func (s *SysJobController) ResetQueueJob(c *gin.Context) {
s.sysJobService.ResetQueueJob() s.sysJobService.Reset()
c.JSON(200, result.Ok(nil)) c.JSON(200, resp.Ok(nil))
} }
// 导出调度任务信息 // Export 导出调度任务信息
// //
// POST /export // GET /export
func (s *SysJobController) Export(c *gin.Context) { func (s *SysJobController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
querys := ctx.BodyJSONMap(c) query := reqctx.QueryMap(c)
querys["pageNum"] = 1 rows, total := s.sysJobService.FindByPage(query)
querys["pageSize"] = 10000 if total == 0 {
data := s.sysJobService.SelectJobPage(querys) // c.JSON(200, resp.CodeMsg(40016, "export data record as empty"))
if parse.Number(data["total"]) == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
rows := data["rows"].([]model.SysJob)
// rows := s.sysJobService.SelectJobList(model.SysJob{}) // rows := s.sysJobService.SelectJobList(model.SysJob{})
if len(rows) <= 0 { if len(rows) <= 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -358,7 +372,7 @@ func (s *SysJobController) Export(c *gin.Context) {
// "E1": i18n.TKey(language, "job.export.targetParams"), // "E1": i18n.TKey(language, "job.export.targetParams"),
} }
// 读取任务组名字典数据 // 读取任务组名字典数据
dictSysJobGroup := s.sysDictDataService.SelectDictDataByType("sys_job_group") dictSysJobGroup := s.sysDictDataService.FindByType("sys_job_group")
// 从第二行开始的数据 // 从第二行开始的数据
dataCells := make([]map[string]any, 0) dataCells := make([]map[string]any, 0)
for i, row := range rows { for i, row := range rows {
@@ -366,19 +380,19 @@ func (s *SysJobController) Export(c *gin.Context) {
// 任务组名 // 任务组名
sysJobGroup := "" sysJobGroup := ""
for _, v := range dictSysJobGroup { for _, v := range dictSysJobGroup {
if row.JobGroup == v.DictValue { if row.JobGroup == v.DataValue {
sysJobGroup = i18n.TKey(language, v.DictLabel) sysJobGroup = i18n.TKey(language, v.DataLabel)
break break
} }
} }
// 状态 // 状态
statusValue := i18n.TKey(language, "dictData.fail") statusValue := i18n.TKey(language, "dictData.fail")
if row.Status == "1" { if row.StatusFlag == "1" {
statusValue = i18n.TKey(language, "dictData.success") statusValue = i18n.TKey(language, "dictData.success")
} }
dataCells = append(dataCells, map[string]any{ dataCells = append(dataCells, map[string]any{
"A" + idx: row.JobID, "A" + idx: row.JobId,
"B" + idx: row.JobName, "B" + idx: row.JobName,
"C" + idx: sysJobGroup, "C" + idx: sysJobGroup,
"D" + idx: row.InvokeTarget, "D" + idx: row.InvokeTarget,
@@ -392,7 +406,7 @@ func (s *SysJobController) Export(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "") saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -3,15 +3,14 @@ package controller
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/date" "be.ems/src/framework/utils/date"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/service" "be.ems/src/modules/monitor/service"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
@@ -21,6 +20,7 @@ import (
// 实例化控制层 SysJobLogController 结构体 // 实例化控制层 SysJobLogController 结构体
var NewSysJobLog = &SysJobLogController{ var NewSysJobLog = &SysJobLogController{
sysJobService: service.NewSysJob,
sysJobLogService: service.NewSysJobLog, sysJobLogService: service.NewSysJobLog,
sysDictDataService: systemService.NewSysDictData, sysDictDataService: systemService.NewSysDictData,
} }
@@ -29,6 +29,7 @@ var NewSysJobLog = &SysJobLogController{
// //
// PATH /monitor/jobLog // PATH /monitor/jobLog
type SysJobLogController struct { type SysJobLogController struct {
sysJobService *service.SysJob // 调度任务服务
sysJobLogService *service.SysJobLog // 调度任务日志服务 sysJobLogService *service.SysJobLog // 调度任务日志服务
sysDictDataService *systemService.SysDictData // 字典数据服务 sysDictDataService *systemService.SysDictData // 字典数据服务
} }
@@ -37,22 +38,23 @@ type SysJobLogController struct {
// //
// GET /list // GET /list
func (s *SysJobLogController) List(c *gin.Context) { func (s *SysJobLogController) List(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询参数转换map // 查询参数转换map
querys := ctx.QueryMap(c) query := reqctx.QueryMap(c)
// 任务ID优先级更高 // 任务ID优先级更高
if v, ok := querys["jobId"]; ok && v != nil { if jobIdStr := c.Query("jobId"); jobIdStr != "" {
jobInfo := service.NewSysJob.SelectJobById(v.(string)) if jobId := parse.Number(jobIdStr); jobId > 0 {
querys["jobName"] = jobInfo.JobName job := s.sysJobService.FindById(jobId)
querys["jobGroup"] = jobInfo.JobGroup query["jobName"] = job.JobName
query["jobGroup"] = job.JobGroup
}
} }
// 多语言值转key查询 // 多语言值转key查询
if v, ok := querys["jobName"]; ok && v != "" { if v, ok := query["jobName"]; ok && v != "" {
querys["jobName"] = i18n.TFindKeyPrefix(language, "job", v.(string)) query["jobName"] = i18n.TFindKeyPrefix(language, "job", v)
} }
data := s.sysJobLogService.SelectJobLogPage(querys) rows, total := s.sysJobLogService.FindByPage(query)
rows := data["rows"].([]model.SysJobLog)
// 闭包函数处理多语言 // 闭包函数处理多语言
converI18n := func(language string, arr *[]model.SysJobLog) { converI18n := func(language string, arr *[]model.SysJobLog) {
@@ -62,88 +64,89 @@ func (s *SysJobLogController) List(c *gin.Context) {
} }
converI18n(language, &rows) converI18n(language, &rows)
c.JSON(200, result.Ok(data)) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// 调度任务日志信息 // 调度任务日志信息
// //
// GET /:jobLogId // GET /:logId
func (s *SysJobLogController) Info(c *gin.Context) { func (s *SysJobLogController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c) logId := parse.Number(c.Param("logId"))
jobLogId := c.Param("jobLogId") if logId <= 0 {
if jobLogId == "" { c.JSON(400, resp.CodeMsg(40010, "bind err: logId is empty"))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
data := s.sysJobLogService.SelectJobLogById(jobLogId)
if data.JobLogID == jobLogId { jobLogInfo := s.sysJobLogService.FindById(logId)
c.JSON(200, result.OkData(data)) if jobLogInfo.LogId == logId {
c.JSON(200, resp.OkData(jobLogInfo))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务日志删除 // 调度任务日志删除
// //
// DELETE /:jobLogIds // DELETE /:logId
func (s *SysJobLogController) Remove(c *gin.Context) { func (s *SysJobLogController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
jobLogIds := c.Param("jobLogIds") logId := c.Param("logId")
if jobLogIds == "" { if logId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: logId is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(jobLogIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(logId, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows := s.sysJobLogService.DeleteJobLogByIds(uniqueIDs)
rows := s.sysJobLogService.DeleteByIds(ids)
if rows > 0 { if rows > 0 {
// 删除成功:%d // 删除成功:%d
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
return return
} }
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
} }
// 调度任务日志清空 // 调度任务日志清空
// //
// DELETE /clean // DELETE /clean
func (s *SysJobLogController) Clean(c *gin.Context) { func (s *SysJobLogController) Clean(c *gin.Context) {
err := s.sysJobLogService.CleanJobLog() rows := s.sysJobLogService.Clean()
if err != nil { c.JSON(200, resp.OkData(rows))
c.JSON(200, result.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
} }
// 导出调度任务日志信息 // Export 导出调度任务日志信息
// //
// POST /export // GET /export
func (s *SysJobLogController) Export(c *gin.Context) { func (s *SysJobLogController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
querys := ctx.BodyJSONMap(c) query := reqctx.QueryMap(c)
querys["pageNum"] = 1 if jobIdStr := c.Query("jobId"); jobIdStr != "" {
querys["pageSize"] = 10000 if jobId := parse.Number(jobIdStr); jobId > 0 {
data := s.sysJobLogService.SelectJobLogPage(querys) job := s.sysJobService.FindById(jobId)
if parse.Number(data["total"]) == 0 { query["jobName"] = job.JobName
query["jobGroup"] = job.JobGroup
}
}
rows, total := s.sysJobLogService.FindByPage(query)
if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
rows := data["rows"].([]model.SysJobLog)
// rows := s.sysJobLogService.SelectJobLogList(model.SysJobLog{}) // rows := s.sysJobLogService.SelectJobLogList(model.SysJobLog{})
if len(rows) <= 0 { if len(rows) <= 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -170,7 +173,7 @@ func (s *SysJobLogController) Export(c *gin.Context) {
"G1": i18n.TKey(language, "log.operate.export.costTime"), "G1": i18n.TKey(language, "log.operate.export.costTime"),
} }
// 读取任务组名字典数据 // 读取任务组名字典数据
dictSysJobGroup := s.sysDictDataService.SelectDictDataByType("sys_job_group") dictSysJobGroup := s.sysDictDataService.FindByType("sys_job_group")
// 从第二行开始的数据 // 从第二行开始的数据
dataCells := make([]map[string]any, 0) dataCells := make([]map[string]any, 0)
for i, row := range rows { for i, row := range rows {
@@ -178,18 +181,18 @@ func (s *SysJobLogController) Export(c *gin.Context) {
// 任务组名 // 任务组名
sysJobGroup := "" sysJobGroup := ""
for _, v := range dictSysJobGroup { for _, v := range dictSysJobGroup {
if row.JobGroup == v.DictValue { if row.JobGroup == v.DataValue {
sysJobGroup = i18n.TKey(language, v.DictLabel) sysJobGroup = i18n.TKey(language, v.DataLabel)
break break
} }
} }
// 状态 // 状态
statusValue := i18n.TKey(language, "dictData.fail") statusValue := i18n.TKey(language, "dictData.fail")
if row.Status == "1" { if row.StatusFlag == "1" {
statusValue = i18n.TKey(language, "dictData.success") statusValue = i18n.TKey(language, "dictData.success")
} }
dataCells = append(dataCells, map[string]any{ dataCells = append(dataCells, map[string]any{
"A" + idx: row.JobLogID, "A" + idx: row.LogId,
"B" + idx: row.JobName, "B" + idx: row.JobName,
"C" + idx: sysJobGroup, "C" + idx: sysJobGroup,
"D" + idx: row.InvokeTarget, "D" + idx: row.InvokeTarget,
@@ -204,7 +207,7 @@ func (s *SysJobLogController) Export(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "") saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -2,15 +2,15 @@ package controller
import ( import (
"encoding/json" "encoding/json"
"fmt"
"sort" "sort"
"strings" "strings"
"be.ems/src/framework/constants/cachekey" "be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/database/redis"
"be.ems/src/framework/redis" "be.ems/src/framework/resp"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/token"
"be.ems/src/framework/vo" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/service" "be.ems/src/modules/monitor/service"
@@ -42,12 +42,11 @@ type SysUserOnlineController struct {
// @Description System Online User List // @Description System Online User List
// @Router /monitor/online/list [get] // @Router /monitor/online/list [get]
func (s *SysUserOnlineController) List(c *gin.Context) { func (s *SysUserOnlineController) List(c *gin.Context) {
language := ctx.AcceptLanguage(c) loginIp := c.Query("loginIp")
ipaddr := c.Query("ipaddr")
userName := c.Query("userName") userName := c.Query("userName")
// 获取所有在线用户key // 获取所有在线用户key
keys, _ := redis.GetKeys("", cachekey.LOGIN_TOKEN_KEY+"*") keys, _ := redis.GetKeys("", constants.CACHE_LOGIN_TOKEN+":*")
// 分批获取 // 分批获取
arr := make([]string, 0) arr := make([]string, 0)
@@ -59,81 +58,84 @@ func (s *SysUserOnlineController) List(c *gin.Context) {
chunk := keys[i:end] chunk := keys[i:end]
values, _ := redis.GetBatch("", chunk) values, _ := redis.GetBatch("", chunk)
for _, v := range values { for _, v := range values {
arr = append(arr, v.(string)) arr = append(arr, fmt.Sprint(v))
} }
} }
// 遍历字符串信息解析组合可用对象 // 遍历字符串信息解析组合可用对象
userOnlines := make([]model.SysUserOnline, 0) var userOnlines []model.SysUserOnline
for _, str := range arr { for _, str := range arr {
if str == "" { if str == "" {
continue continue
} }
var loginUser vo.LoginUser var tokenInfo token.TokenInfo
err := json.Unmarshal([]byte(str), &loginUser) err := json.Unmarshal([]byte(str), &tokenInfo)
if err != nil { if err != nil {
continue continue
} }
onlineUser := s.sysUserOnlineService.LoginUserToUserOnline(loginUser) onlineUser := s.sysUserOnlineService.TokenInfoToUserOnline(tokenInfo)
if onlineUser.TokenID != "" { if onlineUser.TokenID != "" {
onlineUser.LoginLocation = i18n.TKey(language, onlineUser.LoginLocation)
userOnlines = append(userOnlines, onlineUser) userOnlines = append(userOnlines, onlineUser)
} }
} }
// 根据查询条件过滤 // 根据查询条件过滤
filteredUserOnlines := make([]model.SysUserOnline, 0) filteredUserOnline := make([]model.SysUserOnline, 0)
if ipaddr != "" && userName != "" { if loginIp != "" && userName != "" {
for _, o := range userOnlines { for _, o := range userOnlines {
if strings.Contains(o.IPAddr, ipaddr) && strings.Contains(o.UserName, userName) { if strings.Contains(o.LoginIp, loginIp) && strings.Contains(o.UserName, userName) {
filteredUserOnlines = append(filteredUserOnlines, o) filteredUserOnline = append(filteredUserOnline, o)
} }
} }
} else if ipaddr != "" { } else if loginIp != "" {
for _, o := range userOnlines { for _, o := range userOnlines {
if strings.Contains(o.IPAddr, ipaddr) { if strings.Contains(o.LoginIp, loginIp) {
filteredUserOnlines = append(filteredUserOnlines, o) filteredUserOnline = append(filteredUserOnline, o)
} }
} }
} else if userName != "" { } else if userName != "" {
for _, o := range userOnlines { for _, o := range userOnlines {
if strings.Contains(o.UserName, userName) { if strings.Contains(o.UserName, userName) {
filteredUserOnlines = append(filteredUserOnlines, o) filteredUserOnline = append(filteredUserOnline, o)
} }
} }
} else { } else {
filteredUserOnlines = userOnlines filteredUserOnline = userOnlines
} }
// 按登录时间排序 // 按登录时间排序
sort.Slice(filteredUserOnlines, func(i, j int) bool { sort.Slice(filteredUserOnline, func(i, j int) bool {
return filteredUserOnlines[j].LoginTime > filteredUserOnlines[i].LoginTime return filteredUserOnline[j].LoginTime > filteredUserOnline[i].LoginTime
}) })
c.JSON(200, result.Ok(map[string]any{ c.JSON(200, resp.OkData(map[string]any{
"total": len(filteredUserOnlines), "total": len(filteredUserOnline),
"rows": filteredUserOnlines, "rows": filteredUserOnline,
})) }))
} }
// 在线用户强制退出 // Logout 在线用户强制退出
// //
// DELETE /:tokenId // DELETE /logout/:tokenId
func (s *SysUserOnlineController) ForceLogout(c *gin.Context) { func (s SysUserOnlineController) Logout(c *gin.Context) {
language := ctx.AcceptLanguage(c) tokenIdStr := c.Param("tokenId")
tokenId := c.Param("tokenId") if tokenIdStr == "" || strings.Contains(tokenIdStr, "*") {
if tokenId == "" || tokenId == "*" { c.JSON(400, resp.CodeMsg(40010, "bind err: tokenId is empty"))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 删除token // 处理字符转id数组后去重
ok, _ := redis.Del("", cachekey.LOGIN_TOKEN_KEY+tokenId) ids := strings.Split(tokenIdStr, ",")
if ok { uniqueIDs := parse.RemoveDuplicates(ids)
c.JSON(200, result.Ok(nil)) for _, v := range uniqueIDs {
return key := constants.CACHE_LOGIN_TOKEN + ":" + v
if err := redis.Del("", key); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
} }
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Ok(nil))
} }

View File

@@ -1,22 +1,23 @@
package controller package controller
import ( import (
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"be.ems/src/modules/monitor/service" "be.ems/src/modules/monitor/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 SystemInfoController 结构体 // NewSystem 实例化控制层
var NewSystemInfo = &SystemInfoController{ var NewSystem = &SystemController{
systemInfogService: service.NewSystemInfo, systemInfoService: service.NewSystemInfo,
} }
// 服务器监控信息 // SystemController 服务器监控信息 控制层处理
// //
// PATH /monitor/system-info // PATH /monitor/system
type SystemInfoController struct { type SystemController struct {
systemInfogService *service.SystemInfo // 服务器系统相关信息服务 // 服务器系统相关信息服务
systemInfoService *service.SystemInfo
} }
// 服务器信息 // 服务器信息
@@ -28,17 +29,17 @@ type SystemInfoController struct {
// @Produce json // @Produce json
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Server Information // @Summary System Server Information
// @Description Server Information // @Description System Server Information
// @Router /monitor/system-info [get] // @Router /monitor/system-info [get]
func (s *SystemInfoController) Info(c *gin.Context) { func (s SystemController) Info(c *gin.Context) {
data := map[string]any{ data := map[string]any{
"cpu": s.systemInfogService.CPUInfo(), "cpu": s.systemInfoService.CPUInfo(),
"memory": s.systemInfogService.MemoryInfo(), "memory": s.systemInfoService.MemoryInfo(),
"network": s.systemInfogService.NetworkInfo(), "network": s.systemInfoService.NetworkInfo(),
"time": s.systemInfogService.TimeInfo(), "time": s.systemInfoService.TimeInfo(),
"system": s.systemInfogService.SystemInfo(), "system": s.systemInfoService.SystemInfo(),
"disk": s.systemInfogService.DiskInfo(), "disk": s.systemInfoService.DiskInfo(),
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -3,15 +3,15 @@ package model
// MonitorBase 监控_基本信息 monitor_base // MonitorBase 监控_基本信息 monitor_base
type MonitorBase struct { type MonitorBase struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间 CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间
CPU float64 `json:"cpu" gorm:"cpu"` // cpu使用率 CPU float64 `json:"cpu" gorm:"column:cpu"` // cpu使用率
LoadUsage float64 `json:"loadUsage" gorm:"load_usage"` // cpu平均使用率 LoadUsage float64 `json:"loadUsage" gorm:"column:load_usage"` // cpu平均使用率
CPULoad1 float64 `json:"cpuLoad1" gorm:"cpu_load1"` // cpu使用1分钟 CPULoad1 float64 `json:"cpuLoad1" gorm:"column:cpu_load1"` // cpu使用1分钟
CPULoad5 float64 `json:"cpuLoad5" gorm:"cpu_load5"` // cpu使用5分钟 CPULoad5 float64 `json:"cpuLoad5" gorm:"column:cpu_load5"` // cpu使用5分钟
CPULoad15 float64 `json:"cpuLoad15" gorm:"cpu_load15"` // cpu使用15分钟 CPULoad15 float64 `json:"cpuLoad15" gorm:"column:cpu_load15"` // cpu使用15分钟
Memory float64 `json:"memory" gorm:"memory"` // 内存使用率 Memory float64 `json:"memory" gorm:"column:memory"` // 内存使用率
NeType string `json:"neType" gorm:"ne_type"` // 网元类型 NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
NeID string `json:"neId" gorm:"ne_id"` // 网元ID NeID string `json:"neId" gorm:"column:ne_id"` // 网元ID
} }
// TableName 表名称 // TableName 表名称

View File

@@ -3,14 +3,14 @@ package model
// MonitorIO 监控_磁盘IO monitor_io // MonitorIO 监控_磁盘IO monitor_io
type MonitorIO struct { type MonitorIO struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间 CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
Name string `json:"name" gorm:"name"` // 磁盘名 Name string `json:"name" gorm:"column:name"` // 磁盘名
Read int64 `json:"read" gorm:"read"` // 读取K Read int64 `json:"read" gorm:"column:read"` // 读取K
Write int64 `json:"write" gorm:"write"` // 写入K Write int64 `json:"write" gorm:"column:write"` // 写入K
Count int64 `json:"count" gorm:"count"` // 读写次数 Count int64 `json:"count" gorm:"column:count"` // 读写次数
Time int64 `json:"time" gorm:"time"` // 读写延迟 Time int64 `json:"time" gorm:"column:time"` // 读写延迟
NeType string `json:"neType" gorm:"ne_type"` // 网元类型 NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
NeID string `json:"neId" gorm:"ne_id"` // 网元ID NeID string `json:"neId" gorm:"column:ne_id"` // 网元ID
} }
// TableName 表名称 // TableName 表名称

View File

@@ -3,12 +3,12 @@ package model
// MonitorNetwork 监控_网络IO monitor_network // MonitorNetwork 监控_网络IO monitor_network
type MonitorNetwork struct { type MonitorNetwork struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间 CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
Name string `json:"name" gorm:"name"` // 网卡名 Name string `json:"name" gorm:"column:name"` // 网卡名
Up float64 `json:"up" gorm:"up"` // 上行 Up float64 `json:"up" gorm:"column:up"` // 上行
Down float64 `json:"down" gorm:"down"` // 下行 Down float64 `json:"down" gorm:"column:down"` // 下行
NeType string `json:"neType" gorm:"ne_type"` // 网元类型 NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
NeID string `json:"neId" gorm:"ne_id"` // 网元ID NeID string `json:"neId" gorm:"column:ne_id"` // 网元ID
} }
// TableName 表名称 // TableName 表名称

View File

@@ -10,18 +10,18 @@ type SysCache struct {
Remark string `json:"remark"` // 备注 Remark string `json:"remark"` // 备注
} }
// NewSysCacheNames 创建新的缓存名称列表项实例 // NewNames 创建新的缓存名称列表项实例
func NewSysCacheNames(cacheName string, cacheKey string) SysCache { func NewNames(cacheName string, cacheKey string) SysCache {
return SysCache{ return SysCache{
CacheName: cacheKey[:len(cacheKey)-1], CacheName: cacheKey,
CacheKey: "", CacheKey: "",
CacheValue: "", CacheValue: "",
Remark: cacheName, Remark: cacheName,
} }
} }
// NewSysCacheKeys 创建新的缓存键名列表项实例 // NewKeys 创建新的缓存键名列表项实例
func NewSysCacheKeys(cacheName string, cacheKey string) SysCache { func NewKeys(cacheName string, cacheKey string) SysCache {
return SysCache{ return SysCache{
CacheName: cacheName, CacheName: cacheName,
CacheKey: strings.Replace(cacheKey, cacheName+":", "", 1), CacheKey: strings.Replace(cacheKey, cacheName+":", "", 1),
@@ -30,8 +30,8 @@ func NewSysCacheKeys(cacheName string, cacheKey string) SysCache {
} }
} }
// NewSysCacheValue 创建新的缓存键名内容项实例 // NewValue 创建新的缓存键名内容项实例
func NewSysCacheValue(cacheName string, cacheKey string, cacheValue string) SysCache { func NewValue(cacheName string, cacheKey string, cacheValue string) SysCache {
return SysCache{ return SysCache{
CacheName: cacheName, CacheName: cacheName,
CacheKey: cacheKey, CacheKey: cacheKey,

View File

@@ -1,35 +1,25 @@
package model package model
// SysJob 调度任务信息表 sys_job // SysJob 调度任务调度表
type SysJob struct { type SysJob struct {
// 任务ID JobId int64 `json:"jobId" gorm:"column:job_id;primaryKey;autoIncrement"` // 任务ID
JobID string `json:"jobId"` JobName string `json:"jobName" gorm:"column:job_name" binding:"required"` // 任务名称
// 任务名 JobGroup string `json:"jobGroup" gorm:"column:job_group" binding:"required"` // 任务
JobName string `json:"jobName" binding:"required"` InvokeTarget string `json:"invokeTarget" gorm:"column:invoke_target" binding:"required"` // 调用目标字符串
// 任务组名 TargetParams string `json:"targetParams" gorm:"column:target_params"` // 调用目标传入参数
JobGroup string `json:"jobGroup" binding:"required"` CronExpression string `json:"cronExpression" gorm:"column:cron_expression" binding:"required"` // cron执行表达式
// 调用目标字符串 MisfirePolicy string `json:"misfirePolicy" gorm:"column:misfire_policy"` // 计划执行错误策略1立即执行 2执行一次 3放弃执行
InvokeTarget string `json:"invokeTarget" binding:"required"` Concurrent string `json:"concurrent" gorm:"column:concurrent"` // 是否并发执行0禁止 1允许
// 调用目标传入参数 StatusFlag string `json:"statusFlag" gorm:"column:status_flag"` // 任务状态0暂停 1正常
TargetParams string `json:"targetParams"` SaveLog string `json:"saveLog" gorm:"column:save_log"` // 是否记录任务日志0不记录 1记录
// cron执行表达式 CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CronExpression string `json:"cronExpression" binding:"required"` CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
// 计划执行错误策略1立即执行 2执行一次 3放弃执行 UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
MisfirePolicy string `json:"misfirePolicy"` UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
// 是否并发执行0禁止 1允许 Remark string `json:"remark" gorm:"column:remark"` // 备注
Concurrent string `json:"concurrent"` }
// 任务状态0暂停 1正常
Status string `json:"status"` // TableName 表名称
// 是否记录任务日志 func (*SysJob) TableName() string {
SaveLog string `json:"saveLog"` return "sys_job"
// 创建者
CreateBy string `json:"createBy"`
// 创建时间
CreateTime int64 `json:"createTime"`
// 更新者
UpdateBy string `json:"updateBy"`
// 更新时间
UpdateTime int64 `json:"updateTime"`
// 备注
Remark string `json:"remark"`
} }

View File

@@ -1,23 +1,19 @@
package model package model
// SysJobLog 定时任务调度日志表 sys_job_log // SysJobLog 调度任务调度日志表
type SysJobLog struct { type SysJobLog struct {
// 日志序号 LogId int64 `json:"logId" gorm:"column:log_id;primaryKey;autoIncrement"` // 任务日志ID
JobLogID string `json:"jobLogId"` JobName string `json:"jobName" gorm:"column:job_name"` // 任务名称
// 任务名 JobGroup string `json:"jobGroup" gorm:"column:job_group"` // 任务
JobName string `json:"jobName"` InvokeTarget string `json:"invokeTarget" gorm:"column:invoke_target"` // 调用目标字符串
// 任务组名 TargetParams string `json:"targetParams" gorm:"column:target_params"` // 调用目标传入参数
JobGroup string `json:"jobGroup"` JobMsg string `json:"jobMsg" gorm:"column:job_msg"` // 日志信息
// 调用目标字符串 StatusFlag string `json:"statusFlag" gorm:"column:status_flag"` // 执行状态0失败 1正常
InvokeTarget string `json:"invokeTarget"` CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
// 调用目标传入参数 CostTime int64 `json:"costTime" gorm:"column:cost_time"` // 消耗时间(毫秒)
TargetParams string `json:"targetParams"` }
// 日志信息
JobMsg string `json:"jobMsg"` // TableName 表名称
// 执行状态0失败 1正常 func (*SysJobLog) TableName() string {
Status string `json:"status"` return "sys_job_log"
// 创建时间
CreateTime int64 `json:"createTime"`
// 消耗时间(毫秒)
CostTime int64 `json:"costTime"`
} }

View File

@@ -2,20 +2,12 @@ package model
// SysUserOnline 当前在线会话对象 // SysUserOnline 当前在线会话对象
type SysUserOnline struct { type SysUserOnline struct {
// 会话编号 TokenID string `json:"tokenId"` // 会话编号
TokenID string `json:"tokenId"` DeptName string `json:"deptName"` // 部门名称
// 部门名称 UserName string `json:"userName"` // 用户名称
DeptName string `json:"deptName"` LoginIp string `json:"loginIp"` // 登录IP地址
// 用户名称 LoginLocation string `json:"loginLocation"` // 登录地址
UserName string `json:"userName"` Browser string `json:"browser"` // 浏览器类型
// 登录IP地址 OS string `json:"os"` // 操作系统
IPAddr string `json:"ipaddr"` LoginTime int64 `json:"loginTime"` // 登录时间
// 登录地址
LoginLocation string `json:"loginLocation"`
// 浏览器类型
Browser string `json:"browser"`
// 操作系统
OS string `json:"os"`
// 登录时间
LoginTime int64 `json:"loginTime"`
} }

View File

@@ -28,13 +28,26 @@ func Setup(router *gin.Engine) {
) )
} }
// 服务器服务信息 // 服务器信息
router.GET("/monitor/system-info", router.GET("/monitor/system",
// middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:system:info"}}), // middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:system:info"}}),
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewSystemInfo.Info, controller.NewSystem.Info,
) )
// 在线用户监控
sysUserOnlineGroup := router.Group("/monitor/user-online")
{
sysUserOnlineGroup.GET("/list",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:online:list"}}),
controller.NewSysUserOnline.List,
)
sysUserOnlineGroup.DELETE("/logout/:tokenId",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:online:logout"}}),
controller.NewSysUserOnline.Logout,
)
}
// 缓存服务信息 // 缓存服务信息
sysCacheGroup := router.Group("/monitor/cache") sysCacheGroup := router.Group("/monitor/cache")
{ {
@@ -43,29 +56,29 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewSysCache.Info, controller.NewSysCache.Info,
) )
sysCacheGroup.GET("/getNames", sysCacheGroup.GET("/names",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:list"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:list"}}),
controller.NewSysCache.Names, controller.NewSysCache.Names,
) )
sysCacheGroup.GET("/getKeys/:cacheName", sysCacheGroup.GET("/keys",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:list"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:list"}}),
controller.NewSysCache.Keys, controller.NewSysCache.Keys,
) )
sysCacheGroup.GET("/getValue/:cacheName/:cacheKey", sysCacheGroup.GET("/value",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:query"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:query"}}),
controller.NewSysCache.Value, controller.NewSysCache.Value,
) )
sysCacheGroup.DELETE("/clearCacheName/:cacheName", sysCacheGroup.DELETE("/names",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}),
controller.NewSysCache.ClearCacheName, controller.NewSysCache.CleanNames,
) )
sysCacheGroup.DELETE("/clearCacheKey/:cacheName/:cacheKey", sysCacheGroup.DELETE("/keys",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}),
controller.NewSysCache.ClearCacheKey, controller.NewSysCache.CleanKeys,
) )
sysCacheGroup.DELETE("/clearCacheSafe", sysCacheGroup.DELETE("/value",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:cache:remove"}}),
controller.NewSysCache.ClearCacheSafe, controller.NewSysCache.CleanValue,
) )
} }
@@ -76,11 +89,11 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:list"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:list"}}),
controller.NewSysJobLog.List, controller.NewSysJobLog.List,
) )
sysJobLogGroup.GET("/:jobLogId", sysJobLogGroup.GET("/:logId",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:query"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:query"}}),
controller.NewSysJobLog.Info, controller.NewSysJobLog.Info,
) )
sysJobLogGroup.DELETE("/:jobLogIds", sysJobLogGroup.DELETE("/:logId",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:remove"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:remove"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewSysJobLog.Remove, controller.NewSysJobLog.Remove,
@@ -91,7 +104,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_CLEAN)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_CLEAN)),
controller.NewSysJobLog.Clean, controller.NewSysJobLog.Clean,
) )
sysJobLogGroup.POST("/export", sysJobLogGroup.GET("/export",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:export"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:export"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_EXPORT)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJobLog", collectlogs.BUSINESS_TYPE_EXPORT)),
controller.NewSysJobLog.Export, controller.NewSysJobLog.Export,
@@ -119,12 +132,12 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewSysJob.Edit, controller.NewSysJob.Edit,
) )
sysJobGroup.DELETE("/:jobIds", sysJobGroup.DELETE("/:jobId",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:remove"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:remove"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewSysJob.Remove, controller.NewSysJob.Remove,
) )
sysJobGroup.PUT("/changeStatus", sysJobGroup.PUT("/status",
repeat.RepeatSubmit(5), repeat.RepeatSubmit(5),
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:changeStatus"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:changeStatus"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)),
@@ -136,30 +149,17 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewSysJob.Run, controller.NewSysJob.Run,
) )
sysJobGroup.PUT("/resetQueueJob", sysJobGroup.PUT("/reset",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:changeStatus"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:changeStatus"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_CLEAN)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_CLEAN)),
controller.NewSysJob.ResetQueueJob, controller.NewSysJob.ResetQueueJob,
) )
sysJobGroup.POST("/export", sysJobGroup.GET("/export",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:export"}}), middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:job:export"}}),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_EXPORT)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sysJob", collectlogs.BUSINESS_TYPE_EXPORT)),
controller.NewSysJob.Export, controller.NewSysJob.Export,
) )
} }
// 在线用户监控
sysUserOnlineGroup := router.Group("/monitor/online")
{
sysUserOnlineGroup.GET("/list",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:online:list"}}),
controller.NewSysUserOnline.List,
)
sysUserOnlineGroup.DELETE("/:tokenId",
middleware.PreAuthorize(map[string][]string{"hasPerms": {"monitor:online:forceLogout"}}),
controller.NewSysUserOnline.ForceLogout,
)
}
} }
// InitLoad 初始参数 // InitLoad 初始参数
@@ -167,5 +167,5 @@ func InitLoad() {
// 初始化定时任务处理 // 初始化定时任务处理
processor.InitCronQueue() processor.InitCronQueue()
// 启动时,初始化调度任务 // 启动时,初始化调度任务
service.NewSysJob.ResetQueueJob() service.NewSysJob.Reset()
} }

View File

@@ -26,7 +26,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 实现任务处理逻辑 // 实现任务处理逻辑
i := 0 i := 0
@@ -34,7 +34,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
for i < 5 { for i < 5 {
// 获取任务进度 // 获取任务进度
progress := s.progress progress := s.progress
logger.Infof("jonId: %s => 任务进度:%d", sysJob.JobID, progress) logger.Infof("jonId: %d => 任务进度:%d", sysJob.JobId, progress)
// 延迟响应 // 延迟响应
time.Sleep(time.Second * 2) time.Sleep(time.Second * 2)
// 程序中途执行错误 // 程序中途执行错误

View File

@@ -26,7 +26,7 @@ func (s *FooProcessor) Execute(data any) (any, error) {
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 实现任务处理逻辑 // 实现任务处理逻辑
i := 0 i := 0
@@ -34,7 +34,7 @@ func (s *FooProcessor) Execute(data any) (any, error) {
for i < 20 { for i < 20 {
// 获取任务进度 // 获取任务进度
progress := s.progress progress := s.progress
logger.Infof("jonId: %s => 任务进度:%d", sysJob.JobID, progress) logger.Infof("jonId: %d => 任务进度:%d", sysJob.JobId, progress)
// 延迟响应 // 延迟响应
time.Sleep(time.Second * 2) time.Sleep(time.Second * 2)
i++ i++

View File

@@ -14,7 +14,7 @@ func (s *simpleProcessor) Execute(data any) (any, error) {
options := data.(cron.JobData) options := data.(cron.JobData)
sysJob := options.SysJob sysJob := options.SysJob
logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID) logger.Infof("重复 %v 任务ID %d", options.Repeat, sysJob.JobId)
// 返回结果,用于记录执行结果 // 返回结果,用于记录执行结果
result := map[string]any{ result := map[string]any{

View File

@@ -1,33 +1,114 @@
package repository package repository
import "be.ems/src/modules/monitor/model" import (
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/monitor/model"
)
// IMonitor 监控服务资源相关信息 数据接口 // 实例化数据层 Monitor 结构体
type IMonitor interface { var NewMonitor = &Monitor{}
// CreateMonitorBase 创建监控_基本信息
CreateMonitorBase(m model.MonitorBase) error
// DelMonitorBase 删除监控_基本信息 // Monitor 监控服务资源相关信息 数据层处理
DelMonitorBase(ltTime int64) error type Monitor struct{}
// SelectMonitorBase 查询监控_基本信息 // SelectByBase 查询监控_基本信息
SelectMonitorBase(query map[string]any) []model.MonitorBase func (r Monitor) SelectByBase(query map[string]any) []model.MonitorBase {
tx := db.DB("").Model(&model.MonitorBase{})
// 查询条件拼接
if v, ok := query["neType"]; ok && v != "" {
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
tx = tx.Where("ne_id = ?", v)
}
tx.Where("create_time >= ? and create_time <= ?", query["beginTime"], query["endTime"])
// BatchCreateMonitorIO 批量创建监控_IO // 查询数据
BatchCreateMonitorIO(ioList []model.MonitorIO) error rows := []model.MonitorBase{}
if err := tx.Order("create_time asc").Find(&rows).Error; err != nil {
// DelMonitorIO 删除监控_IO logger.Errorf("query find err => %v", err.Error())
DelMonitorIO(ltTime int64) error return rows
}
// SelectMonitorIO 查询监控_IO return rows
SelectMonitorIO(query map[string]any) []model.MonitorIO }
// BatchCreateMonitorNet 批量创建监控_网络 // InsertByBase 创建监控_基本信息
BatchCreateMonitorNet(netList []model.MonitorNetwork) error func (r Monitor) InsertByBase(param model.MonitorBase) error {
return db.DB("").Create(&param).Error
// DelMonitorNet 删除监控_网络 }
DelMonitorNet(ltTime int64) error
// DeleteByBase 删除监控_基本信息
// SelectMonitorNetwork 查询监控_网络 func (r Monitor) DeleteByBase(ltTime int64) error {
SelectMonitorNetwork(query map[string]any) []model.MonitorNetwork return db.DB("").Where("create_time < ?", ltTime).Delete(&model.MonitorBase{}).Error
}
// SelectByIO 查询监控_IO
func (r Monitor) SelectByIO(query map[string]any) []model.MonitorIO {
tx := db.DB("").Model(&model.MonitorIO{})
// 查询条件拼接
if v, ok := query["name"]; ok && v != "" {
tx = tx.Where("name = ?", v)
}
if v, ok := query["neType"]; ok && v != "" {
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
tx = tx.Where("ne_id = ?", v)
}
tx.Where("create_time >= ? and create_time <= ?", query["beginTime"], query["endTime"])
// 查询数据
rows := []model.MonitorIO{}
if err := tx.Order("create_time asc").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// BatchInsertByIO 批量创建监控_IO
func (r Monitor) BatchInsertByIO(arr []model.MonitorIO) error {
return db.DB("").CreateInBatches(arr, 100).Error
}
// DeleteByIO 删除监控_IO
func (r Monitor) DeleteByIO(ltTime int64) error {
return db.DB("").Where("create_time < ?", ltTime).Delete(&model.MonitorIO{}).Error
}
// SelectByNetwork 查询监控_网络
func (r Monitor) SelectByNetwork(query map[string]any) []model.MonitorNetwork {
tx := db.DB("").Model(&model.MonitorNetwork{})
// 查询条件拼接
if v, ok := query["name"]; ok && v != "" {
tx = tx.Where("name = ?", v)
} else {
tx = tx.Where("name = 'all'")
}
if v, ok := query["neType"]; ok && v != "" {
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
tx = tx.Where("ne_id = ?", v)
}
tx.Where("create_time >= ? and create_time <= ?", query["beginTime"], query["endTime"])
// 查询数据
rows := []model.MonitorNetwork{}
if err := tx.Order("create_time asc").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// BatchInsertByNetwork 批量创建监控_网络
func (r Monitor) BatchInsertByNetwork(arr []model.MonitorNetwork) error {
return db.DB("").CreateInBatches(arr, 100).Error
}
// DeleteByNetwork 删除监控_网络
func (r Monitor) DeleteByNetwork(ltTime int64) error {
return db.DB("").Where("create_time < ?", ltTime).Delete(&model.MonitorNetwork{}).Error
} }

View File

@@ -1,105 +0,0 @@
package repository
import (
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/modules/monitor/model"
"gorm.io/gorm"
)
// 实例化数据层 MonitorImpl 结构体
var NewMonitorImpl = &MonitorImpl{
db: datasource.DefaultDB,
}
// MonitorImpl 监控服务资源相关信息 数据层处理
type MonitorImpl struct {
// 数据库实例
db func() *gorm.DB
}
// CreateMonitorBase 创建监控_基本信息
func (r *MonitorImpl) CreateMonitorBase(m model.MonitorBase) error {
return r.db().Create(&m).Error
}
// DelMonitorBase 删除监控_基本信息
func (r *MonitorImpl) DelMonitorBase(ltTime int64) error {
return r.db().Where("create_time < ?", ltTime).Delete(&model.MonitorBase{}).Error
}
// SelectMonitorBase 查询监控_基本信息
func (r *MonitorImpl) SelectMonitorBase(query map[string]any) []model.MonitorBase {
var bases []model.MonitorBase
dbConn := r.db()
if query["neType"] != "" && query["neId"] != "" {
dbConn = dbConn.Where("ne_type = ? and ne_id = ?", query["neType"], query["neId"])
}
dbConn = dbConn.Where("create_time >= ? and create_time <= ?", query["startTime"], query["endTime"])
err := dbConn.Order("create_time asc").Find(&bases).Error
if err != nil {
logger.Errorf("SelectMonitorBase %v", err)
return bases
}
return bases
}
// BatchCreateMonitorIO 批量创建监控_IO
func (r *MonitorImpl) BatchCreateMonitorIO(ioList []model.MonitorIO) error {
return r.db().CreateInBatches(ioList, len(ioList)).Error
}
// DelMonitorIO 删除监控_IO
func (r *MonitorImpl) DelMonitorIO(ltTime int64) error {
return r.db().Where("create_time < ?", ltTime).Delete(&model.MonitorIO{}).Error
}
// SelectMonitorIO 查询监控_IO
func (r *MonitorImpl) SelectMonitorIO(query map[string]any) []model.MonitorIO {
var ios []model.MonitorIO
dbConn := r.db()
if query["name"] != "" {
dbConn = dbConn.Where("name = ?", query["name"])
}
if query["neType"] != "" && query["neId"] != "" {
dbConn = dbConn.Where("ne_type = ? and ne_id = ?", query["neType"], query["neId"])
}
dbConn = dbConn.Where("create_time >= ? and create_time <= ?", query["startTime"], query["endTime"])
err := dbConn.Order("create_time asc").Find(&ios).Error
if err != nil {
logger.Errorf("SelectMonitorIO %v", err)
return ios
}
return ios
}
// BatchCreateMonitorNet 批量创建监控_网络
func (r *MonitorImpl) BatchCreateMonitorNet(netList []model.MonitorNetwork) error {
return r.db().CreateInBatches(netList, len(netList)).Error
}
// DelMonitorNet 删除监控_网络
func (r *MonitorImpl) DelMonitorNet(ltTime int64) error {
return r.db().Where("create_time < ?", ltTime).Delete(&model.MonitorNetwork{}).Error
}
// SelectMonitorNetwork 查询监控_网络
func (r *MonitorImpl) SelectMonitorNetwork(query map[string]any) []model.MonitorNetwork {
var networks []model.MonitorNetwork
dbConn := r.db()
if query["name"] != "" {
dbConn = dbConn.Where("name = ?", query["name"])
} else {
dbConn = dbConn.Where("name = ?", "all")
}
if query["neType"] != "" && query["neId"] != "" {
dbConn = dbConn.Where("ne_type = ? and ne_id = ?", query["neType"], query["neId"])
}
dbConn = dbConn.Where("create_time >= ? and create_time <= ?", query["startTime"], query["endTime"])
err := dbConn.Order("create_time asc").Find(&networks).Error
if err != nil {
logger.Errorf("SelectMonitorNetwork %v", err)
return networks
}
return networks
}

View File

@@ -1,29 +1,164 @@
package repository package repository
import ( import (
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
) )
// ISysJob 调度任务表 数据层接口 // NewSysJob 实例化数据层
type ISysJob interface { var NewSysJob = &SysJob{}
// SelectJobPage 分页查询调度任务集合
SelectJobPage(query map[string]any) map[string]any
// SelectJobList 查询调度任务集合 // SysJob 调度任务 数据层处理
SelectJobList(sysJob model.SysJob) []model.SysJob type SysJob struct{}
// SelectJobByIds 通过调度ID查询调度任务信息 // SelectByPage 分页查询集合
SelectJobByIds(jobIds []string) []model.SysJob func (r SysJob) SelectByPage(query map[string]string) ([]model.SysJob, int64) {
tx := db.DB("").Model(&model.SysJob{})
// 查询条件拼接
if v, ok := query["jobName"]; ok && v != "" {
tx = tx.Where("job_name like concat(?, '%')", v)
}
if v, ok := query["jobGroup"]; ok && v != "" {
tx = tx.Where("job_group = ?", v)
}
if v, ok := query["invokeTarget"]; ok && v != "" {
tx = tx.Where("invoke_target like concat(?, '%')", v)
}
if v, ok := query["statusFlag"]; ok && v != "" {
tx = tx.Where("status_flag = ?", v)
}
// CheckUniqueJob 校验调度任务是否唯一 // 查询结果
CheckUniqueJob(sysJob model.SysJob) string var total int64 = 0
rows := []model.SysJob{}
// InsertJob 新增调度任务信息 // 查询数量为0直接返回
InsertJob(sysJob model.SysJob) string if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// UpdateJob 修改调度任务信息 // 查询数据分页
UpdateJob(sysJob model.SysJob) int64 pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
// DeleteJobByIds 批量删除调度任务信息 err := tx.Find(&rows).Error
DeleteJobByIds(jobIds []string) int64 if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// Select 查询集合
func (r SysJob) Select(sysJob model.SysJob) []model.SysJob {
tx := db.DB("").Model(&model.SysJob{})
// 查询条件拼接
if sysJob.JobName != "" {
tx = tx.Where("job_name like concat(?, '%')", sysJob.JobName)
}
if sysJob.JobGroup != "" {
tx = tx.Where("job_group = ?", sysJob.JobGroup)
}
if sysJob.InvokeTarget != "" {
tx = tx.Where("invoke_target like concat(?, '%')", sysJob.InvokeTarget)
}
if sysJob.StatusFlag != "" {
tx = tx.Where("status_flag = ?", sysJob.StatusFlag)
}
// 查询数据
rows := []model.SysJob{}
if err := tx.Order("job_id asc").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// SelectByIds 通过ID查询信息
func (r SysJob) SelectByIds(jobIds []int64) []model.SysJob {
rows := []model.SysJob{}
if len(jobIds) <= 0 {
return rows
}
tx := db.DB("").Model(&model.SysJob{})
// 构建查询条件
tx = tx.Where("job_id in ?", jobIds)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息 返回新增数据ID
func (r SysJob) Insert(sysJob model.SysJob) int64 {
if sysJob.CreateBy != "" {
ms := time.Now().UnixMilli()
sysJob.UpdateBy = sysJob.CreateBy
sysJob.UpdateTime = ms
sysJob.CreateTime = ms
}
// 执行插入
if err := db.DB("").Create(&sysJob).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return sysJob.JobId
}
// Update 修改信息
func (r SysJob) Update(sysJob model.SysJob) int64 {
if sysJob.JobId <= 0 {
return 0
}
if sysJob.UpdateBy != "" {
sysJob.UpdateTime = time.Now().UnixMilli()
}
tx := db.DB("").Model(&model.SysJob{})
// 构建查询条件
tx = tx.Where("job_id = ?", sysJob.JobId)
tx = tx.Omit("config_id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(sysJob).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r SysJob) DeleteByIds(jobIds []int64) int64 {
if len(jobIds) <= 0 {
return 0
}
tx := db.DB("").Where("job_id in ?", jobIds)
if err := tx.Delete(&model.SysJob{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// CheckUnique 校验信息是否唯一
func (r SysJob) CheckUnique(sysJob model.SysJob) int64 {
tx := db.DB("").Model(&model.SysJob{})
// 查询条件拼接
if sysJob.JobName != "" {
tx = tx.Where("job_name = ?", sysJob.JobName)
}
if sysJob.JobGroup != "" {
tx = tx.Where("job_group = ?", sysJob.JobGroup)
}
// 查询数据
var id int64 = 0
if err := tx.Select("job_id").Limit(1).Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
}
return id
} }

View File

@@ -1,343 +0,0 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/monitor/model"
)
// 实例化数据层 SysJobImpl 结构体
var NewSysJobImpl = &SysJobImpl{
selectSql: `select job_id, job_name, job_group, invoke_target, target_params, cron_expression,
misfire_policy, concurrent, status, save_log, create_by, create_time, remark from sys_job`,
resultMap: map[string]string{
"job_id": "JobID",
"job_name": "JobName",
"job_group": "JobGroup",
"invoke_target": "InvokeTarget",
"target_params": "TargetParams",
"cron_expression": "CronExpression",
"misfire_policy": "MisfirePolicy",
"concurrent": "Concurrent",
"status": "Status",
"save_log": "SaveLog",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
"remark": "Remark",
},
}
// SysJobImpl 调度任务表 数据层处理
type SysJobImpl struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
// convertResultRows 将结果记录转实体结果组
func (r *SysJobImpl) convertResultRows(rows []map[string]any) []model.SysJob {
arr := make([]model.SysJob, 0)
for _, row := range rows {
sysJob := model.SysJob{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&sysJob, keyMapper, value)
}
}
arr = append(arr, sysJob)
}
return arr
}
// SelectJobPage 分页查询调度任务集合
func (r *SysJobImpl) SelectJobPage(query map[string]any) map[string]any {
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["jobName"]; ok && v != "" {
conditions = append(conditions, "job_name like concat(?, '%')")
params = append(params, v)
}
if v, ok := query["jobGroup"]; ok && v != "" {
conditions = append(conditions, "job_group = ?")
params = append(params, v)
}
if v, ok := query["invokeTarget"]; ok && v != "" {
conditions = append(conditions, "invoke_target like concat(?, '%')")
params = append(params, v)
}
if v, ok := query["status"]; ok && v != "" {
conditions = append(conditions, "status = ?")
params = append(params, v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询结果
result := map[string]any{
"total": 0,
"rows": []model.SysJob{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from sys_job"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
if err != nil {
logger.Errorf("total err => %v", err)
return result
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
}
// SelectJobList 查询调度任务集合
func (r *SysJobImpl) SelectJobList(sysJob model.SysJob) []model.SysJob {
// 查询条件拼接
var conditions []string
var params []any
if sysJob.JobName != "" {
conditions = append(conditions, "job_name like concat(?, '%')")
params = append(params, sysJob.JobName)
}
if sysJob.JobGroup != "" {
conditions = append(conditions, "job_group = ?")
params = append(params, sysJob.JobGroup)
}
if sysJob.InvokeTarget != "" {
conditions = append(conditions, "invoke_target like concat(?, '%')")
params = append(params, sysJob.InvokeTarget)
}
if sysJob.Status != "" {
conditions = append(conditions, "status = ?")
params = append(params, sysJob.Status)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := r.selectSql + whereSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.SysJob{}
}
// 转换实体
return r.convertResultRows(results)
}
// SelectJobByIds 通过调度ID查询调度任务信息
func (r *SysJobImpl) SelectJobByIds(jobIds []string) []model.SysJob {
placeholder := repo.KeyPlaceholderByQuery(len(jobIds))
querySql := r.selectSql + " where job_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(jobIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.SysJob{}
}
// 转换实体
return r.convertResultRows(results)
}
// CheckUniqueJob 校验调度任务是否唯一
func (r *SysJobImpl) CheckUniqueJob(sysJob model.SysJob) string {
// 查询条件拼接
var conditions []string
var params []any
if sysJob.JobName != "" {
conditions = append(conditions, "job_name = ?")
params = append(params, sysJob.JobName)
}
if sysJob.JobGroup != "" {
conditions = append(conditions, "job_group = ?")
params = append(params, sysJob.JobGroup)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} else {
return ""
}
// 查询数据
querySql := "select job_id as 'str' from sys_job " + whereSql + " limit 1"
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err %v", err)
return ""
}
if len(results) > 0 {
return fmt.Sprint(results[0]["str"])
}
return ""
}
// InsertJob 新增调度任务信息
func (r *SysJobImpl) InsertJob(sysJob model.SysJob) string {
// 参数拼接
params := make(map[string]any)
if sysJob.JobID != "" {
params["job_id"] = sysJob.JobID
}
if sysJob.JobName != "" {
params["job_name"] = sysJob.JobName
}
if sysJob.JobGroup != "" {
params["job_group"] = sysJob.JobGroup
}
if sysJob.InvokeTarget != "" {
params["invoke_target"] = sysJob.InvokeTarget
}
params["target_params"] = sysJob.TargetParams
if sysJob.CronExpression != "" {
params["cron_expression"] = sysJob.CronExpression
}
if sysJob.MisfirePolicy != "" {
params["misfire_policy"] = sysJob.MisfirePolicy
}
if sysJob.Concurrent != "" {
params["concurrent"] = sysJob.Concurrent
}
if sysJob.Status != "" {
params["status"] = sysJob.Status
}
if sysJob.SaveLog != "" {
params["save_log"] = sysJob.SaveLog
}
params["remark"] = sysJob.Remark
if sysJob.CreateBy != "" {
params["create_by"] = sysJob.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into sys_job (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// UpdateJob 修改调度任务信息
func (r *SysJobImpl) UpdateJob(sysJob model.SysJob) int64 {
// 参数拼接
params := make(map[string]any)
if sysJob.JobName != "" {
params["job_name"] = sysJob.JobName
}
if sysJob.JobGroup != "" {
params["job_group"] = sysJob.JobGroup
}
if sysJob.InvokeTarget != "" {
params["invoke_target"] = sysJob.InvokeTarget
}
params["target_params"] = sysJob.TargetParams
if sysJob.CronExpression != "" {
params["cron_expression"] = sysJob.CronExpression
}
if sysJob.MisfirePolicy != "" {
params["misfire_policy"] = sysJob.MisfirePolicy
}
if sysJob.Concurrent != "" {
params["concurrent"] = sysJob.Concurrent
}
if sysJob.Status != "" {
params["status"] = sysJob.Status
}
if sysJob.SaveLog != "" {
params["save_log"] = sysJob.SaveLog
}
params["remark"] = sysJob.Remark
if sysJob.UpdateBy != "" {
params["update_by"] = sysJob.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update sys_job set " + strings.Join(keys, ",") + " where job_id = ?"
// 执行更新
values = append(values, sysJob.JobID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
}
return rows
}
// DeleteJobByIds 批量删除调度任务信息
func (r *SysJobImpl) DeleteJobByIds(jobIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(jobIds))
sql := "delete from sys_job where job_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(jobIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
return 0
}
return results
}

View File

@@ -1,26 +1,144 @@
package repository package repository
import ( import (
"fmt"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
) )
// 调度任务日志表 数据层接口 // NewSysJobLog 实例化数据层
type ISysJobLog interface { var NewSysJobLog = &SysJobLog{}
// 分页查询调度任务日志集合
SelectJobLogPage(query map[string]any) map[string]any
// 查询调度任务日志集合 // SysJobLog 调度任务日志表 数据层处理
SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog type SysJobLog struct{}
// 通过调度ID查询调度任务日志信息 // SelectByPage 分页查询集合
SelectJobLogById(jobLogId string) model.SysJobLog func (r SysJobLog) SelectByPage(query map[string]string) ([]model.SysJobLog, int64) {
tx := db.DB("").Model(&model.SysJobLog{})
// 查询条件拼接
if v, ok := query["jobName"]; ok && v != "" {
tx = tx.Where("job_name = ?", v)
}
if v, ok := query["jobGroup"]; ok && v != "" {
tx = tx.Where("job_group = ?", v)
}
if v, ok := query["statusFlag"]; ok && v != "" {
tx = tx.Where("status_flag = ?", v)
}
if v, ok := query["invokeTarget"]; ok && v != "" {
tx = tx.Where("invoke_target like concat(?, '%')", v)
}
if v, ok := query["beginTime"]; ok && v != "" {
if len(v) == 10 {
v = fmt.Sprintf("%s000", v)
tx = tx.Where("create_time >= ?", v)
} else if len(v) == 13 {
tx = tx.Where("create_time >= ?", v)
}
}
if v, ok := query["endTime"]; ok && v != "" {
if len(v) == 10 {
v = fmt.Sprintf("%s999", v)
tx = tx.Where("create_time <= ?", v)
} else if len(v) == 13 {
tx = tx.Where("create_time <= ?", v)
}
}
// 新增调度任务日志信息 // 查询结果
InsertJobLog(sysJobLog model.SysJobLog) string var total int64 = 0
rows := []model.SysJobLog{}
// 批量删除调度任务日志信息 // 查询数量为0直接返回
DeleteJobLogByIds(jobLogId []string) int64 if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 清空调度任务日志 // 查询数据分页
CleanJobLog() error pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// Select 查询集合
func (r SysJobLog) Select(sysJobLog model.SysJobLog) []model.SysJobLog {
tx := db.DB("").Model(&model.SysJobLog{})
// 查询条件拼接
if sysJobLog.JobName != "" {
tx = tx.Where("job_name like concat(?, '%')", sysJobLog.JobName)
}
if sysJobLog.JobGroup != "" {
tx = tx.Where("job_group = ?", sysJobLog.JobGroup)
}
if sysJobLog.StatusFlag != "" {
tx = tx.Where("status_flag = ?", sysJobLog.StatusFlag)
}
if sysJobLog.InvokeTarget != "" {
tx = tx.Where("invoke_target like concat(?, '%')", sysJobLog.InvokeTarget)
}
// 查询数据
rows := []model.SysJobLog{}
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// SelectById 通过ID查询信息
func (r SysJobLog) SelectById(logId int64) model.SysJobLog {
item := model.SysJobLog{}
if logId <= 0 {
return item
}
tx := db.DB("").Model(&model.SysJobLog{})
// 构建查询条件
tx = tx.Where("log_id = ?", logId)
// 查询数据
if err := tx.Limit(1).Find(&item).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return item
}
return item
}
// Insert 新增信息
func (r SysJobLog) Insert(sysJobLog model.SysJobLog) int64 {
// 执行插入
if err := db.DB("").Create(&sysJobLog).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return sysJobLog.LogId
}
// DeleteByIds 批量删除信息
func (r SysJobLog) DeleteByIds(logIds []int64) int64 {
if len(logIds) <= 0 {
return 0
}
tx := db.DB("").Where("log_id in ?", logIds)
if err := tx.Delete(&model.SysJobLog{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// Clean 清空集合数据
func (r SysJobLog) Clean() int64 {
tx := db.DB("").Delete(&model.SysJobLog{})
if err := tx.Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
} }

View File

@@ -1,269 +0,0 @@
package repository
import (
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/monitor/model"
)
// 实例化数据层 SysJobLogImpl 结构体
var NewSysJobLogImpl = &SysJobLogImpl{
selectSql: `select job_log_id, job_name, job_group, invoke_target,
target_params, job_msg, status, create_time, cost_time from sys_job_log`,
resultMap: map[string]string{
"job_log_id": "JobLogID",
"job_name": "JobName",
"job_group": "JobGroup",
"invoke_target": "InvokeTarget",
"target_params": "TargetParams",
"job_msg": "JobMsg",
"status": "Status",
"create_time": "CreateTime",
"cost_time": "CostTime",
},
}
// SysJobLogImpl 调度任务日志表 数据层处理
type SysJobLogImpl struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
// convertResultRows 将结果记录转实体结果组
func (r *SysJobLogImpl) convertResultRows(rows []map[string]any) []model.SysJobLog {
arr := make([]model.SysJobLog, 0)
for _, row := range rows {
sysJobLog := model.SysJobLog{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&sysJobLog, keyMapper, value)
}
}
arr = append(arr, sysJobLog)
}
return arr
}
// 分页查询调度任务日志集合
func (r *SysJobLogImpl) SelectJobLogPage(query map[string]any) map[string]any {
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["jobName"]; ok && v != "" {
conditions = append(conditions, "job_name = ?")
params = append(params, v)
}
if v, ok := query["jobGroup"]; ok && v != "" {
conditions = append(conditions, "job_group = ?")
params = append(params, v)
}
if v, ok := query["status"]; ok && v != "" {
conditions = append(conditions, "status = ?")
params = append(params, v)
}
if v, ok := query["invokeTarget"]; ok && v != "" {
conditions = append(conditions, "invoke_target like concat(?, '%')")
params = append(params, v)
}
beginTime, ok := query["beginTime"]
if !ok {
beginTime, ok = query["params[beginTime]"]
}
if ok && beginTime != "" {
conditions = append(conditions, "create_time >= ?")
params = append(params, parse.Number(beginTime.(string)))
}
endTime, ok := query["endTime"]
if !ok {
endTime, ok = query["params[endTime]"]
}
if ok && endTime != "" {
conditions = append(conditions, "create_time <= ?")
params = append(params, parse.Number(endTime.(string)))
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询结果
result := map[string]any{
"total": 0,
"rows": []model.SysJobLog{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from sys_job_log"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
if err != nil {
logger.Errorf("total err => %v", err)
return result
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " order by job_log_id desc limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
}
// 查询调度任务日志集合
func (r *SysJobLogImpl) SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog {
// 查询条件拼接
var conditions []string
var params []any
if sysJobLog.JobName != "" {
conditions = append(conditions, "job_name like concat(?, '%')")
params = append(params, sysJobLog.JobName)
}
if sysJobLog.JobGroup != "" {
conditions = append(conditions, "job_group = ?")
params = append(params, sysJobLog.JobGroup)
}
if sysJobLog.Status != "" {
conditions = append(conditions, "status = ?")
params = append(params, sysJobLog.Status)
}
if sysJobLog.InvokeTarget != "" {
conditions = append(conditions, "invoke_target like concat(?, '%')")
params = append(params, sysJobLog.InvokeTarget)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := r.selectSql + whereSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.SysJobLog{}
}
// 转换实体
return r.convertResultRows(results)
}
// 通过调度ID查询调度任务日志信息
func (r *SysJobLogImpl) SelectJobLogById(jobLogId string) model.SysJobLog {
querySql := r.selectSql + " where job_log_id = ?"
results, err := datasource.RawDB("", querySql, []any{jobLogId})
if err != nil {
logger.Errorf("query err => %v", err)
return model.SysJobLog{}
}
// 转换实体
rows := r.convertResultRows(results)
if len(rows) > 0 {
return rows[0]
}
return model.SysJobLog{}
}
// 新增调度任务日志信息
func (r *SysJobLogImpl) InsertJobLog(sysJobLog model.SysJobLog) string {
// 参数拼接
params := make(map[string]any)
params["create_time"] = time.Now().UnixMilli()
if sysJobLog.JobLogID != "" {
params["job_log_id"] = sysJobLog.JobLogID
}
if sysJobLog.JobName != "" {
params["job_name"] = sysJobLog.JobName
}
if sysJobLog.JobGroup != "" {
params["job_group"] = sysJobLog.JobGroup
}
if sysJobLog.InvokeTarget != "" {
params["invoke_target"] = sysJobLog.InvokeTarget
}
if sysJobLog.TargetParams != "" {
params["target_params"] = sysJobLog.TargetParams
}
if sysJobLog.JobMsg != "" {
params["job_msg"] = sysJobLog.JobMsg
}
if sysJobLog.Status != "" {
params["status"] = sysJobLog.Status
}
if sysJobLog.CostTime > 0 {
params["cost_time"] = sysJobLog.CostTime
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into sys_job_log (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// 批量删除调度任务日志信息
func (r *SysJobLogImpl) DeleteJobLogByIds(jobLogIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(jobLogIds))
sql := "delete from sys_job_log where job_log_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(jobLogIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
return 0
}
return results
}
// 清空调度任务日志
func (r *SysJobLogImpl) CleanJobLog() error {
sql := "truncate table sys_job_log"
_, err := datasource.ExecDB("", sql, []any{})
return err
}

View File

@@ -9,6 +9,7 @@ import (
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/repository" "be.ems/src/modules/monitor/repository"
systemService "be.ems/src/modules/system/service" systemService "be.ems/src/modules/system/service"
"github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk" "github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/load" "github.com/shirou/gopsutil/v4/load"
@@ -18,18 +19,16 @@ import (
// 实例化服务层 Monitor 结构体 // 实例化服务层 Monitor 结构体
var NewMonitor = &Monitor{ var NewMonitor = &Monitor{
sysConfigService: systemService.NewSysConfigImpl, sysConfigService: systemService.NewSysConfig,
monitorRepository: repository.NewMonitorImpl, monitorRepository: repository.NewMonitor,
diskIO: make(chan []disk.IOCountersStat, 2), diskIO: make(chan []disk.IOCountersStat, 2),
netIO: make(chan []net.IOCountersStat, 2), netIO: make(chan []net.IOCountersStat, 2),
} }
// Monitor 服务器系统相关信息 服务层处理 // Monitor 服务器系统相关信息 服务层处理
type Monitor struct { type Monitor struct {
// 参数配置服务 sysConfigService *systemService.SysConfig // 参数配置服务
sysConfigService systemService.ISysConfig monitorRepository *repository.Monitor // 监控服务资源数据信息
// 监控服务资源数据信息
monitorRepository repository.IMonitor
// 磁盘网络IO 数据通道 // 磁盘网络IO 数据通道
diskIO chan ([]disk.IOCountersStat) diskIO chan ([]disk.IOCountersStat)
netIO chan ([]net.IOCountersStat) netIO chan ([]net.IOCountersStat)
@@ -59,8 +58,8 @@ func (s *Monitor) RunMonitor() {
memoryInfo, _ := mem.VirtualMemory() memoryInfo, _ := mem.VirtualMemory()
itemBase.Memory = memoryInfo.UsedPercent itemBase.Memory = memoryInfo.UsedPercent
if err := s.monitorRepository.CreateMonitorBase(itemBase); err != nil { if err := s.monitorRepository.InsertByBase(itemBase); err != nil {
logger.Errorf("CreateMonitorBase err: %v", err) logger.Errorf("InsertByBase err: %v", err)
} }
// 将当前资源发送到chan中处理保存 // 将当前资源发送到chan中处理保存
@@ -68,13 +67,13 @@ func (s *Monitor) RunMonitor() {
s.loadNetIO() s.loadNetIO()
// 监控系统资源-保留天数 // 监控系统资源-保留天数
storeDays := s.sysConfigService.SelectConfigValueByKey("monitor.sysResource.storeDays") storeDays := s.sysConfigService.FindValueByKey("monitor.sysResource.storeDays")
if storeDays != "" { if storeDays != "" {
storeDays, _ := strconv.Atoi(storeDays) storeDays, _ := strconv.Atoi(storeDays)
ltTime := time.Now().AddDate(0, 0, -storeDays).UnixMilli() ltTime := time.Now().AddDate(0, 0, -storeDays).UnixMilli()
_ = s.monitorRepository.DelMonitorBase(ltTime) _ = s.monitorRepository.DeleteByBase(ltTime)
_ = s.monitorRepository.DelMonitorIO(ltTime) _ = s.monitorRepository.DeleteByIO(ltTime)
_ = s.monitorRepository.DelMonitorNet(ltTime) _ = s.monitorRepository.DeleteByNetwork(ltTime)
} }
} }
@@ -171,8 +170,8 @@ func (s *Monitor) saveIODataToDB(ctx context.Context, interval float64) {
} }
} }
} }
if err := s.monitorRepository.BatchCreateMonitorIO(ioList); err != nil { if err := s.monitorRepository.BatchInsertByIO(ioList); err != nil {
logger.Errorf("BatchCreateMonitorIO err: %v", err) logger.Errorf("BatchInsertByIO err: %v", err)
} }
s.diskIO <- ioStat2 s.diskIO <- ioStat2
} }
@@ -214,8 +213,8 @@ func (s *Monitor) saveNetDataToDB(ctx context.Context, interval float64) {
} }
} }
if err := s.monitorRepository.BatchCreateMonitorNet(netList); err != nil { if err := s.monitorRepository.BatchInsertByNetwork(netList); err != nil {
logger.Errorf("BatchCreateMonitorNet err: %v", err) logger.Errorf("BatchInsertByNetwork err: %v", err)
} }
s.netIO <- netStat2 s.netIO <- netStat2
} }
@@ -223,10 +222,10 @@ func (s *Monitor) saveNetDataToDB(ctx context.Context, interval float64) {
} }
} }
// SelectMonitorInfo 查询监控资源信息 // FindInfo 查询监控资源信息
func (s *Monitor) SelectMonitorInfo(query map[string]any) map[string]any { func (s *Monitor) FindInfo(query map[string]any) map[string]any {
infoType := query["type"] infoType := query["type"]
startTimeMilli := query["startTime"] beginTimeMilli := query["beginTime"]
endTimeMilli := query["endTime"] endTimeMilli := query["endTime"]
neType := query["neType"] neType := query["neType"]
neId := query["neId"] neId := query["neId"]
@@ -237,8 +236,8 @@ func (s *Monitor) SelectMonitorInfo(query map[string]any) map[string]any {
// 基本信息 // 基本信息
if infoType == "all" || infoType == "load" || infoType == "cpu" || infoType == "memory" { if infoType == "all" || infoType == "load" || infoType == "cpu" || infoType == "memory" {
rows := s.monitorRepository.SelectMonitorBase(map[string]any{ rows := s.monitorRepository.SelectByBase(map[string]any{
"startTime": startTimeMilli, "beginTime": beginTimeMilli,
"endTime": endTimeMilli, "endTime": endTimeMilli,
"neType": neType, "neType": neType,
"neId": neId, "neId": neId,
@@ -248,8 +247,8 @@ func (s *Monitor) SelectMonitorInfo(query map[string]any) map[string]any {
// 磁盘IO // 磁盘IO
if infoType == "all" || infoType == "io" { if infoType == "all" || infoType == "io" {
rows := s.monitorRepository.SelectMonitorIO(map[string]any{ rows := s.monitorRepository.SelectByIO(map[string]any{
"startTime": startTimeMilli, "beginTime": beginTimeMilli,
"endTime": endTimeMilli, "endTime": endTimeMilli,
"neType": neType, "neType": neType,
"neId": neId, "neId": neId,
@@ -260,8 +259,8 @@ func (s *Monitor) SelectMonitorInfo(query map[string]any) map[string]any {
// 网络 // 网络
if infoType == "all" || infoType == "network" { if infoType == "all" || infoType == "network" {
rows := s.monitorRepository.SelectMonitorNetwork(map[string]any{ rows := s.monitorRepository.SelectByNetwork(map[string]any{
"startTime": startTimeMilli, "beginTime": beginTimeMilli,
"endTime": endTimeMilli, "endTime": endTimeMilli,
"neType": neType, "neType": neType,
"neId": neId, "neId": neId,

View File

@@ -2,131 +2,112 @@ package service
import ( import (
"fmt" "fmt"
"strconv"
"be.ems/src/framework/constants/common" "be.ems/src/framework/constants"
"be.ems/src/framework/cron" "be.ems/src/framework/cron"
"be.ems/src/framework/utils/file"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/repository" "be.ems/src/modules/monitor/repository"
systemService "be.ems/src/modules/system/service"
) )
// 实例化服务层 SysJob 结构体 // NewSysJob 服务层实例化
var NewSysJob = &SysJob{ var NewSysJob = &SysJob{
sysJobRepository: repository.NewSysJobImpl, sysJobRepository: repository.NewSysJob,
sysDictTypeService: systemService.NewSysDictType,
} }
// SysJob 调度任务 服务层处理 // SysJob 调度任务 服务层处理
type SysJob struct { type SysJob struct {
// 调度任务数据信息 sysJobRepository *repository.SysJob // 调度任务数据信息
sysJobRepository repository.ISysJob sysDictTypeService *systemService.SysDictType // 字典类型服务
} }
// SelectJobPage 分页查询调度任务集合 // FindByPage 分页查询
func (r *SysJob) SelectJobPage(query map[string]any) map[string]any { func (s SysJob) FindByPage(query map[string]string) ([]model.SysJob, int64) {
return r.sysJobRepository.SelectJobPage(query) return s.sysJobRepository.SelectByPage(query)
} }
// SelectJobList 查询调度任务集合 // Find 查询
func (r *SysJob) SelectJobList(sysJob model.SysJob) []model.SysJob { func (s SysJob) Find(sysJob model.SysJob) []model.SysJob {
return r.sysJobRepository.SelectJobList(sysJob) return s.sysJobRepository.Select(sysJob)
} }
// SelectJobById 通过调度ID查询调度任务信息 // FindById 通过ID查询
func (r *SysJob) SelectJobById(jobId string) model.SysJob { func (s SysJob) FindById(jobId int64) model.SysJob {
if jobId == "" { if jobId <= 0 {
return model.SysJob{} return model.SysJob{}
} }
jobs := r.sysJobRepository.SelectJobByIds([]string{jobId}) jobs := s.sysJobRepository.SelectByIds([]int64{jobId})
if len(jobs) > 0 { if len(jobs) > 0 {
return jobs[0] return jobs[0]
} }
return model.SysJob{} return model.SysJob{}
} }
// CheckUniqueJobName 校验调度任务名称和组是否唯一 // Insert 新增
func (r *SysJob) CheckUniqueJobName(jobName, jobGroup, jobId string) bool { func (s SysJob) Insert(sysJob model.SysJob) int64 {
uniqueId := r.sysJobRepository.CheckUniqueJob(model.SysJob{ insertId := s.sysJobRepository.Insert(sysJob)
if insertId > 0 && sysJob.StatusFlag == constants.STATUS_YES {
sysJob.JobId = insertId
s.insertQueueJob(sysJob, true)
}
return insertId
}
// Update 修改
func (s SysJob) Update(sysJob model.SysJob) int64 {
rows := s.sysJobRepository.Update(sysJob)
if rows > 0 {
//状态正常添加队列任务
if sysJob.StatusFlag == constants.STATUS_YES {
s.insertQueueJob(sysJob, true)
}
// 状态禁用删除队列任务
if sysJob.StatusFlag == constants.STATUS_NO {
s.deleteQueueJob(sysJob)
}
}
return rows
}
// DeleteByIds 批量删除
func (s SysJob) DeleteByIds(jobIds []int64) (int64, error) {
// 检查是否存在
jobs := s.sysJobRepository.SelectByIds(jobIds)
if len(jobs) <= 0 {
return 0, fmt.Errorf("没有权限访问调度任务数据!")
}
if len(jobs) == len(jobIds) {
// 清除任务
for _, job := range jobs {
s.deleteQueueJob(job)
}
return s.sysJobRepository.DeleteByIds(jobIds), nil
}
return 0, fmt.Errorf("删除调度任务信息失败!")
}
// CheckUniqueByJobName 校验调度任务名称和组是否唯一
func (s SysJob) CheckUniqueByJobName(jobName, jobGroup string, jobId int64) bool {
uniqueId := s.sysJobRepository.CheckUnique(model.SysJob{
JobName: jobName, JobName: jobName,
JobGroup: jobGroup, JobGroup: jobGroup,
}) })
if uniqueId == jobId { if uniqueId == jobId {
return true return true
} }
return uniqueId == "" return uniqueId == 0
} }
// InsertJob 新增调度任务信息 // Run 立即运行一次调度任务
func (r *SysJob) InsertJob(sysJob model.SysJob) string { func (s SysJob) Run(sysJob model.SysJob) bool {
insertId := r.sysJobRepository.InsertJob(sysJob) return s.insertQueueJob(sysJob, false)
if insertId == "" && sysJob.Status == common.STATUS_YES {
sysJob.JobID = insertId
r.insertQueueJob(sysJob, true)
}
return insertId
}
// UpdateJob 修改调度任务信息
func (r *SysJob) UpdateJob(sysJob model.SysJob) int64 {
rows := r.sysJobRepository.UpdateJob(sysJob)
if rows > 0 {
//状态正常添加队列任务
if sysJob.Status == common.STATUS_YES {
r.insertQueueJob(sysJob, true)
}
// 状态禁用删除队列任务
if sysJob.Status == common.STATUS_NO {
r.deleteQueueJob(sysJob)
}
}
return rows
}
// DeleteJobByIds 批量删除调度任务信息
func (r *SysJob) DeleteJobByIds(jobIds []string) (int64, error) {
// 检查是否存在
jobs := r.sysJobRepository.SelectJobByIds(jobIds)
if len(jobs) <= 0 {
// 没有可访问调度任务数据!
return 0, fmt.Errorf("there is no accessible scheduling task data")
}
if len(jobs) == len(jobIds) {
// 清除任务
for _, job := range jobs {
r.deleteQueueJob(job)
}
rows := r.sysJobRepository.DeleteJobByIds(jobIds)
return rows, nil
}
// 删除调度任务信息失败!
return 0, fmt.Errorf("failed to delete scheduling task information")
}
// ResetQueueJob 重置初始调度任务
func (r *SysJob) ResetQueueJob() {
// 获取注册的队列名称
queueNames := cron.QueueNames()
if len(queueNames) == 0 {
return
}
// 查询系统中定义状态为正常启用的任务
sysJobs := r.sysJobRepository.SelectJobList(model.SysJob{
Status: common.STATUS_YES,
})
for _, sysJob := range sysJobs {
for _, name := range queueNames {
if name == sysJob.InvokeTarget {
r.insertQueueJob(sysJob, true)
}
}
}
}
// RunQueueJob 立即运行一次调度任务
func (r *SysJob) RunQueueJob(sysJob model.SysJob) bool {
return r.insertQueueJob(sysJob, false)
} }
// insertQueueJob 添加调度任务 // insertQueueJob 添加调度任务
func (r *SysJob) insertQueueJob(sysJob model.SysJob, repeat bool) bool { func (s SysJob) insertQueueJob(sysJob model.SysJob, repeat bool) bool {
// 获取队列 Processor // 获取队列 Processor
queue := cron.GetQueue(sysJob.InvokeTarget) queue := cron.GetQueue(sysJob.InvokeTarget)
if queue.Name != sysJob.InvokeTarget { if queue.Name != sysJob.InvokeTarget {
@@ -143,7 +124,7 @@ func (r *SysJob) insertQueueJob(sysJob model.SysJob, repeat bool) bool {
if !repeat { if !repeat {
// 执行单次任务 // 执行单次任务
status := queue.RunJob(options, cron.JobOptions{ status := queue.RunJob(options, cron.JobOptions{
JobId: sysJob.JobID, JobId: fmt.Sprint(sysJob.JobId),
}) })
// 执行中或等待中的都返回正常 // 执行中或等待中的都返回正常
return status == cron.Active || status == cron.Waiting return status == cron.Active || status == cron.Waiting
@@ -151,19 +132,101 @@ func (r *SysJob) insertQueueJob(sysJob model.SysJob, repeat bool) bool {
// 执行重复任务 // 执行重复任务
queue.RunJob(options, cron.JobOptions{ queue.RunJob(options, cron.JobOptions{
JobId: sysJob.JobID, JobId: fmt.Sprint(sysJob.JobId),
Cron: sysJob.CronExpression, Cron: sysJob.CronExpression,
}) })
return true return true
} }
// deleteQueueJob 删除调度任务 // deleteQueueJob 删除调度任务
func (r *SysJob) deleteQueueJob(sysJob model.SysJob) bool { func (s SysJob) deleteQueueJob(sysJob model.SysJob) bool {
// 获取队列 Processor // 获取队列 Processor
queue := cron.GetQueue(sysJob.InvokeTarget) queue := cron.GetQueue(sysJob.InvokeTarget)
if queue.Name != sysJob.InvokeTarget { if queue.Name != sysJob.InvokeTarget {
return false return false
} }
return queue.RemoveJob(sysJob.JobID) return queue.RemoveJob(fmt.Sprint(sysJob.JobId))
}
// Reset 重置初始调度任务
func (s SysJob) Reset() {
// 获取注册的队列名称
queueNames := cron.QueueNames()
if len(queueNames) == 0 {
return
}
// 查询系统中定义状态为正常启用的任务
sysJobs := s.sysJobRepository.Select(model.SysJob{
StatusFlag: constants.STATUS_YES,
})
for _, sysJob := range sysJobs {
for _, name := range queueNames {
if name == sysJob.InvokeTarget {
s.deleteQueueJob(sysJob)
s.insertQueueJob(sysJob, true)
}
}
}
}
// ExportData 导出数据表格
func (s SysJob) ExportData(rows []model.SysJob, fileName string) (string, error) {
// 第一行表头标题
headerCells := map[string]string{
"A1": "任务编号",
"B1": "任务名称",
"C1": "任务组名",
"D1": "调用目标",
"E1": "传入参数",
"F1": "执行表达式",
"G1": "出错策略",
"H1": "并发执行",
"I1": "任务状态",
"J1": "备注说明",
}
// 读取任务组名字典数据
dictSysJobGroup := s.sysDictTypeService.FindDataByType("sys_job_group")
// 从第二行开始的数据
dataCells := make([]map[string]any, 0)
for i, row := range rows {
idx := strconv.Itoa(i + 2)
// 任务组名
sysJobGroup := ""
for _, v := range dictSysJobGroup {
if row.JobGroup == v.DataValue {
sysJobGroup = v.DataLabel
break
}
}
misfirePolicy := "放弃执行"
if row.MisfirePolicy == "1" {
misfirePolicy = "立即执行"
} else if row.MisfirePolicy == "2" {
misfirePolicy = "执行一次"
}
concurrent := "禁止"
if row.Concurrent == "1" {
concurrent = "允许"
}
// 状态
statusValue := "失败"
if row.StatusFlag == constants.STATUS_YES {
statusValue = "成功"
}
dataCells = append(dataCells, map[string]any{
"A" + idx: row.JobId,
"B" + idx: row.JobName,
"C" + idx: sysJobGroup,
"D" + idx: row.InvokeTarget,
"E" + idx: row.TargetParams,
"F" + idx: row.CronExpression,
"G" + idx: misfirePolicy,
"H" + idx: concurrent,
"I" + idx: statusValue,
"J" + idx: row.Remark,
})
}
// 导出数据表格
return file.WriteSheet(headerCells, dataCells, fileName, "")
} }

View File

@@ -1,42 +1,97 @@
package service package service
import ( import (
"strconv"
"be.ems/src/framework/constants"
"be.ems/src/framework/utils/date"
"be.ems/src/framework/utils/file"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
"be.ems/src/modules/monitor/repository" "be.ems/src/modules/monitor/repository"
systemService "be.ems/src/modules/system/service"
) )
// 实例化服务层 SysJobLog 结构体 // NewSysJobLog 服务层实例化
var NewSysJobLog = &SysJobLog{ var NewSysJobLog = &SysJobLog{
sysJobLogRepository: repository.NewSysJobLogImpl, sysJobLogRepository: repository.NewSysJobLog,
sysDictTypeService: systemService.NewSysDictType,
} }
// SysJobLog 调度任务日志 服务层处理 // SysJobLog 调度任务日志 服务层处理
type SysJobLog struct { type SysJobLog struct {
// 调度任务日志数据信息 sysJobLogRepository *repository.SysJobLog // 调度任务日志数据信息
sysJobLogRepository repository.ISysJobLog sysDictTypeService *systemService.SysDictType // 字典类型服务
} }
// SelectJobLogPage 分页查询调度任务日志集合 // FindByPage 分页查询
func (s *SysJobLog) SelectJobLogPage(query map[string]any) map[string]any { func (s SysJobLog) FindByPage(query map[string]string) ([]model.SysJobLog, int64) {
return s.sysJobLogRepository.SelectJobLogPage(query) return s.sysJobLogRepository.SelectByPage(query)
} }
// SelectJobLogList 查询调度任务日志集合 // Find 查询
func (s *SysJobLog) SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog { func (s SysJobLog) Find(sysJobLog model.SysJobLog) []model.SysJobLog {
return s.sysJobLogRepository.SelectJobLogList(sysJobLog) return s.sysJobLogRepository.Select(sysJobLog)
} }
// SelectJobLogById 通过调度ID查询调度任务日志信息 // FindById 通过ID查询
func (s *SysJobLog) SelectJobLogById(jobLogId string) model.SysJobLog { func (s SysJobLog) FindById(logId int64) model.SysJobLog {
return s.sysJobLogRepository.SelectJobLogById(jobLogId) return s.sysJobLogRepository.SelectById(logId)
} }
// DeleteJobLogByIds 批量删除调度任务日志信息 // RemoveByIds 批量删除
func (s *SysJobLog) DeleteJobLogByIds(jobLogIds []string) int64 { func (s SysJobLog) DeleteByIds(logIds []int64) int64 {
return s.sysJobLogRepository.DeleteJobLogByIds(jobLogIds) return s.sysJobLogRepository.DeleteByIds(logIds)
} }
// CleanJobLog 清空调度任务日志 // Clean 清空
func (s *SysJobLog) CleanJobLog() error { func (s SysJobLog) Clean() int64 {
return s.sysJobLogRepository.CleanJobLog() return s.sysJobLogRepository.Clean()
}
// ExportData 导出数据表格
func (s SysJobLog) ExportData(rows []model.SysJobLog, fileName string) (string, error) {
// 第一行表头标题
headerCells := map[string]string{
"A1": "日志序号",
"B1": "任务名称",
"C1": "任务组名",
"D1": "调用目标",
"E1": "传入参数",
"F1": "日志信息",
"G1": "执行状态",
"H1": "记录时间",
}
// 读取任务组名字典数据
dictSysJobGroup := s.sysDictTypeService.FindDataByType("sys_job_group")
// 从第二行开始的数据
dataCells := make([]map[string]any, 0)
for i, row := range rows {
idx := strconv.Itoa(i + 2)
// 任务组名
sysJobGroup := ""
for _, v := range dictSysJobGroup {
if row.JobGroup == v.DataValue {
sysJobGroup = v.DataLabel
break
}
}
// 状态
statusValue := "失败"
if row.StatusFlag == constants.STATUS_YES {
statusValue = "成功"
}
dataCells = append(dataCells, map[string]any{
"A" + idx: row.LogId,
"B" + idx: row.JobName,
"C" + idx: sysJobGroup,
"D" + idx: row.InvokeTarget,
"E" + idx: row.TargetParams,
"F" + idx: row.JobMsg,
"G" + idx: statusValue,
"H" + idx: date.ParseDateToStr(row.CreateTime, date.YYYY_MM_DD_HH_MM_SS),
})
}
// 导出数据表格
return file.WriteSheet(headerCells, dataCells, fileName, "")
} }

View File

@@ -1,7 +1,7 @@
package service package service
import ( import (
"be.ems/src/framework/vo" "be.ems/src/framework/token"
"be.ems/src/modules/monitor/model" "be.ems/src/modules/monitor/model"
) )
@@ -11,23 +11,23 @@ var NewSysUserOnline = &SysUserOnline{}
// SysUserOnline 在线用户 服务层处理 // SysUserOnline 在线用户 服务层处理
type SysUserOnline struct{} type SysUserOnline struct{}
// LoginUserToUserOnline 设置在线用户信息 // TokenInfoToUserOnline 在线用户信息
func (r *SysUserOnline) LoginUserToUserOnline(loginUser vo.LoginUser) model.SysUserOnline { func (s SysUserOnline) TokenInfoToUserOnline(tokenInfo token.TokenInfo) model.SysUserOnline {
if loginUser.UserID == "" { if tokenInfo.UserId <= 0 {
return model.SysUserOnline{} return model.SysUserOnline{}
} }
sysUserOnline := model.SysUserOnline{ sysUserOnline := model.SysUserOnline{
TokenID: loginUser.UUID, TokenID: tokenInfo.UUID,
UserName: loginUser.User.UserName, UserName: tokenInfo.User.UserName,
IPAddr: loginUser.IPAddr, LoginIp: tokenInfo.LoginIp,
LoginLocation: loginUser.LoginLocation, LoginLocation: tokenInfo.LoginLocation,
Browser: loginUser.Browser, Browser: tokenInfo.Browser,
OS: loginUser.OS, OS: tokenInfo.OS,
LoginTime: loginUser.LoginTime, LoginTime: tokenInfo.LoginTime,
} }
if loginUser.User.DeptID != "" { if tokenInfo.User.DeptId > 0 {
sysUserOnline.DeptName = loginUser.User.Dept.DeptName sysUserOnline.DeptName = tokenInfo.User.Dept.DeptName
} }
return sysUserOnline return sysUserOnline
} }

View File

@@ -91,9 +91,9 @@ func (s *SystemInfo) MemoryInfo() map[string]any {
// CPUInfo CPU信息 // CPUInfo CPU信息
func (s *SystemInfo) CPUInfo() map[string]any { func (s *SystemInfo) CPUInfo() map[string]any {
var core int = 0 var core = 0
var speed string = "未知" var speed = "-"
var model string = "未知" var model = "-"
cpuInfo, err := cpu.Info() cpuInfo, err := cpu.Info()
if err == nil { if err == nil {
core = runtime.NumCPU() core = runtime.NumCPU()
@@ -101,11 +101,11 @@ func (s *SystemInfo) CPUInfo() map[string]any {
model = strings.TrimSpace(cpuInfo[0].ModelName) model = strings.TrimSpace(cpuInfo[0].ModelName)
} }
useds := []string{} var used []string
cpuPercent, err := cpu.Percent(0, true) cpuPercent, err := cpu.Percent(0, true)
if err == nil { if err == nil {
for _, v := range cpuPercent { for _, v := range cpuPercent {
useds = append(useds, fmt.Sprintf("%.2f", v)) used = append(used, fmt.Sprintf("%.2f", v))
} }
} }
@@ -113,39 +113,39 @@ func (s *SystemInfo) CPUInfo() map[string]any {
"model": model, "model": model,
"speed": speed, "speed": speed,
"core": core, "core": core,
"coreUsed": useds, "coreUsed": used,
} }
} }
// NetworkInfo 网络信息 // NetworkInfo 网络信息
func (s *SystemInfo) NetworkInfo() map[string]string { func (s *SystemInfo) NetworkInfo() map[string]string {
ipAddrs := make(map[string]string) ipAdders := make(map[string]string)
interfaces, err := net.Interfaces() interfaces, err := net.Interfaces()
if err == nil { if err == nil {
for _, iface := range interfaces { for _, v := range interfaces {
name := iface.Name name := v.Name
if name[len(name)-1] == '0' { if name[len(name)-1] == '0' {
name = name[0 : len(name)-1] name = name[0 : len(name)-1]
name = strings.Trim(name, "") name = strings.Trim(name, "")
} }
// ignore localhost // ignore localhost
if name == "lo" { if strings.HasPrefix(name, "lo") || strings.HasPrefix(name, "veth") || strings.HasPrefix(name, "Loopback") {
continue continue
} }
var addrs []string var adders []string
for _, v := range iface.Addrs { for _, v := range v.Addrs {
prefix := strings.Split(v.Addr, "/")[0] prefix := strings.Split(v.Addr, "/")[0]
if strings.Contains(prefix, "::") { if strings.Contains(prefix, "::") {
addrs = append(addrs, fmt.Sprintf("IPv6 %s", prefix)) adders = append(adders, fmt.Sprintf("IPv6 %s", prefix))
} }
if strings.Contains(prefix, ".") { if strings.Contains(prefix, ".") {
addrs = append(addrs, fmt.Sprintf("IPv4 %s", prefix)) adders = append(adders, fmt.Sprintf("IPv4 %s", prefix))
} }
} }
ipAddrs[name] = strings.Join(addrs, " / ") ipAdders[name] = strings.Join(adders, " / ")
} }
} }
return ipAddrs return ipAdders
} }
// DiskInfo 磁盘信息 // DiskInfo 磁盘信息
@@ -166,11 +166,11 @@ func (s *SystemInfo) DiskInfo() []map[string]string {
continue continue
} }
disks = append(disks, map[string]string{ disks = append(disks, map[string]string{
"size": parse.Bit(float64(usage.Total)), "size": parse.Bit(float64(usage.Total)),
"used": parse.Bit(float64(usage.Used)), "used": parse.Bit(float64(usage.Used)),
"avail": parse.Bit(float64(usage.Free)), "avail": parse.Bit(float64(usage.Free)),
"pcent": fmt.Sprintf("%.1f%%", usage.UsedPercent), "percent": fmt.Sprintf("%.1f%%", usage.UsedPercent),
"target": partition.Device, "target": partition.Device,
}) })
} }
return disks return disks

View File

@@ -1,12 +1,12 @@
package controller package controller
import ( import (
"strings" "fmt"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -31,49 +31,63 @@ type AlarmController struct {
// 告警列表 // 告警列表
// //
// GET /list // GET /list
//
// @Tags network_data/alarm
// @Accept json
// @Produce json
// @Param neType query string false "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string false "NE ID The actual record is the network element RmUid"
// @Param neName query string false "NE Name"
// @Param pvFlag query string false "PV Flag" Enums(PNF,VNF)
// @Param alarmCode query string false "alarm status code"
// @Param alarmType query string false "Alarm type Communication alarms=1, Equipment alarms=2, Processing faults=3, Environmental alarms=4, Quality of service alarms=5" Enums(1,2,3,4,5)
// @Param alarmStatus query string false "Alarm status 0:clear, 1:active" Enums(0,1)
// @Param origSeverity query string false "Alarm Type 1: Critical, 2: Major, 3: Minor, 4: Warning" Enums(1,2,3,4)
// @Param sortField query string false "Sort fields, fill in result fields" default(event_time)
// @Param sortOrder query string false "Sort by ascending or descending order, asc desc" default(asc)
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Alarm List
// @Description Alarm List
// @Router /neData/alarm/list [get]
func (s *AlarmController) List(c *gin.Context) { func (s *AlarmController) List(c *gin.Context) {
language := ctx.AcceptLanguage(c) var query model.AlarmQuery
var querys model.AlarmQuery if err := c.ShouldBindQuery(&query); err != nil {
if err := c.ShouldBindQuery(&querys); err != nil { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.alarmService.SelectPage(querys) rows, total := s.alarmService.FindByPage(query)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// 告警删除 // 告警删除
// //
// DELETE /:alarmIds // DELETE /:id
func (s *AlarmController) Remove(c *gin.Context) { func (s *AlarmController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
alarmIds := c.Param("alarmIds") id := c.Param("id")
if alarmIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(alarmIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.alarmService.DeleteByIds(uniqueIDs)
rows, err := s.alarmService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }

View File

@@ -0,0 +1,93 @@
package controller
import (
"fmt"
"be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
"be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
)
// 实例化控制层 AlarmLogController 结构体
var NewAlarmLog = &AlarmLogController{
neInfoService: neService.NewNeInfo,
alarmLogService: neDataService.NewAlarmLog,
}
// 告警数据
//
// PATH /alarm/log
type AlarmLogController struct {
neInfoService *neService.NeInfo // 网元信息服务
alarmLogService *neDataService.AlarmLog // 告警信息服务
}
// 告警日志列表
//
// GET /list
//
// @Tags network_data/alarm_log
// @Accept json
// @Produce json
// @Param neType query string false "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string false "NE ID The actual record is the network element RmUid"
// @Param neName query string false "NE Name"
// @Param pvFlag query string false "PV Flag" Enums(PNF,VNF)
// @Param alarmLogCode query string false "AlarmLog status code"
// @Param alarmLogType query string false "AlarmLog type Communication AlarmLogs=1, Equipment AlarmLogs=2, Processing faults=3, Environmental AlarmLogs=4, Quality of service AlarmLogs=5" Enums(1,2,3,4,5)
// @Param alarmLogStatus query string false "AlarmLog status 0:clear, 1:active" Enums(0,1)
// @Param origSeverity query string false "AlarmLog Type 1: Critical, 2: Major, 3: Minor, 4: Warning" Enums(1,2,3,4)
// @Param sortField query string false "Sort fields, fill in result fields" default(event_time)
// @Param sortOrder query string false "Sort by ascending or descending order, asc desc" default(asc)
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary AlarmLog List
// @Description AlarmLog List
// @Router /neData/alarm/log/list [get]
func (s *AlarmLogController) List(c *gin.Context) {
var query model.AlarmLogQuery
if err := c.ShouldBindQuery(&query); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询数据
rows, total := s.alarmLogService.FindByPage(query)
c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}
// 告警删除
//
// DELETE /:id
func (s AlarmLogController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.alarmLogService.DeleteByIds(ids)
if err != nil {
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, resp.OkMsg(msg))
}

View File

@@ -1,27 +1,30 @@
package controller package controller
import ( import (
"fmt"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 PerfKPIController 结构体 // 实例化控制层 KPIController 结构体
var NewPerfKPI = &PerfKPIController{ var NewKPI = &KPIController{
neInfoService: neService.NewNeInfo, neInfoService: neService.NewNeInfo,
perfKPIService: neDataService.NewPerfKPI, kpiReportService: neDataService.NewKpiReport,
} }
// 性能统计 // 性能统计
// //
// PATH /kpi // PATH /kpi
type PerfKPIController struct { type KPIController struct {
neInfoService *neService.NeInfo // 网元信息服务 neInfoService *neService.NeInfo // 网元信息服务
perfKPIService *neDataService.PerfKPI // 统计信息服务 kpiReportService *neDataService.KpiReport // 指标统计服务
} }
// 获取统计数据 // 获取统计数据
@@ -31,39 +34,36 @@ type PerfKPIController struct {
// @Tags network_data/kpi // @Tags network_data/kpi
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(AMF) // @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(AMF)
// @Param neId query string true "NE ID" default(001) // @Param neId query string true "NE ID" default(001)
// @Param startTime query number true "Start time (timestamped milliseconds)" default(1729162507596) // @Param beginTime query number true "begin time (timestamped milliseconds)" default(1729162507596)
// @Param endTime query number true "End time (timestamped milliseconds)" default(1729164187611) // @Param endTime query number true "end time (timestamped milliseconds)" default(1729164187611)
// @Param interval query number true "interval" Enums(5,10,15,30,60,300,600,900,1800,3600) default(60) // @Param interval query number true "interval" Enums(5,10,15,30,60,300,600,900,1800,3600) default(60)
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Access to statistical data // @Summary Access to statistical data
// @Description Access to statistical data // @Description Access to statistical data
// @Router /neData/kpi/data [get] // @Router /neData/kpi/data [get]
func (s *PerfKPIController) GoldKPI(c *gin.Context) { func (s KPIController) KPIData(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.GoldKPIQuery var querys model.KPIQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
return c.JSON(422, resp.CodeMsg(40422, errMsgs))
}
if querys.Interval < 5 || querys.Interval > 3600 {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
kpiData := s.perfKPIService.SelectGoldKPI(querys) kpiData := s.kpiReportService.FindData(querys)
c.JSON(200, result.OkData(kpiData)) c.JSON(200, resp.OkData(kpiData))
} }
// 获取统计标题 // 获取统计标题
@@ -73,21 +73,18 @@ func (s *PerfKPIController) GoldKPI(c *gin.Context) {
// @Tags network_data/kpi // @Tags network_data/kpi
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(AMF) // @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(AMF)
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Get Statistical Headings // @Summary Get Statistical Headings
// @Description Get Statistical Headings // @Description Get Statistical Headings
// @Router /neData/kpi/title [get] // @Router /neData/kpi/title [get]
func (s *PerfKPIController) Title(c *gin.Context) { func (s KPIController) KPITitle(c *gin.Context) {
language := ctx.AcceptLanguage(c)
neType := c.Query("neType") neType := c.Query("neType")
if neType == "" { if neType == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: neType is empty"))
return return
} }
kpiTitles := s.kpiReportService.FindTitle(neType)
kpiTitles := s.perfKPIService.SelectGoldKPITitle(neType) c.JSON(200, resp.OkData(kpiTitles))
c.JSON(200, result.OkData(kpiTitles))
} }

View File

@@ -7,8 +7,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -35,38 +35,39 @@ type NBStateController struct {
// @Tags network_data/amf,network_data/mme // @Tags network_data/amf,network_data/mme
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param neType query string true "NE Type only AMF/MME" Enums(AMF,MME) default(AMF) // @Param neType query string true "NE Type only AMF/MME" Enums(AMF,MME) default(AMF)
// @Param neId query string true "NE ID" default(001) // @Param neId query string true "NE ID" default(001)
// @Param pageNum query number true "pageNum" default(1) // @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10) // @Param pageSize query number true "pageSize" default(10)
// @Param startTime query number false "Start time (timestamped milliseconds)" default(1729162507596) // @Param startTime query number false "Start time (timestamped milliseconds)" default(1729162507596)
// @Param endTime query number false "End time (timestamped milliseconds)" default(1729164187611) // @Param endTime query number false "End time (timestamped milliseconds)" default(1729164187611)
// @Param sortField query string false "Sort fields, fill in result fields" Enums(id,create_time) default(id) // @Param sortField query string false "Sort fields, fill in result fields" Enums(id,create_time) default(id)
// @Param sortOrder query string false "Sort by ascending or descending order" Enums(asc,desc) default(asc) // @Param sortOrder query string false "Sort by ascending or descending order" Enums(asc,desc) default(asc)
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary Base Station Status List // @Summary Base Station Status List
// @Description Base Station Status List // @Description Base Station Status List
// @Router /nb-state/list [get] // @Router /nb-state/list [get]
func (s NBStateController) List(c *gin.Context) { func (s NBStateController) List(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query model.NBStateQuery var query model.NBStateQuery
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(query.NeType, query.NeID)
if neInfo.NeId != query.NeID || neInfo.IP == "" { if neInfo.NeId != query.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
query.RmUID = neInfo.RmUID query.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.nbStateService.SelectPage(query) rows, total := s.nbStateService.FindByPage(query)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// 历史记录列表导出 // 历史记录列表导出
@@ -83,11 +84,12 @@ func (s NBStateController) List(c *gin.Context) {
// @Description Base Station Status List Export // @Description Base Station Status List Export
// @Router /nb-state/export [post] // @Router /nb-state/export [post]
func (s NBStateController) Export(c *gin.Context) { func (s NBStateController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.NBStateQuery var querys model.NBStateQuery
if err := c.ShouldBindBodyWithJSON(&querys); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -95,16 +97,16 @@ func (s NBStateController) Export(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.nbStateService.SelectPage(querys) rows, total := s.nbStateService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -113,7 +115,7 @@ func (s NBStateController) Export(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.nbStateService.ExportXlsx(rows, fileName, language) saveFilePath, err := s.nbStateService.ExportXlsx(rows, fileName, language)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -2,13 +2,12 @@ package controller
import ( import (
"fmt" "fmt"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
@@ -49,60 +48,63 @@ type AMFController struct {
// @Description UE Session List // @Description UE Session List
// @Router /neData/amf/ue/list [get] // @Router /neData/amf/ue/list [get]
func (s *AMFController) UEList(c *gin.Context) { func (s *AMFController) UEList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.UEEventAMFQuery var querys model.UEEventAMFQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("AMF", querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID("AMF", querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.ueEventService.SelectPage(querys) rows, total := s.ueEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// UE会话删除 // UE会话删除
// //
// DELETE /ue/:ueIds // DELETE /ue/:id
// //
// @Tags network_data/amf // @Tags network_data/amf
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param ueIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary UE Session Deletion // @Summary UE Session Deletion
// @Description UE Session Deletion // @Description UE Session Deletion
// @Router /neData/amf/ue/{ueIds} [delete] // @Router /neData/amf/ue/{id} [delete]
func (s *AMFController) UERemove(c *gin.Context) { func (s *AMFController) UERemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
ueIds := c.Param("ueIds") id := c.Param("id")
if ueIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(ueIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.ueEventService.DeleteByIds(uniqueIDs)
rows, err := s.ueEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// UE会话列表导出 // UE会话列表导出
@@ -119,11 +121,12 @@ func (s *AMFController) UERemove(c *gin.Context) {
// @Description UE Session List Export // @Description UE Session List Export
// @Router /neData/amf/ue/export [post] // @Router /neData/amf/ue/export [post]
func (s *AMFController) UEExport(c *gin.Context) { func (s *AMFController) UEExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.UEEventAMFQuery var querys model.UEEventAMFQuery
if err := c.ShouldBindBodyWithJSON(&querys); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -131,16 +134,16 @@ func (s *AMFController) UEExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("AMF", querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID("AMF", querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.ueEventService.SelectPage(querys) rows, total := s.ueEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -149,7 +152,7 @@ func (s *AMFController) UEExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.ueEventService.ExportXlsx(rows, fileName, language) saveFilePath, err := s.ueEventService.ExportXlsx(rows, fileName, language)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -171,20 +174,21 @@ func (s *AMFController) UEExport(c *gin.Context) {
// @Description Access Base Station Information List // @Description Access Base Station Information List
// @Router /neData/amf/nb/list [get] // @Router /neData/amf/nb/list [get]
func (s *AMFController) NbInfoList(c *gin.Context) { func (s *AMFController) NbInfoList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { var query struct {
NeId string `form:"neId" binding:"required"` NeId string `form:"neId" binding:"required"`
NbId string `form:"id"` NbId string `form:"id"`
} }
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("AMF", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("AMF", query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
@@ -193,11 +197,11 @@ func (s *AMFController) NbInfoList(c *gin.Context) {
"id": query.NbId, "id": query.NbId,
}) })
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// 接入基站状态信息列表 // 接入基站状态信息列表
@@ -214,28 +218,26 @@ func (s *AMFController) NbInfoList(c *gin.Context) {
// @Description Access to the base station status information list // @Description Access to the base station status information list
// @Router /neData/amf/nb/list-cfg [get] // @Router /neData/amf/nb/list-cfg [get]
func (s *AMFController) NbStateList(c *gin.Context) { func (s *AMFController) NbStateList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { neId := c.Query("neId")
NeId string `form:"neId" binding:"required"` if neId == "" {
} c.JSON(400, resp.CodeMsg(40010, "bind err: neId is empty"))
if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("AMF", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("AMF", neId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元直连 // 网元直连
data, err := neFetchlink.AMFGnbStateList(neInfo) data, err := neFetchlink.AMFGnbStateList(neInfo)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -2,13 +2,12 @@ package controller
import ( import (
"fmt" "fmt"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
@@ -50,60 +49,63 @@ type IMSController struct {
// @Description CDR Session List // @Description CDR Session List
// @Router /neData/ims/cdr/list [get] // @Router /neData/ims/cdr/list [get]
func (s *IMSController) CDRList(c *gin.Context) { func (s *IMSController) CDRList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.CDREventIMSQuery var querys model.CDREventIMSQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// CDR会话删除 // CDR会话删除
// //
// DELETE /cdr/:cdrIds // DELETE /cdr/:id
// //
// @Tags network_data/ims // @Tags network_data/ims
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param cdrIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary CDR Session Delete // @Summary CDR Session Delete
// @Description CDR Session Delete // @Description CDR Session Delete
// @Router /neData/ims/cdr/{cdrIds} [delete] // @Router /neData/ims/cdr/{id} [delete]
func (s *IMSController) CDRRemove(c *gin.Context) { func (s *IMSController) CDRRemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
cdrIds := c.Param("cdrIds") id := c.Param("id")
if cdrIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(cdrIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.cdrEventService.DeleteByIds(uniqueIDs)
rows, err := s.cdrEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// CDR会话列表导出 // CDR会话列表导出
@@ -120,11 +122,12 @@ func (s *IMSController) CDRRemove(c *gin.Context) {
// @Description CDR Session List Export // @Description CDR Session List Export
// @Router /neData/ims/cdr/export [post] // @Router /neData/ims/cdr/export [post]
func (s *IMSController) CDRExport(c *gin.Context) { func (s *IMSController) CDRExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.CDREventIMSQuery var querys model.CDREventIMSQuery
if err := c.ShouldBindBodyWithJSON(&querys); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -132,16 +135,16 @@ func (s *IMSController) CDRExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -150,7 +153,7 @@ func (s *IMSController) CDRExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName, language) saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName, language)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -171,30 +174,28 @@ func (s *IMSController) CDRExport(c *gin.Context) {
// @Description Number of online session users // @Description Number of online session users
// @Router /neData/ims/session/num [get] // @Router /neData/ims/session/num [get]
func (s *IMSController) UeSessionNum(c *gin.Context) { func (s *IMSController) UeSessionNum(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { neId := c.Query("neId")
NeId string `form:"neId" binding:"required"` if neId == "" {
} c.JSON(400, resp.CodeMsg(40010, "bind err: neId is empty"))
if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("IMS", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("IMS", neId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元直连 // 网元直连
num, err := neFetchlink.IMSUeSessionNum(neInfo) num, err := neFetchlink.IMSUeSessionNum(neInfo)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(num)) c.JSON(200, resp.OkData(num))
} }
// 在线会话用户列表信息 // 在线会话用户列表信息
@@ -213,21 +214,22 @@ func (s *IMSController) UeSessionNum(c *gin.Context) {
// @Description Online session user list information // @Description Online session user list information
// @Router /neData/ims/session/list [get] // @Router /neData/ims/session/list [get]
func (s *IMSController) UeSessionList(c *gin.Context) { func (s *IMSController) UeSessionList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { var query struct {
NeId string `form:"neId" binding:"required"` NeId string `form:"neId" binding:"required"`
IMSI string `form:"imsi"` IMSI string `form:"imsi"`
MSISDN string `form:"msisdn"` MSISDN string `form:"msisdn"`
} }
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("IMS", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("IMS", query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
@@ -237,9 +239,9 @@ func (s *IMSController) UeSessionList(c *gin.Context) {
"msisdn": query.MSISDN, "msisdn": query.MSISDN,
}) })
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -2,19 +2,18 @@ package controller
import ( import (
"fmt" "fmt"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 MMEController 结构体 // 实例化控制层 MMEController 结构体
@@ -49,60 +48,63 @@ type MMEController struct {
// @Description UE Session List // @Description UE Session List
// @Router /neData/mme/ue/list [get] // @Router /neData/mme/ue/list [get]
func (s *MMEController) UEList(c *gin.Context) { func (s *MMEController) UEList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.UEEventMMEQuery var querys model.UEEventMMEQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("MME", querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID("MME", querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.ueEventService.SelectPage(querys) rows, total := s.ueEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// UE会话删除 // UE会话删除
// //
// DELETE /ue/:ueIds // DELETE /ue/:id
// //
// @Tags network_data/mme // @Tags network_data/mme
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param ueIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary UE Session Deletion // @Summary UE Session Deletion
// @Description UE Session Deletion // @Description UE Session Deletion
// @Router /neData/mme/ue/{ueIds} [delete] // @Router /neData/mme/ue/{id} [delete]
func (s *MMEController) UERemove(c *gin.Context) { func (s *MMEController) UERemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
ueIds := c.Param("ueIds") id := c.Param("id")
if ueIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(ueIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.ueEventService.DeleteByIds(uniqueIDs)
rows, err := s.ueEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// UE会话列表导出 // UE会话列表导出
@@ -119,11 +121,12 @@ func (s *MMEController) UERemove(c *gin.Context) {
// @Description UE Session List Export // @Description UE Session List Export
// @Router /neData/mme/ue/export [post] // @Router /neData/mme/ue/export [post]
func (s *MMEController) UEExport(c *gin.Context) { func (s *MMEController) UEExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.UEEventMMEQuery var querys model.UEEventMMEQuery
if err := c.ShouldBindBodyWith(&querys, binding.JSON); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -131,16 +134,16 @@ func (s *MMEController) UEExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("MME", querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID("MME", querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.ueEventService.SelectPage(querys) rows, total := s.ueEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -149,7 +152,7 @@ func (s *MMEController) UEExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.ueEventService.ExportXlsx(rows, fileName, language) saveFilePath, err := s.ueEventService.ExportXlsx(rows, fileName, language)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -171,20 +174,21 @@ func (s *MMEController) UEExport(c *gin.Context) {
// @Description Access Base Station Information List // @Description Access Base Station Information List
// @Router /neData/mme/nb/list [get] // @Router /neData/mme/nb/list [get]
func (s *MMEController) NbInfoList(c *gin.Context) { func (s *MMEController) NbInfoList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { var query struct {
NeId string `form:"neId" binding:"required"` NeId string `form:"neId" binding:"required"`
NbId string `form:"id"` NbId string `form:"id"`
} }
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("MME", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("MME", query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
@@ -193,11 +197,11 @@ func (s *MMEController) NbInfoList(c *gin.Context) {
"id": query.NbId, "id": query.NbId,
}) })
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// 接入基站状态信息列表 // 接入基站状态信息列表
@@ -214,28 +218,26 @@ func (s *MMEController) NbInfoList(c *gin.Context) {
// @Description Access to the base station status information list // @Description Access to the base station status information list
// @Router /neData/mme/nb/list-cfg [get] // @Router /neData/mme/nb/list-cfg [get]
func (s *MMEController) NbStateList(c *gin.Context) { func (s *MMEController) NbStateList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { neId := c.Query("neId")
NeId string `form:"neId" binding:"required"` if neId == "" {
} c.JSON(400, resp.CodeMsg(40010, "bind err: neId is empty"))
if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("MME", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("MME", neId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元直连 // 网元直连
data, err := neFetchlink.MMEEnbStateList(neInfo) data, err := neFetchlink.MMEEnbStateList(neInfo)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -2,13 +2,12 @@ package controller
import ( import (
"fmt" "fmt"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -17,18 +16,18 @@ import (
// 实例化控制层 SGWCController 结构体 // 实例化控制层 SGWCController 结构体
var NewSGWC = &SGWCController{ var NewSGWC = &SGWCController{
neInfoService: neService.NewNeInfo, neInfoService: neService.NewNeInfo,
cdrEventService: neDataService.NewCDREventSGWC, cdrEventService: neDataService.NewCDREventSGWC,
udmUserInfoService: neDataService.NewUDMUserInfo, UDMExtendService: neDataService.NewUDMExtend,
} }
// 网元SGWC // 网元SGWC
// //
// PATH /sgwc // PATH /sgwc
type SGWCController struct { type SGWCController struct {
neInfoService *neService.NeInfo // 网元信息服务 neInfoService *neService.NeInfo // 网元信息服务
cdrEventService *neDataService.CDREventSGWC // CDR会话事件服务 cdrEventService *neDataService.CDREventSGWC // CDR会话事件服务
udmUserInfoService *neDataService.UDMUserInfo // UDM用户信息服务 UDMExtendService *neDataService.UDMExtend // UDM用户信息服务
} }
// CDR会话列表 // CDR会话列表
@@ -50,60 +49,63 @@ type SGWCController struct {
// @Description CDR Session List // @Description CDR Session List
// @Router /neData/sgwc/cdr/list [get] // @Router /neData/sgwc/cdr/list [get]
func (s *SGWCController) CDRList(c *gin.Context) { func (s *SGWCController) CDRList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.CDREventSGWCQuery var querys model.CDREventSGWCQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// CDR会话删除 // CDR会话删除
// //
// DELETE /cdr/:cdrIds // DELETE /cdr/:id
// //
// @Tags network_data/sgwc // @Tags network_data/sgwc
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param cdrIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary CDR Session Delete // @Summary CDR Session Delete
// @Description CDR Session Delete // @Description CDR Session Delete
// @Router /neData/sgwc/cdr/{cdrIds} [delete] // @Router /neData/sgwc/cdr/{id} [delete]
func (s *SGWCController) CDRRemove(c *gin.Context) { func (s *SGWCController) CDRRemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
cdrIds := c.Param("cdrIds") id := c.Param("id")
if cdrIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(cdrIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.cdrEventService.DeleteByIds(uniqueIDs)
rows, err := s.cdrEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// CDR会话列表导出 // CDR会话列表导出
@@ -120,11 +122,12 @@ func (s *SGWCController) CDRRemove(c *gin.Context) {
// @Description CDR Session List Export // @Description CDR Session List Export
// @Router /neData/sgwc/cdr/export [post] // @Router /neData/sgwc/cdr/export [post]
func (s *SGWCController) CDRExport(c *gin.Context) { func (s *SGWCController) CDRExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.CDREventSGWCQuery var querys model.CDREventSGWCQuery
if err := c.ShouldBindBodyWithJSON(&querys); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -132,16 +135,16 @@ func (s *SGWCController) CDRExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -150,7 +153,7 @@ func (s *SGWCController) CDRExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName) saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -6,31 +6,31 @@ import (
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 SMFController 结构体 // 实例化控制层 SMFController 结构体
var NewSMF = &SMFController{ var NewSMF = &SMFController{
neInfoService: neService.NewNeInfo, neInfoService: neService.NewNeInfo,
cdrEventService: neDataService.NewCDREventSMF, cdrEventService: neDataService.NewCDREventSMF,
udmUserInfoService: neDataService.NewUDMUserInfo, UDMExtendService: neDataService.NewUDMExtend,
} }
// 网元SMF // 网元SMF
// //
// PATH /smf // PATH /smf
type SMFController struct { type SMFController struct {
neInfoService *neService.NeInfo // 网元信息服务 neInfoService *neService.NeInfo // 网元信息服务
cdrEventService *neDataService.CDREventSMF // CDR会话事件服务 cdrEventService *neDataService.CDREventSMF // CDR会话事件服务
udmUserInfoService *neDataService.UDMUserInfo // UDM用户信息服务 UDMExtendService *neDataService.UDMExtend // UDM用户信息服务
} }
// CDR会话列表 // CDR会话列表
@@ -51,60 +51,63 @@ type SMFController struct {
// @Description CDR Session List // @Description CDR Session List
// @Router /neData/smf/cdr/list [get] // @Router /neData/smf/cdr/list [get]
func (s *SMFController) CDRList(c *gin.Context) { func (s *SMFController) CDRList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.CDREventSMFQuery var querys model.CDREventSMFQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// CDR会话删除 // CDR会话删除
// //
// DELETE /cdr/:cdrIds // DELETE /cdr/:id
// //
// @Tags network_data/smf // @Tags network_data/smf
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param cdrIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary CDR Session Delete // @Summary CDR Session Delete
// @Description CDR Session Delete // @Description CDR Session Delete
// @Router /neData/smf/cdr/{cdrIds} [delete] // @Router /neData/smf/cdr/{id} [delete]
func (s *SMFController) CDRRemove(c *gin.Context) { func (s *SMFController) CDRRemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
cdrIds := c.Param("cdrIds") id := c.Param("id")
if cdrIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(cdrIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.cdrEventService.DeleteByIds(uniqueIDs)
rows, err := s.cdrEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// CDR会话列表导出 // CDR会话列表导出
@@ -121,11 +124,12 @@ func (s *SMFController) CDRRemove(c *gin.Context) {
// @Description CDR Session List Export // @Description CDR Session List Export
// @Router /neData/smf/cdr/export [post] // @Router /neData/smf/cdr/export [post]
func (s *SMFController) CDRExport(c *gin.Context) { func (s *SMFController) CDRExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.CDREventSMFQuery var querys model.CDREventSMFQuery
if err := c.ShouldBindBodyWith(&querys, binding.JSON); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -133,16 +137,16 @@ func (s *SMFController) CDRExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -151,7 +155,7 @@ func (s *SMFController) CDRExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName) saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -172,30 +176,30 @@ func (s *SMFController) CDRExport(c *gin.Context) {
// @Description Number of online session users // @Description Number of online session users
// @Router /neData/smf/sub/num [get] // @Router /neData/smf/sub/num [get]
func (s *SMFController) SubUserNum(c *gin.Context) { func (s *SMFController) SubUserNum(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { var query struct {
NeId string `form:"neId" binding:"required"` NeId string `form:"neId" binding:"required"`
} }
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("SMF", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("SMF", query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元直连 // 网元直连
num, err := neFetchlink.SMFSubNum(neInfo) num, err := neFetchlink.SMFSubNum(neInfo)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
c.JSON(200, result.OkData(num)) c.JSON(200, resp.OkData(num))
} }
// 在线订阅用户列表信息 // 在线订阅用户列表信息
@@ -216,7 +220,7 @@ func (s *SMFController) SubUserNum(c *gin.Context) {
// @Description Online session user list information // @Description Online session user list information
// @Router /neData/smf/session/list [get] // @Router /neData/smf/session/list [get]
func (s *SMFController) SubUserList(c *gin.Context) { func (s *SMFController) SubUserList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var query struct { var query struct {
NeId string `form:"neId" binding:"required"` NeId string `form:"neId" binding:"required"`
IMSI string `form:"imsi"` IMSI string `form:"imsi"`
@@ -225,14 +229,14 @@ func (s *SMFController) SubUserList(c *gin.Context) {
PageNum string `form:"pageNum"` PageNum string `form:"pageNum"`
} }
if err := c.ShouldBindQuery(&query); err != nil { if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元信息 // 查询网元信息
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("SMF", query.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("SMF", query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" { if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
@@ -244,7 +248,7 @@ func (s *SMFController) SubUserList(c *gin.Context) {
"pageNum": query.PageNum, "pageNum": query.PageNum,
}) })
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -259,7 +263,7 @@ func (s *SMFController) SubUserList(c *gin.Context) {
imsiStr = strings.TrimPrefix(imsiStr, "imsi-") imsiStr = strings.TrimPrefix(imsiStr, "imsi-")
item["imsi"] = imsiStr item["imsi"] = imsiStr
// 查UDM拓展信息 // 查UDM拓展信息
info := s.udmUserInfoService.SelectByIMSIAndNeID(imsiStr, "%") info := s.UDMExtendService.FindByIMSIAndNeID(imsiStr, "%")
item["remark"] = info.Remark item["remark"] = info.Remark
} }
if v, ok := item["msisdn"]; ok && v != nil { if v, ok := item["msisdn"]; ok && v != nil {
@@ -268,5 +272,5 @@ func (s *SMFController) SubUserList(c *gin.Context) {
} }
} }
c.JSON(200, result.Ok(data)) c.JSON(200, resp.OkData(data))
} }

View File

@@ -2,13 +2,12 @@ package controller
import ( import (
"fmt" "fmt"
"strings"
"time" "time"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
@@ -49,60 +48,63 @@ type SMSCController struct {
// @Description CDR Session List // @Description CDR Session List
// @Router /neData/smsc/cdr/list [get] // @Router /neData/smsc/cdr/list [get]
func (s *SMSCController) CDRList(c *gin.Context) { func (s *SMSCController) CDRList(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys model.CDREventSMSCQuery var querys model.CDREventSMSCQuery
if err := c.ShouldBindQuery(&querys); err != nil { if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
// 查询数据 // 查询数据
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total})) c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
} }
// CDR会话删除 // CDR会话删除
// //
// DELETE /cdr/:cdrIds // DELETE /cdr/:id
// //
// @Tags network_data/smsc // @Tags network_data/smsc
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param cdrIds path string true "list data id, multiple separated by a , sign" // @Param id path string true "list data id, multiple separated by a , sign"
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary CDR Session Delete // @Summary CDR Session Delete
// @Description CDR Session Delete // @Description CDR Session Delete
// @Router /neData/smsc/cdr/{cdrIds} [delete] // @Router /neData/smsc/cdr/{id} [delete]
func (s *SMSCController) CDRRemove(c *gin.Context) { func (s *SMSCController) CDRRemove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
cdrIds := c.Param("cdrIds") id := c.Param("id")
if cdrIds == "" { if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return return
} }
// 处理字符转id数组后去重 // 处理字符转id数组后去重
ids := strings.Split(cdrIds, ",") uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids) // 转换成int64数组类型
if len(uniqueIDs) <= 0 { ids := make([]int64, 0)
c.JSON(200, result.Err(nil)) for _, v := range uniqueIDs {
return ids = append(ids, parse.Number(v))
} }
rows, err := s.cdrEventService.DeleteByIds(uniqueIDs)
rows, err := s.cdrEventService.DeleteByIds(ids)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error()))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return return
} }
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows}) msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg)) c.JSON(200, resp.OkMsg(msg))
} }
// CDR会话列表导出 // CDR会话列表导出
@@ -119,11 +121,12 @@ func (s *SMSCController) CDRRemove(c *gin.Context) {
// @Description CDR Session List Export // @Description CDR Session List Export
// @Router /neData/smsc/cdr/export [post] // @Router /neData/smsc/cdr/export [post]
func (s *SMSCController) CDRExport(c *gin.Context) { func (s *SMSCController) CDRExport(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
var querys model.CDREventSMSCQuery var querys model.CDREventSMSCQuery
if err := c.ShouldBindBodyWithJSON(&querys); err != nil { if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 限制导出数据集 // 限制导出数据集
@@ -131,16 +134,16 @@ func (s *SMSCController) CDRExport(c *gin.Context) {
querys.PageSize = 10000 querys.PageSize = 10000
} }
// 查询网元信息 rmUID // 查询网元信息 rmUID
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
querys.RmUID = neInfo.RmUID querys.RmUID = neInfo.RmUID
rows, total := s.cdrEventService.SelectPage(querys) rows, total := s.cdrEventService.FindByPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
@@ -149,7 +152,7 @@ func (s *SMSCController) CDRExport(c *gin.Context) {
// 导出数据表格 // 导出数据表格
saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName, language) saveFilePath, err := s.cdrEventService.ExportXlsx(rows, fileName, language)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }

View File

@@ -6,19 +6,19 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/constants/uploadsubpath" "be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/telnet" "be.ems/src/framework/telnet"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neFetchlink "be.ems/src/modules/network_element/fetch_link" neFetchlink "be.ems/src/modules/network_element/fetch_link"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 UDMAuthController 结构体 // 实例化控制层 UDMAuthController 结构体
@@ -45,19 +45,19 @@ type UDMAuthController struct {
// @Param neId path string true "NE ID" default(001) // @Param neId path string true "NE ID" default(001)
// @Success 200 {object} object "Response Results" // @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary UDM Authentication User Reload Data // @Summary UDM Authentication User Data Refresh
// @Description UDM Authentication User Reload Data // @Description UDM Authenticated User Data List Refresh Synchronization Latest
// @Router /neData/udm/auth/resetData/{neId} [put] // @Router /neData/udm/auth/resetData/{neId} [put]
func (s *UDMAuthController) ResetData(c *gin.Context) { func (s *UDMAuthController) ResetData(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
data := s.udmAuthService.ResetData(neId) data := s.udmAuthService.ResetData(neId)
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM鉴权用户列表 // UDM鉴权用户列表
@@ -77,9 +77,9 @@ func (s *UDMAuthController) ResetData(c *gin.Context) {
// @Description UDM Authentication User List // @Description UDM Authentication User List
// @Router /neData/udm/auth/list [get] // @Router /neData/udm/auth/list [get]
func (s *UDMAuthController) List(c *gin.Context) { func (s *UDMAuthController) List(c *gin.Context) {
querys := ctx.QueryMap(c) query := reqctx.QueryMap(c)
total, rows := s.udmAuthService.SelectPage(querys) total, rows := s.udmAuthService.FindByPage(query)
c.JSON(200, result.Ok(map[string]any{"total": total, "rows": rows})) c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
} }
// UDM鉴权用户信息 // UDM鉴权用户信息
@@ -97,24 +97,24 @@ func (s *UDMAuthController) List(c *gin.Context) {
// @Description UDM Authentication User Information // @Description UDM Authentication User Information
// @Router /neData/udm/auth/{neId}/{value} [get] // @Router /neData/udm/auth/{neId}/{value} [get]
func (s *UDMAuthController) Info(c *gin.Context) { func (s *UDMAuthController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
if neId == "" || imsi == "" { if neId == "" || imsi == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -123,19 +123,19 @@ func (s *UDMAuthController) Info(c *gin.Context) {
cmd := fmt.Sprintf("dsp authdat:imsi=%s", imsi) cmd := fmt.Sprintf("dsp authdat:imsi=%s", imsi)
data, err := telnet.ConvertToMap(telnetClient, cmd) data, err := telnet.ConvertToMap(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
if len(data) == 0 { if len(data) == 0 {
c.JSON(200, result.ErrMsg("No Auth Data")) c.JSON(200, resp.ErrMsg("No Auth Data"))
return return
} }
// 解析返回的数据 // 解析返回的数据
u := s.udmAuthService.ParseInfo(imsi, neId, data) u := s.udmAuthService.ParseInfo(imsi, neId, data)
s.udmAuthService.Insert(neId, u) s.udmAuthService.Insert(neId, u)
c.JSON(200, result.OkData(u)) c.JSON(200, resp.OkData(u))
} }
// UDM鉴权用户新增 // UDM鉴权用户新增
@@ -153,30 +153,30 @@ func (s *UDMAuthController) Info(c *gin.Context) {
// @Description UDM Authentication User Added // @Description UDM Authentication User Added
// @Router /neData/udm/auth/{neId} [post] // @Router /neData/udm/auth/{neId} [post]
func (s *UDMAuthController) Add(c *gin.Context) { func (s *UDMAuthController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMAuthUser var body model.UDMAuthUser
err := c.ShouldBindBodyWith(&body, binding.JSON) err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.IMSI == "" { if err != nil || body.IMSI == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -186,7 +186,7 @@ func (s *UDMAuthController) Add(c *gin.Context) {
cmd += s.udmAuthService.ParseCommandParams(body) cmd += s.udmAuthService.ParseCommandParams(body)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -194,7 +194,7 @@ func (s *UDMAuthController) Add(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmAuthService.Insert(neId, body) s.udmAuthService.Insert(neId, body)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM鉴权用户批量新增 // UDM鉴权用户批量新增
@@ -213,31 +213,31 @@ func (s *UDMAuthController) Add(c *gin.Context) {
// @Description UDM Authentication User Batch Add // @Description UDM Authentication User Batch Add
// @Router /neData/udm/auth/{neId}/{value} [post] // @Router /neData/udm/auth/{neId}/{value} [post]
func (s *UDMAuthController) Adds(c *gin.Context) { func (s *UDMAuthController) Adds(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
num := c.Param("num") num := c.Param("num")
if neId == "" || num == "" { if neId == "" || num == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMAuthUser var body model.UDMAuthUser
err := c.ShouldBindBodyWith(&body, binding.JSON) err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.IMSI == "" { if err != nil || body.IMSI == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -247,7 +247,7 @@ func (s *UDMAuthController) Adds(c *gin.Context) {
cmd += s.udmAuthService.ParseCommandParams(body) cmd += s.udmAuthService.ParseCommandParams(body)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -255,7 +255,7 @@ func (s *UDMAuthController) Adds(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmAuthService.LoadData(neId, body.IMSI, num) s.udmAuthService.LoadData(neId, body.IMSI, num)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM鉴权用户修改 // UDM鉴权用户修改
@@ -273,30 +273,30 @@ func (s *UDMAuthController) Adds(c *gin.Context) {
// @Description UDM Authenticated User Modification // @Description UDM Authenticated User Modification
// @Router /neData/udm/auth/{neId} [put] // @Router /neData/udm/auth/{neId} [put]
func (s *UDMAuthController) Edit(c *gin.Context) { func (s *UDMAuthController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMAuthUser var body model.UDMAuthUser
err := c.ShouldBindBodyWith(&body, binding.JSON) err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.IMSI == "" { if err != nil || body.IMSI == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -306,7 +306,7 @@ func (s *UDMAuthController) Edit(c *gin.Context) {
cmd += s.udmAuthService.ParseCommandParams(body) cmd += s.udmAuthService.ParseCommandParams(body)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -314,7 +314,7 @@ func (s *UDMAuthController) Edit(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmAuthService.Insert(neId, body) s.udmAuthService.Insert(neId, body)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM鉴权用户删除 // UDM鉴权用户删除
@@ -332,11 +332,11 @@ func (s *UDMAuthController) Edit(c *gin.Context) {
// @Description UDM Authenticated User Deletion // @Description UDM Authenticated User Deletion
// @Router /neData/udm/auth/{neId}/{value} [delete] // @Router /neData/udm/auth/{neId}/{value} [delete]
func (s *UDMAuthController) Remove(c *gin.Context) { func (s *UDMAuthController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
if neId == "" || imsi == "" { if neId == "" || imsi == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
@@ -344,20 +344,20 @@ func (s *UDMAuthController) Remove(c *gin.Context) {
imsiArr := strings.Split(imsi, ",") imsiArr := strings.Split(imsi, ",")
uniqueIDs := parse.RemoveDuplicates(imsiArr) uniqueIDs := parse.RemoveDuplicates(imsiArr)
if len(uniqueIDs) <= 0 { if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -378,7 +378,7 @@ func (s *UDMAuthController) Remove(c *gin.Context) {
resultData[imsi] = data resultData[imsi] = data
} }
c.JSON(200, result.OkData(resultData)) c.JSON(200, resp.OkData(resultData))
} }
// UDM鉴权用户批量删除 // UDM鉴权用户批量删除
@@ -397,25 +397,25 @@ func (s *UDMAuthController) Remove(c *gin.Context) {
// @Description UDM Authentication User Batch Deletion // @Description UDM Authentication User Batch Deletion
// @Router /neData/udm/auth/{neId}/{imsi}/{num} [delete] // @Router /neData/udm/auth/{neId}/{imsi}/{num} [delete]
func (s *UDMAuthController) Removes(c *gin.Context) { func (s *UDMAuthController) Removes(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
num := c.Param("num") num := c.Param("num")
if neId == "" || imsi == "" || num == "" { if neId == "" || imsi == "" || num == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -424,7 +424,7 @@ func (s *UDMAuthController) Removes(c *gin.Context) {
cmd := fmt.Sprintf("bde authdat:start_imsi=%s,sub_num=%s", imsi, num) cmd := fmt.Sprintf("bde authdat:start_imsi=%s,sub_num=%s", imsi, num)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -432,56 +432,58 @@ func (s *UDMAuthController) Removes(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmAuthService.LoadData(neId, imsi, num) s.udmAuthService.LoadData(neId, imsi, num)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM鉴权用户导出 // UDM鉴权用户导出
// //
// POST /export // GET /export
// //
// @Tags network_data/udm/auth // @Tags network_data/udm/auth
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param data body object true "Request Param" // @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results" // @Param type query string true "File Type" Enums(csv,txt) default(txt)
// @Param imsi query string false "IMSI"
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary UDM Authenticated User Export // @Summary UDM Authenticated User Export
// @Description UDM Authenticated User Export // @Description UDM Authenticated User Export
// @Router /neData/udm/auth/export [post] // @Router /neData/udm/auth/export [get]
func (s *UDMAuthController) Export(c *gin.Context) { func (s *UDMAuthController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
querys := ctx.BodyJSONMap(c) neId := c.Query("neId")
neId := querys["neId"].(string) fileType := c.Query("type")
fileType := querys["type"].(string) if neId == "" {
if neId == "" || fileType == "" { c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
if !(fileType == "csv" || fileType == "txt") { if !(fileType == "csv" || fileType == "txt") {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat")))
return return
} }
querys["pageNum"] = 1 query := reqctx.QueryMap(c)
querys["pageSize"] = 10000 total, rows := s.udmAuthService.FindByPage(query)
total, rows := s.udmAuthService.SelectPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
// rows := s.udmAuthService.SelectList(model.UDMAuthUser{NeId: neId}) // rows := s.udmAuthService.SelectList(model.UDMAuthUser{NeId: neId})
if len(rows) <= 0 { if len(rows) <= 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
// 文件名 // 文件名
fileName := fmt.Sprintf("udm_auth_user_export_%s_%d.%s", neId, time.Now().UnixMilli(), fileType) fileName := fmt.Sprintf("udm_auth_user_export_%s_%d.%s", neId, time.Now().UnixMilli(), fileType)
filePath := filepath.Join(file.ParseUploadFileDir(uploadsubpath.EXPORT), fileName) filePath := filepath.Join(file.ParseUploadFileDir(constants.UPLOAD_EXPORT), fileName)
if fileType == "csv" { if fileType == "csv" {
// 转换数据 // 转换数据
@@ -497,7 +499,7 @@ func (s *UDMAuthController) Export(c *gin.Context) {
// 输出到文件 // 输出到文件
err := file.WriterFileCSV(data, filePath) err := file.WriterFileCSV(data, filePath)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
} }
@@ -515,7 +517,7 @@ func (s *UDMAuthController) Export(c *gin.Context) {
// 输出到文件 // 输出到文件
if err := file.WriterFileTXT(data, ",", filePath); err != nil { if err := file.WriterFileTXT(data, ",", filePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
} }
@@ -537,59 +539,60 @@ func (s *UDMAuthController) Export(c *gin.Context) {
// @Description UDM Authenticated User Import // @Description UDM Authenticated User Import
// @Router /neData/udm/auth/import [post] // @Router /neData/udm/auth/import [post]
func (s *UDMAuthController) Import(c *gin.Context) { func (s *UDMAuthController) Import(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
NeId string `json:"neId" binding:"required"` // 网元ID NeId string `json:"neId" binding:"required"` // 网元ID
UploadPath string `json:"uploadPath" binding:"required"` // 上传文件路径 UploadPath string `json:"uploadPath" binding:"required"` // 上传文件路径
TypeVal string `json:"typeVal" binding:"required,oneof=default k4"` // default: 默认导入方式, k4: k4类型导入方式 TypeVal string `json:"typeVal" binding:"required,oneof=default k4"` // default: 默认导入方式, k4: k4类型导入方式
TypeData any `json:"typeData"` // k4类型的数据密钥 TypeData any `json:"typeData"` // k4类型的数据密钥
} }
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil { if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 判断文件名 // 判断文件名
if !(strings.HasSuffix(body.UploadPath, ".csv") || strings.HasSuffix(body.UploadPath, ".txt")) { if !(strings.HasSuffix(body.UploadPath, ".csv") || strings.HasSuffix(body.UploadPath, ".txt")) {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserAuthFileFormat"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserAuthFileFormat")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", body.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" { if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer sshClient.Close() defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() sftpClient, err := sshClient.NewClientSFTP()
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer sftpClient.Close() defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFilePath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
c.JSON(200, result.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient(neInfo.NeType, neInfo.NeId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient(neInfo.NeType, neInfo.NeId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -612,7 +615,7 @@ func (s *UDMAuthController) Import(c *gin.Context) {
} }
if resultErr != nil { if resultErr != nil {
c.JSON(200, result.ErrMsg(resultErr.Error())) c.JSON(200, resp.ErrMsg(resultErr.Error()))
return return
} }
@@ -627,5 +630,5 @@ func (s *UDMAuthController) Import(c *gin.Context) {
go s.udmAuthService.InsertData(neInfo.NeId, "txt", data) go s.udmAuthService.InsertData(neInfo.NeId, "txt", data)
} }
} }
c.JSON(200, result.OkMsg(resultMsg)) c.JSON(200, resp.OkMsg(resultMsg))
} }

View File

@@ -6,18 +6,18 @@ import (
"strings" "strings"
"time" "time"
"be.ems/src/framework/constants/uploadsubpath" "be.ems/src/framework/constants"
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/telnet" "be.ems/src/framework/telnet"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/utils/file" "be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse" "be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
) )
// 实例化控制层 UDMSubController 结构体 // 实例化控制层 UDMSubController 结构体
@@ -48,15 +48,15 @@ type UDMSubController struct {
// @Description UDM Subscriber User Reload Data // @Description UDM Subscriber User Reload Data
// @Router /neData/udm/sub/resetData/{neId} [put] // @Router /neData/udm/sub/resetData/{neId} [put]
func (s *UDMSubController) ResetData(c *gin.Context) { func (s *UDMSubController) ResetData(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
data := s.udmSubService.ResetData(neId) data := s.udmSubService.ResetData(neId)
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM签约用户列表 // UDM签约用户列表
@@ -77,9 +77,9 @@ func (s *UDMSubController) ResetData(c *gin.Context) {
// @Description UDM Subscriber User List // @Description UDM Subscriber User List
// @Router /neData/udm/sub/list [get] // @Router /neData/udm/sub/list [get]
func (s *UDMSubController) List(c *gin.Context) { func (s *UDMSubController) List(c *gin.Context) {
querys := ctx.QueryMap(c) query := reqctx.QueryMap(c)
total, rows := s.udmSubService.SelectPage(querys) total, rows := s.udmSubService.FindByPage(query)
c.JSON(200, result.Ok(map[string]any{"total": total, "rows": rows})) c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
} }
// UDM签约用户信息 // UDM签约用户信息
@@ -97,24 +97,24 @@ func (s *UDMSubController) List(c *gin.Context) {
// @Description UDM Subscriber User Information // @Description UDM Subscriber User Information
// @Router /neData/udm/sub/{neId}/{value} [get] // @Router /neData/udm/sub/{neId}/{value} [get]
func (s *UDMSubController) Info(c *gin.Context) { func (s *UDMSubController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
if neId == "" || imsi == "" { if neId == "" || imsi == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -123,19 +123,19 @@ func (s *UDMSubController) Info(c *gin.Context) {
cmd := fmt.Sprintf("dsp udmuser:imsi=%s", imsi) cmd := fmt.Sprintf("dsp udmuser:imsi=%s", imsi)
data, err := telnet.ConvertToMap(telnetClient, cmd) data, err := telnet.ConvertToMap(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
if len(data) == 0 { if len(data) == 0 {
c.JSON(200, result.ErrMsg("No Subs Data")) c.JSON(200, resp.ErrMsg("No Subs Data"))
return return
} }
// 解析返回的数据 // 解析返回的数据
u := s.udmSubService.ParseInfo(imsi, neId, data) u := s.udmSubService.ParseInfo(imsi, neId, data)
s.udmSubService.Insert(neId, u) s.udmSubService.Insert(neId, u)
c.JSON(200, result.OkData(u)) c.JSON(200, resp.OkData(u))
} }
// UDM签约用户新增 // UDM签约用户新增
@@ -153,30 +153,34 @@ func (s *UDMSubController) Info(c *gin.Context) {
// @Description UDM Subscriber User Added // @Description UDM Subscriber User Added
// @Router /neData/udm/sub/{neId} [post] // @Router /neData/udm/sub/{neId} [post]
func (s *UDMSubController) Add(c *gin.Context) { func (s *UDMSubController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMSubUser var body model.UDMSubUser
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil || len(body.IMSI) < 15 { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if len(body.IMSI) != 15 {
c.JSON(400, resp.CodeMsg(40010, "bind err: IMSI length is not 15 bits"))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -186,7 +190,7 @@ func (s *UDMSubController) Add(c *gin.Context) {
cmd += s.udmSubService.ParseCommandParams(body) cmd += s.udmSubService.ParseCommandParams(body)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -195,7 +199,7 @@ func (s *UDMSubController) Add(c *gin.Context) {
body.NeId = neId body.NeId = neId
s.udmSubService.Insert(neId, body) s.udmSubService.Insert(neId, body)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM签约用户批量新增 // UDM签约用户批量新增
@@ -214,31 +218,35 @@ func (s *UDMSubController) Add(c *gin.Context) {
// @Description UDM Subscriber User Batch Add // @Description UDM Subscriber User Batch Add
// @Router /neData/udm/sub/{neId}/{value} [post] // @Router /neData/udm/sub/{neId}/{value} [post]
func (s *UDMSubController) Adds(c *gin.Context) { func (s *UDMSubController) Adds(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
num := c.Param("num") num := c.Param("num")
if neId == "" || num == "" { if neId == "" || num == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMSubUser var body model.UDMSubUser
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil || len(body.IMSI) < 15 { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if len(body.IMSI) != 15 {
c.JSON(400, resp.CodeMsg(40010, "bind err: IMSI length is not 15 bits"))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -251,7 +259,7 @@ func (s *UDMSubController) Adds(c *gin.Context) {
cmd = strings.Replace(cmd, omemsisdn, ",", 1) cmd = strings.Replace(cmd, omemsisdn, ",", 1)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -259,7 +267,7 @@ func (s *UDMSubController) Adds(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmSubService.LoadData(neId, body.IMSI, num, body.Remark) s.udmSubService.LoadData(neId, body.IMSI, num, body.Remark)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM签约用户修改 // UDM签约用户修改
@@ -277,30 +285,34 @@ func (s *UDMSubController) Adds(c *gin.Context) {
// @Description UDM Subscriber User Modification // @Description UDM Subscriber User Modification
// @Router /neData/udm/sub/{neId} [put] // @Router /neData/udm/sub/{neId} [put]
func (s *UDMSubController) Edit(c *gin.Context) { func (s *UDMSubController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
if neId == "" { if neId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
var body model.UDMSubUser var body model.UDMSubUser
err := c.ShouldBindBodyWith(&body, binding.JSON) if err := c.ShouldBindBodyWithJSON(&body); err != nil {
if err != nil || len(body.IMSI) < 15 { errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if len(body.IMSI) != 15 {
c.JSON(400, resp.CodeMsg(40010, "bind err: IMSI length is not 15 bits"))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -310,7 +322,7 @@ func (s *UDMSubController) Edit(c *gin.Context) {
cmd += s.udmSubService.ParseCommandParams(body) cmd += s.udmSubService.ParseCommandParams(body)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -319,7 +331,7 @@ func (s *UDMSubController) Edit(c *gin.Context) {
body.NeId = neId body.NeId = neId
s.udmSubService.Insert(neId, body) s.udmSubService.Insert(neId, body)
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM签约用户删除 // UDM签约用户删除
@@ -337,11 +349,11 @@ func (s *UDMSubController) Edit(c *gin.Context) {
// @Description UDM Subscriber User Deletion // @Description UDM Subscriber User Deletion
// @Router /neData/udm/sub/{neId}/{value} [delete] // @Router /neData/udm/sub/{neId}/{value} [delete]
func (s *UDMSubController) Remove(c *gin.Context) { func (s *UDMSubController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
if neId == "" || len(imsi) < 15 { if neId == "" || len(imsi) < 15 {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
@@ -349,20 +361,20 @@ func (s *UDMSubController) Remove(c *gin.Context) {
imsiArr := strings.Split(imsi, ",") imsiArr := strings.Split(imsi, ",")
uniqueIDs := parse.RemoveDuplicates(imsiArr) uniqueIDs := parse.RemoveDuplicates(imsiArr)
if len(uniqueIDs) <= 0 { if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil)) c.JSON(200, resp.Err(nil))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -383,7 +395,7 @@ func (s *UDMSubController) Remove(c *gin.Context) {
resultData[imsi] = data resultData[imsi] = data
} }
c.JSON(200, result.OkData(resultData)) c.JSON(200, resp.OkData(resultData))
} }
// UDM签约用户批量删除 // UDM签约用户批量删除
@@ -402,25 +414,25 @@ func (s *UDMSubController) Remove(c *gin.Context) {
// @Description UDM Subscriber User Batch Deletion // @Description UDM Subscriber User Batch Deletion
// @Router /neData/udm/sub/{neId}/{imsi}/{num} [delete] // @Router /neData/udm/sub/{neId}/{imsi}/{num} [delete]
func (s *UDMSubController) Removes(c *gin.Context) { func (s *UDMSubController) Removes(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
neId := c.Param("neId") neId := c.Param("neId")
imsi := c.Param("imsi") imsi := c.Param("imsi")
num := c.Param("num") num := c.Param("num")
if neId == "" || len(imsi) < 15 || num == "" { if neId == "" || len(imsi) < 15 || num == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", neId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
if neInfo.NeId != neId || neInfo.IP == "" { if neInfo.NeId != neId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -429,7 +441,7 @@ func (s *UDMSubController) Removes(c *gin.Context) {
cmd := fmt.Sprintf("bde udmuser:start_imsi=%s,sub_num=%s", imsi, num) cmd := fmt.Sprintf("bde udmuser:start_imsi=%s,sub_num=%s", imsi, num)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -437,56 +449,59 @@ func (s *UDMSubController) Removes(c *gin.Context) {
if strings.Contains(data, "ok") { if strings.Contains(data, "ok") {
s.udmSubService.LoadData(neId, imsi, num, "-(Deleted)-") s.udmSubService.LoadData(neId, imsi, num, "-(Deleted)-")
} }
c.JSON(200, result.OkData(data)) c.JSON(200, resp.OkData(data))
} }
// UDM签约用户导出 // UDM签约用户导出
// //
// POST /export // GET /export
// //
// @Tags network_data/udm/sub // @Tags network_data/udm/sub
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param data body object true "Request Param" // @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results" // @Param type query string true "File Type" Enums(csv,txt) default(txt)
// @Param imsi query string false "IMSI"
// @Param msisdn query string false "Msisdn"
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth // @Security TokenAuth
// @Summary UDM Subscriber User Export // @Summary UDM Subscriber User Export
// @Description UDM Subscriber User Export // @Description UDM Subscriber User Export
// @Router /neData/udm/sub/export [post] // @Router /neData/udm/sub/export [post]
func (s *UDMSubController) Export(c *gin.Context) { func (s *UDMSubController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
// 查询结果,根据查询条件结果,单页最大值限制 // 查询结果,根据查询条件结果,单页最大值限制
querys := ctx.BodyJSONMap(c) neId := c.Query("neId")
neId := querys["neId"].(string) fileType := c.Query("type")
fileType := querys["type"].(string)
if neId == "" || fileType == "" { if neId == "" || fileType == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
if !(fileType == "csv" || fileType == "txt") { if !(fileType == "csv" || fileType == "txt") {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat")))
return return
} }
querys["pageNum"] = 1 query := reqctx.QueryMap(c)
querys["pageSize"] = 10000 total, rows := s.udmSubService.FindByPage(query)
total, rows := s.udmSubService.SelectPage(querys)
if total == 0 { if total == 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
// rows := s.udmSubService.SelectList(model.UDMSubUser{NeId: neId}) // rows := s.udmSubService.SelectList(model.UDMSubUser{NeId: neId})
if len(rows) <= 0 { if len(rows) <= 0 {
// 导出数据记录为空 // 导出数据记录为空
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
return return
} }
// 文件名 // 文件名
fileName := fmt.Sprintf("udm_sub_user_export_%s_%d.%s", neId, time.Now().UnixMilli(), fileType) fileName := fmt.Sprintf("udm_sub_user_export_%s_%d.%s", neId, time.Now().UnixMilli(), fileType)
filePath := filepath.Join(file.ParseUploadFileDir(uploadsubpath.EXPORT), fileName) filePath := filepath.Join(file.ParseUploadFileDir(constants.UPLOAD_EXPORT), fileName)
if fileType == "csv" { if fileType == "csv" {
// 转换数据 // 转换数据
@@ -498,7 +513,7 @@ func (s *UDMSubController) Export(c *gin.Context) {
} }
// 输出到文件 // 输出到文件
if err := file.WriterFileCSV(data, filePath); err != nil { if err := file.WriterFileCSV(data, filePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
} }
@@ -512,7 +527,7 @@ func (s *UDMSubController) Export(c *gin.Context) {
} }
// 输出到文件 // 输出到文件
if err := file.WriterFileTXT(data, ",", filePath); err != nil { if err := file.WriterFileTXT(data, ",", filePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
} }
@@ -534,57 +549,58 @@ func (s *UDMSubController) Export(c *gin.Context) {
// @Description UDM Subscriber User Import // @Description UDM Subscriber User Import
// @Router /neData/udm/sub/import [post] // @Router /neData/udm/sub/import [post]
func (s *UDMSubController) Import(c *gin.Context) { func (s *UDMSubController) Import(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var body struct { var body struct {
NeId string `json:"neId" binding:"required"` NeId string `json:"neId" binding:"required"`
UploadPath string `json:"uploadPath" binding:"required"` UploadPath string `json:"uploadPath" binding:"required"`
} }
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil { if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return return
} }
// 判断文件名 // 判断文件名
if !(strings.HasSuffix(body.UploadPath, ".csv") || strings.HasSuffix(body.UploadPath, ".txt")) { if !(strings.HasSuffix(body.UploadPath, ".csv") || strings.HasSuffix(body.UploadPath, ".txt")) {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UDM", body.NeId) neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" { if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
// 网元主机的SSH客户端 // 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId) sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer sshClient.Close() defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输 // 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP() sftpClient, err := sshClient.NewClientSFTP()
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer sftpClient.Close() defer sftpClient.Close()
// 本地文件 // 本地文件
localFilePath := file.ParseUploadFilePath(body.UploadPath) localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath)) neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
// 复制到远程 // 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil { if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
c.JSON(200, result.ErrMsg("error uploading file")) c.JSON(200, resp.ErrMsg("error uploading file"))
return return
} }
// 网元主机的Telnet客户端 // 网元主机的Telnet客户端
telnetClient, err := s.neInfoService.NeRunTelnetClient(neInfo.NeType, neInfo.NeId, 1) telnetClient, err := s.neInfoService.NeRunTelnetClient(neInfo.NeType, neInfo.NeId, 1)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
defer telnetClient.Close() defer telnetClient.Close()
@@ -593,7 +609,7 @@ func (s *UDMSubController) Import(c *gin.Context) {
cmd := fmt.Sprintf("import udmuser:path=%s", neFilePath) cmd := fmt.Sprintf("import udmuser:path=%s", neFilePath)
data, err := telnet.ConvertToStr(telnetClient, cmd) data, err := telnet.ConvertToStr(telnetClient, cmd)
if err != nil { if err != nil {
c.JSON(200, result.ErrMsg(err.Error())) c.JSON(200, resp.ErrMsg(err.Error()))
return return
} }
@@ -608,5 +624,5 @@ func (s *UDMSubController) Import(c *gin.Context) {
go s.udmSubService.InsertData(neInfo.NeId, "txt", data) go s.udmSubService.InsertData(neInfo.NeId, "txt", data)
} }
} }
c.JSON(200, result.OkMsg(data)) c.JSON(200, resp.OkMsg(data))
} }

View File

@@ -2,25 +2,26 @@ package controller
import ( import (
"be.ems/src/framework/i18n" "be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx" "be.ems/src/framework/reqctx"
"be.ems/src/framework/vo/result" "be.ems/src/framework/resp"
neDataService "be.ems/src/modules/network_data/service" neDataService "be.ems/src/modules/network_data/service"
neService "be.ems/src/modules/network_element/service" neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 实例化控制层 UPFController 结构体 // 实例化控制层 UPFController 结构体
var NewUPF = &UPFController{ var NewUPF = &UPFController{
neInfoService: neService.NewNeInfo, neInfoService: neService.NewNeInfo,
perfKPIService: neDataService.NewPerfKPI, kpiReportService: neDataService.NewKpiReport,
} }
// 网元UPF // 网元UPF
// //
// PATH /upf // PATH /upf
type UPFController struct { type UPFController struct {
neInfoService *neService.NeInfo // 网元信息服务 neInfoService *neService.NeInfo // 网元信息服务
perfKPIService *neDataService.PerfKPI // 统计信息服务 kpiReportService *neDataService.KpiReport // 统计信息服务
} }
// 总流量数 N3上行 N6下行 // 总流量数 N3上行 N6下行
@@ -38,25 +39,24 @@ type UPFController struct {
// @Summary Total number of flows N3 upstream N6 downstream // @Summary Total number of flows N3 upstream N6 downstream
// @Description Total number of flows N3 upstream N6 downstream // @Description Total number of flows N3 upstream N6 downstream
// @Router /neData/upf/totalFlow [get] // @Router /neData/upf/totalFlow [get]
func (s *UPFController) TotalFlow(c *gin.Context) { func (s UPFController) TotalFlow(c *gin.Context) {
language := ctx.AcceptLanguage(c) language := reqctx.AcceptLanguage(c)
var querys struct { var querys struct {
NeID string `form:"neId" binding:"required"` NeID string `form:"neId" binding:"required"`
Day int `form:"day"` Day int `form:"day"`
} }
if err := c.ShouldBindQuery(&querys); querys.Day < 0 || err != nil { if err := c.ShouldBindQuery(&querys); querys.Day < 0 || err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400"))) c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return return
} }
// 查询网元获取IP // 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("UPF", querys.NeID) neInfo := s.neInfoService.FindByNeTypeAndNeID("UPF", querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" { if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo"))) c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return return
} }
data := s.perfKPIService.SelectUPFTotalFlow(neInfo.NeType, neInfo.RmUID, querys.Day) data := s.kpiReportService.FindUPFTotalFlow(neInfo.RmUID, querys.Day)
c.JSON(200, resp.OkData(data))
c.JSON(200, result.OkData(data))
} }

View File

@@ -1,40 +1,36 @@
package model package model
import "time" // Alarm 告警记录
// Alarm 告警数据对象 alarm
type Alarm struct { type Alarm struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
AlarmSeq string `json:"alarmSeq" gorm:"column:alarm_seq"` NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
AlarmId string `json:"alarmId" gorm:"column:alarm_id"` NeId string `json:"neId" gorm:"column:ne_id"` // 网元ID
AlarmTitle string `json:"alarmTitle" gorm:"column:alarm_title"` NeName string `json:"neName" gorm:"column:ne_name"` // 网元名称
NeType string `json:"neType" gorm:"column:ne_type"` Province string `json:"province" gorm:"column:province"` // 网元省份地域
NeId string `json:"neId" gorm:"column:ne_id"` PvFlag string `json:"pvFlag" gorm:"column:pv_flag"` // 网元标识虚拟化标识
AlarmCode string `json:"alarmCode" gorm:"column:alarm_code"` AlarmSeq int64 `json:"alarmSeq" gorm:"column:alarm_seq"` // 告警序号 同网元类型连续递增
EventTime time.Time `json:"eventTime" gorm:"column:event_time"` AlarmId string `json:"alarmId" gorm:"column:alarm_id"` // 告警ID
AlarmType string `json:"alarmType" gorm:"column:alarm_type"` AlarmTitle string `json:"alarmTitle" gorm:"column:alarm_title"` // 告警标题
OrigSeverity string `json:"origSeverity" gorm:"column:orig_severity"` // 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF) AlarmCode int64 `json:"alarmCode" gorm:"column:alarm_code"` // 告警状态码
PerceivedSeverity string `json:"perceivedSeverity" gorm:"column:perceived_severity"` // 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF) EventTime int64 `json:"eventTime" gorm:"column:event_time"` // 事件产生时间 秒级
PvFlag string `json:"pvFlag" gorm:"column:pv_flag"` AlarmType string `json:"alarmType" gorm:"column:alarm_type"` // 告警类型 CommunicationAlarm=1,EquipmentAlarm=2,ProcessingFailure=3,EnvironmentalAlarm=4,QualityOfServiceAlarm=5
NeName string `json:"neName" gorm:"column:ne_name"` OrigSeverity string `json:"origSeverity" gorm:"column:orig_severity"` // 严重程度 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF)
ObjectUid string `json:"objectUid" gorm:"column:object_uid"` PerceivedSeverity string `json:"perceivedSeverity" gorm:"column:perceived_severity"` // 告警级别 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF)
ObjectName string `json:"objectName" gorm:"column:object_name"` ObjectUid string `json:"objectUid" gorm:"column:object_uid"` // 对象ID
ObjectType string `json:"objectType" gorm:"column:object_type"` ObjectName string `json:"objectName" gorm:"column:object_name"` // 对象名称
LocationInfo string `json:"locationInfo" gorm:"column:location_info"` ObjectType string `json:"objectType" gorm:"column:object_type"` // 对象类型
Province string `json:"province" gorm:"column:province"` LocationInfo string `json:"locationInfo" gorm:"column:location_info"` // 告警定位信息
AlarmStatus string `json:"alarmStatus" gorm:"column:alarm_status"` // 0:clear, 1:active AlarmStatus string `json:"alarmStatus" gorm:"column:alarm_status"` // 告警状态 0:clear, 1:active
SpecificProblem string `json:"specificProblem" gorm:"column:specific_problem"` SpecificProblem string `json:"specificProblem" gorm:"column:specific_problem"` // 告警问题原因
SpecificProblemId string `json:"specificProblemId" gorm:"column:specific_problem_id"` SpecificProblemId string `json:"specificProblemId" gorm:"column:specific_problem_id"` // 告警问题原因ID
AddInfo string `json:"addInfo" gorm:"column:add_info"` AddInfo string `json:"addInfo" gorm:"column:add_info"` // 告警辅助信息
Counter string `json:"counter" gorm:"column:counter"` AckState int64 `json:"ackState" gorm:"column:ack_state"` // 确认状态 0: Unacked, 1: Acked
LatestEventTime time.Time `json:"latestEventTime" gorm:"column:latest_event_time"` AckTime int64 `json:"ackTime" gorm:"column:ack_time"` // 确认时间 秒级
AckState string `json:"ackState" gorm:"column:ack_state"` // 0: Unacked, 1: Acked AckUser string `json:"ackUser" gorm:"column:ack_user"` // 确认用户
AckTime time.Time `json:"ackTime" gorm:"column:ack_time"` ClearType int64 `json:"clearType" gorm:"column:clear_type"` // 清除状态 0: Unclear, 1: AutoClear, 2: ManualClear
AckUser string `json:"ackUser" gorm:"column:ack_user"` ClearTime int64 `json:"clearTime" gorm:"column:clear_time"` // 清除时间
ClearType string `json:"clearType" gorm:"column:clear_type"` // 0: Unclear, 1: AutoClear, 2: ManualClear ClearUser string `json:"clearUser" gorm:"column:clear_user"` // 清除用户
ClearTime time.Time `json:"clearTime" gorm:"column:clear_time"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 创建时间
ClearUser string `json:"clearUser" gorm:"column:clear_user"`
Timestamp time.Time `json:"timestamp" gorm:"column:timestamp"`
} }
// TableName 表名称 // TableName 表名称
@@ -44,14 +40,18 @@ func (*Alarm) TableName() string {
// AlarmQuery 告警数据查询参数结构体 // AlarmQuery 告警数据查询参数结构体
type AlarmQuery struct { type AlarmQuery struct {
NeType string `json:"neType" form:"neType" binding:"required"` // 网元类型 NeType string `json:"neType" form:"neType"` // 网元类型
NeID string `json:"neId" form:"neId" binding:"required"` NeID string `json:"neId" form:"neId"` // 网元ID
RmUID string `json:"rmUID" form:"rmUID"` NeName string `json:"neName" form:"neName"`
OrigSeverity string `json:"origSeverity" form:"origSeverity"` // 告警类型 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF) PvFlag string `json:"pvFlag" form:"pvFlag"`
StartTime string `json:"startTime" form:"startTime"` AlarmCode string `json:"alarmCode" form:"alarmCode"`
EndTime string `json:"endTime" form:"endTime"` AlarmType string `json:"alarmType" form:"alarmType"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"omitempty,oneof=0 1"` // 告警状态 0:clear, 1:active
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc OrigSeverity string `json:"origSeverity" form:"origSeverity"` // 告警类型 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF)
BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查event_time
EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=event_time id"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`
PageSize int64 `json:"pageSize" form:"pageSize" binding:"required"` PageSize int64 `json:"pageSize" form:"pageSize" binding:"required"`
} }

View File

@@ -0,0 +1,44 @@
package model
// AlarmEvent 告警_事件记录表
type AlarmEvent struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
NeId string `json:"neId" gorm:"column:ne_id"` // 网元ID
AlarmSeq int64 `json:"alarmSeq" gorm:"column:alarm_seq"` // 告警序号 同网元类型连续递增
AlarmId string `json:"alarmId" gorm:"column:alarm_id"` // 告警ID
AlarmTitle string `json:"alarmTitle" gorm:"column:alarm_title"` // 告警标题
AlarmCode int64 `json:"alarmCode" gorm:"column:alarm_code"` // 告警状态码
EventTime int64 `json:"eventTime" gorm:"column:event_time"` // 事件产生时间 秒级
ObjectUid string `json:"objectUid" gorm:"column:object_uid"` // 对象ID
ObjectName string `json:"objectName" gorm:"column:object_name"` // 对象名称
ObjectType string `json:"objectType" gorm:"column:object_type"` // 对象类型
LocationInfo string `json:"locationInfo" gorm:"column:location_info"` // 告警定位信息
AlarmStatus string `json:"alarmStatus" gorm:"column:alarm_status"` // 告警状态 0:clear, 1:active
SpecificProblem string `json:"specificProblem" gorm:"column:specific_problem"` // 告警问题原因
SpecificProblemId string `json:"specificProblemId" gorm:"column:specific_problem_id"` // 告警问题原因ID
AddInfo string `json:"addInfo" gorm:"column:add_info"` // 告警辅助信息
ClearType int64 `json:"clearType" gorm:"column:clear_type"` // 清除状态 0: Unclear, 1: AutoClear, 2: ManualClear
ClearTime int64 `json:"clearTime" gorm:"column:clear_time"` // 清除时间
ClearUser string `json:"clearUser" gorm:"column:clear_user"` // 清除用户
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 创建时间
}
// TableName 表名称
func (*AlarmEvent) TableName() string {
return "alarm_event"
}
// AlarmEventQuery 告警事件数据查询参数结构体
type AlarmEventQuery struct {
NeType string `json:"neType" form:"neType"` // 网元类型
NeID string `json:"neId" form:"neId"` // 网元ID
AlarmCode string `json:"alarmCode" form:"alarmCode"`
AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"omitempty,oneof=0 1"` // 告警状态 0:clear, 1:active
BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查event_time
EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=event_time id"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`
PageSize int64 `json:"pageSize" form:"pageSize" binding:"required"`
}

View File

@@ -0,0 +1,38 @@
package model
// AlarmForwardLog 告警_转发日志记录
type AlarmForwardLog struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
NeId string `json:"neId" gorm:"column:ne_id"`
AlarmSeq int64 `json:"alarmSeq" gorm:"column:alarm_seq"` // 告警序号 同网元类型连续递增
AlarmId string `json:"alarmId" gorm:"column:alarm_id"` // 告警ID
AlarmCode int64 `json:"alarmCode" gorm:"column:alarm_code"` // 告警状态码
AlarmTitle string `json:"alarmTitle" gorm:"column:alarm_title"` // 告警标题
AlarmStatus string `json:"alarmStatus" gorm:"column:alarm_status"` // 告警状态 0:clear, 1:active
OrigSeverity string `json:"origSeverity" gorm:"column:orig_severity"` // 严重程度 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF)
EventTime int64 `json:"eventTime" gorm:"column:event_time"` // 事件产生时间 秒级
CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 创建时间
Type string `json:"type" gorm:"column:type"` // 转发方式 SMS/EMAIL
Target string `json:"target" gorm:"column:target"` // 发送目标用户
Result string `json:"result" gorm:"column:result"` // 发送结果
}
// TableName 表名称
func (*AlarmForwardLog) TableName() string {
return "alarm_forward_log"
}
// AlarmForwardLogQuery 告警转发日志数据查询参数结构体
type AlarmForwardLogQuery struct {
NeType string `json:"neType" form:"neType"` // 网元类型
NeID string `json:"neId" form:"neId"` // 网元ID
NeName string `json:"neName" form:"neName"`
AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"omitempty,oneof=0 1"` // 告警状态 0:clear, 1:active
BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查event_time
EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=event_time id"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`
PageSize int64 `json:"pageSize" form:"pageSize" binding:"required"`
}

View File

@@ -0,0 +1,35 @@
package model
// AlarmLog 告警_日志记录
type AlarmLog struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
NeId string `json:"neId" gorm:"column:ne_id"`
AlarmSeq int64 `json:"alarmSeq" gorm:"column:alarm_seq"` // 告警序号 同网元类型连续递增
AlarmId string `json:"alarmId" gorm:"column:alarm_id"` // 告警ID
AlarmCode int64 `json:"alarmCode" gorm:"column:alarm_code"` // 告警状态码
AlarmTitle string `json:"alarmTitle" gorm:"column:alarm_title"` // 告警标题
AlarmStatus string `json:"alarmStatus" gorm:"column:alarm_status"` // 告警状态 0:clear, 1:active
OrigSeverity string `json:"origSeverity" gorm:"column:orig_severity"` // 严重程度 1: Critical, 2: Major, 3: Minor, 4: Warning, 5: Event(Only VNF)
EventTime int64 `json:"eventTime" gorm:"column:event_time"` // 事件产生时间 秒级
CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 创建时间
}
// TableName 表名称
func (*AlarmLog) TableName() string {
return "alarm_log"
}
// AlarmLogQuery 告警日志数据查询参数结构体
type AlarmLogQuery struct {
NeType string `json:"neType" form:"neType"` // 网元类型
NeID string `json:"neId" form:"neId"` // 网元ID
NeName string `json:"neName" form:"neName"`
AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"omitempty,oneof=0 1"` // 告警状态 0:clear, 1:active
BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查event_time
EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=event_time id"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`
PageSize int64 `json:"pageSize" form:"pageSize" binding:"required"`
}

View File

@@ -1,16 +1,14 @@
package model package model
import "time"
// CDREventIMS CDR会话对象IMS cdr_event_ims // CDREventIMS CDR会话对象IMS cdr_event_ims
type CDREventIMS struct { type CDREventIMS struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` RmUid string `json:"rmUid" gorm:"column:rm_uid"`
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
CDRJSONStr string `json:"cdrJSON" gorm:"column:cdr_json"` CdrJson string `json:"cdrJSON" gorm:"column:cdr_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
} }
// TableName 表名称 // TableName 表名称
@@ -26,8 +24,8 @@ type CDREventIMSQuery struct {
RecordType string `json:"recordType" form:"recordType"` // 记录行为 MOC MTC RecordType string `json:"recordType" form:"recordType"` // 记录行为 MOC MTC
CallerParty string `json:"callerParty" form:"callerParty"` // 主叫号码 CallerParty string `json:"callerParty" form:"callerParty"` // 主叫号码
CalledParty string `json:"calledParty" form:"calledParty"` // 被叫号码 CalledParty string `json:"calledParty" form:"calledParty"` // 被叫号码
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -1,18 +1,14 @@
package model package model
import "time"
// CDREventSGWC CDR会话对象SGWC cdr_event_sgwc // CDREventSGWC CDR会话对象SGWC cdr_event_sgwc
type CDREventSGWC struct { type CDREventSGWC struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` RmUid string `json:"rmUid" gorm:"column:rm_uid"`
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
CDRJSONStr string `json:"cdrJSON" gorm:"column:cdr_json"` CdrJson string `json:"cdrJSON" gorm:"column:cdr_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
// ====== 非数据库字段属性 ======
} }
// TableName 表名称 // TableName 表名称
@@ -27,8 +23,8 @@ type CDREventSGWCQuery struct {
RmUID string `json:"rmUID" form:"rmUID"` RmUID string `json:"rmUID" form:"rmUID"`
IMSI string `json:"imsi" form:"imsi"` IMSI string `json:"imsi" form:"imsi"`
MSISDN string `json:"msisdn" form:"msisdn"` MSISDN string `json:"msisdn" form:"msisdn"`
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -1,18 +1,14 @@
package model package model
import "time"
// CDREventSMF CDR会话对象SMF cdr_event_smf // CDREventSMF CDR会话对象SMF cdr_event_smf
type CDREventSMF struct { type CDREventSMF struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` RmUid string `json:"rmUid" gorm:"column:rm_uid"`
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
CDRJSONStr string `json:"cdrJSON" gorm:"column:cdr_json"` CdrJson string `json:"cdrJSON" gorm:"column:cdr_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
// ====== 非数据库字段属性 ======
} }
// TableName 表名称 // TableName 表名称
@@ -28,8 +24,8 @@ type CDREventSMFQuery struct {
RecordType string `json:"recordType" form:"recordType"` // 暂时没用到 RecordType string `json:"recordType" form:"recordType"` // 暂时没用到
SubscriberID string `json:"subscriberID" form:"subscriberID"` SubscriberID string `json:"subscriberID" form:"subscriberID"`
DNN string `json:"dnn" form:"dnn"` DNN string `json:"dnn" form:"dnn"`
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -1,16 +1,14 @@
package model package model
import "time"
// CDREventSMSC CDR会话对象SMSC cdr_event_smsc // CDREventSMSC CDR会话对象SMSC cdr_event_smsc
type CDREventSMSC struct { type CDREventSMSC struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` // 可能没有 RmUid string `json:"rmUid" gorm:"column:rm_uid"` // 可能没有
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
CDRJSONStr string `json:"cdrJSON" gorm:"column:cdr_json"` CdrJson string `json:"cdrJSON" gorm:"column:cdr_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
} }
// TableName 表名称 // TableName 表名称
@@ -26,8 +24,8 @@ type CDREventSMSCQuery struct {
RecordType string `json:"recordType" form:"recordType"` // 记录行为 MOSM MTSM RecordType string `json:"recordType" form:"recordType"` // 记录行为 MOSM MTSM
CallerParty string `json:"callerParty" form:"callerParty"` // 主叫号码 CallerParty string `json:"callerParty" form:"callerParty"` // 主叫号码
CalledParty string `json:"calledParty" form:"calledParty"` // 被叫号码 CalledParty string `json:"calledParty" form:"calledParty"` // 被叫号码
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -0,0 +1,52 @@
package model
// KpiCTitle 自定义指标标题信息对象 kpi_title
type KpiCTitle struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
KpiId string `json:"kpiId" gorm:"column:kpi_id"`
Title string `json:"title" gorm:"column:title"`
Expression string `json:"expression" gorm:"column:expression"`
Unit string `json:"unit" gorm:"column:unit"`
Status string `json:"status" gorm:"column:status"` // 0-Inactive/1-Active/2-Deleted
Description string `json:"description" gorm:"column:description"`
CreatedBy string `json:"createdBy" gorm:"column:created_by"`
UpdatedAt int64 `json:"updatedAt" gorm:"column:updated_at"`
}
// TableName 表名称
func (*KpiCTitle) TableName() string {
return "kpi_c_title"
}
// KpiCReport 自定义指标报表信息对象
type KpiCReport struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"`
RmUid string `json:"rmUid" gorm:"column:rm_uid"`
Date string `json:"date" gorm:"column:date"` // Date of the report yyyy-mm-dd hh:mi:ss
StartTime string `json:"startTime" gorm:"column:start_time"` // Start time of the report hh:mi:ss
EndTime string `json:"endTime" gorm:"column:end_time"` // End time of the report hh:mi:ss
Index int64 `json:"index" gorm:"column:index"` // Index of the report
Granularity int64 `json:"granularity" gorm:"column:granularity"` // Time granualarity: 5/10/.../60/300 (second)
KpiValues string `json:"kpiValues" gorm:"column:kpi_values"` // KPI values JSON String
CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // Creation time
}
// TableName 表名称
func (*KpiCReport) TableName() string {
return "kpi_c_report"
}
// KPICQuery 指标查询参数结构体
type KPICQuery struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
BeginTime int64 `form:"beginTime" binding:"required"` // 开始时间戳毫秒1739361200999
EndTime int64 `form:"endTime" binding:"required"` // 结束时间戳毫秒1739361210088
Interval int64 `form:"interval" binding:"required,oneof=5 60 300 900 1800 3600"`
RmUID string `form:"rmUID"`
SortField string `form:"sortField" binding:"omitempty,oneof=timeGroup"`
SortOrder string `form:"sortOrder" binding:"omitempty,oneof=asc desc"`
}

View File

@@ -0,0 +1,48 @@
package model
// KpiTitle 指标标题信息对象 kpi_title
type KpiTitle struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
KpiId string `json:"kpiId" gorm:"column:kpi_id"` // KPI标识
TitleJson string `json:"titleJson" gorm:"column:title_json"`
CnTitle string `json:"cnTitle" gorm:"column:cn_title"` // 中文名
EnTitle string `json:"enTitle" gorm:"column:en_title"` // 英文名
}
// TableName 表名称
func (*KpiTitle) TableName() string {
return "kpi_title"
}
// KpiReport 指标报表信息对象
type KpiReport struct {
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"`
RmUid string `json:"rmUid" gorm:"column:rm_uid"`
Date string `json:"date" gorm:"column:date"` // Date of the report yyyy-mm-dd hh:mi:ss
StartTime string `json:"startTime" gorm:"column:start_time"` // Start time of the report hh:mi:ss
EndTime string `json:"endTime" gorm:"column:end_time"` // End time of the report hh:mi:ss
Index int64 `json:"index" gorm:"column:index"` // Index of the report
Granularity int64 `json:"granularity" gorm:"column:granularity"` // Time granualarity: 5/10/.../60/300 (second)
KpiValues string `json:"kpiValues" gorm:"column:kpi_values"` // KPI values JSON String
CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // Creation time 接收到的timestamp秒级存储毫秒时间戳
}
// TableName 表名称
func (*KpiReport) TableName() string {
return "kpi_report"
}
// KPIQuery 指标查询参数结构体
type KPIQuery struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
BeginTime int64 `form:"beginTime" binding:"required"` // 开始时间戳毫秒1739361200999
EndTime int64 `form:"endTime" binding:"required"` // 结束时间戳毫秒1739361210088
Interval int64 `form:"interval" binding:"required,oneof=5 60 300 900 1800 3600"`
RmUID string `form:"rmUID"`
SortField string `form:"sortField" binding:"omitempty,oneof=timeGroup"`
SortOrder string `form:"sortOrder" binding:"omitempty,oneof=asc desc"`
}

View File

@@ -1,23 +0,0 @@
package model
// GoldKPITitle 黄金指标标题信息对象 kpi_title
type GoldKPITitle struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"`
KPIID string `json:"kpiId" gorm:"column:kpi_id"`
TitleJson string `json:"titleJson" gorm:"column:title_json"`
CnTitle string `json:"cnTitle" gorm:"column:cn_title"`
EnTitle string `json:"enTitle" gorm:"column:en_title"`
}
// GoldKPIQuery 黄金指标查询参数结构体
type GoldKPIQuery struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
StartTime string `form:"startTime" binding:"required"`
EndTime string `form:"endTime" binding:"required"`
Interval int64 `form:"interval" binding:"required,oneof=5 60 300 900 1800 3600"`
RmUID string `form:"rmUID"`
SortField string `form:"sortField" binding:"omitempty,oneof=timeGroup"`
SortOrder string `form:"sortOrder" binding:"omitempty,oneof=asc desc"`
}

View File

@@ -1,6 +1,6 @@
package model package model
// UDMAuthUser UDM鉴权用户 u_auth_user // UDMAuthUser UDM鉴权用户 udm_auth
type UDMAuthUser struct { type UDMAuthUser struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 默认ID ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 默认ID
IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID
@@ -13,5 +13,5 @@ type UDMAuthUser struct {
// TableName 表名称 // TableName 表名称
func (*UDMAuthUser) TableName() string { func (*UDMAuthUser) TableName() string {
return "u_auth_user" return "udm_auth"
} }

View File

@@ -1,7 +1,7 @@
package model package model
// UDMUserInfo UDM用户IMSI扩展信息 u_user_info // UDMExtend UDM用户IMSI扩展信息 udm_extend
type UDMUserInfo struct { type UDMExtend struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 默认ID ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 默认ID
IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID
MSISDN string `json:"msisdn" gorm:"column:msisdn"` // 用户电话号码 MSISDN string `json:"msisdn" gorm:"column:msisdn"` // 用户电话号码
@@ -10,6 +10,6 @@ type UDMUserInfo struct {
} }
// TableName 表名称 // TableName 表名称
func (*UDMUserInfo) TableName() string { func (*UDMExtend) TableName() string {
return "u_user_info" return "udm_extend"
} }

View File

@@ -1,6 +1,6 @@
package model package model
// UDMSubUser UDM签约用户 u_sub_user // UDMSubUser UDM签约用户 udm_sub
type UDMSubUser struct { type UDMSubUser struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 主键 ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 主键
IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID
@@ -44,5 +44,5 @@ type UDMSubUser struct {
// TableName 表名称 // TableName 表名称
func (*UDMSubUser) TableName() string { func (*UDMSubUser) TableName() string {
return "u_sub_user" return "udm_sub"
} }

View File

@@ -1,17 +1,15 @@
package model package model
import "time"
// UEEventAMF UE会话对象AMF ue_event_amf // UEEventAMF UE会话对象AMF ue_event_amf
type UEEventAMF struct { type UEEventAMF struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` // 可能没有 RmUID string `json:"rmUID" gorm:"column:rm_uid"` // 可能没有
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
EventType string `json:"eventType" gorm:"column:event_type"` // 事件类型 auth-result detach cm-state EventType string `json:"eventType" gorm:"column:event_type"` // 事件类型 auth-result detach cm-state
EventJSONStr string `json:"eventJSON" gorm:"column:event_json"` EventJSONStr string `json:"eventJSON" gorm:"column:event_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
} }
// TableName 表名称 // TableName 表名称
@@ -26,8 +24,8 @@ type UEEventAMFQuery struct {
RmUID string `json:"rmUID" form:"rmUID"` RmUID string `json:"rmUID" form:"rmUID"`
EventType string `json:"eventType" form:"eventType"` // 事件类型 auth-result detach cm-state EventType string `json:"eventType" form:"eventType"` // 事件类型 auth-result detach cm-state
IMSI string `json:"imsi" form:"imsi"` // imsi IMSI string `json:"imsi" form:"imsi"` // imsi
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -1,17 +1,15 @@
package model package model
import "time"
// UEEventMME UE会话对象MME ue_event_mme // UEEventMME UE会话对象MME ue_event_mme
type UEEventMME struct { type UEEventMME struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` NeType string `json:"neType" gorm:"column:ne_type"`
NeName string `json:"neName" gorm:"column:ne_name"` NeName string `json:"neName" gorm:"column:ne_name"`
RmUID string `json:"rmUID" gorm:"column:rm_uid"` // 可能没有 RmUID string `json:"rmUID" gorm:"column:rm_uid"` // 可能没有
Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` Timestamp int64 `json:"timestamp" gorm:"column:timestamp"` // 接收到的timestamp秒级存储毫秒时间戳
EventType string `json:"eventType" gorm:"column:event_type"` // 事件类型 auth-result detach cm-state EventType string `json:"eventType" gorm:"column:event_type"` // 事件类型 auth-result detach cm-state
EventJSONStr string `json:"eventJSON" gorm:"column:event_json"` EventJSONStr string `json:"eventJSON" gorm:"column:event_json"` // data JSON String
CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` CreatedAt int64 `json:"createdAt" gorm:"column:created_at"` // 记录创建存储毫秒
} }
// TableName 表名称 // TableName 表名称
@@ -26,8 +24,8 @@ type UEEventMMEQuery struct {
RmUID string `json:"rmUID" form:"rmUID"` RmUID string `json:"rmUID" form:"rmUID"`
EventType string `json:"eventType" form:"eventType"` // 事件类型 auth-result detach cm-state EventType string `json:"eventType" form:"eventType"` // 事件类型 auth-result detach cm-state
IMSI string `json:"imsi" form:"imsi"` // imsi IMSI string `json:"imsi" form:"imsi"` // imsi
StartTime string `json:"startTime" form:"startTime"` BeginTime int64 `json:"beginTime" form:"beginTime"` // 开始时间 查timestamp
EndTime string `json:"endTime" form:"endTime"` EndTime int64 `json:"endTime" form:"endTime"`
SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段 SortField string `json:"sortField" form:"sortField" binding:"omitempty,oneof=timestamp"` // 排序字段,填写结果字段
SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc SortOrder string `json:"sortOrder" form:"sortOrder" binding:"omitempty,oneof=asc desc"` // 排序升降序asc desc
PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"` PageNum int64 `json:"pageNum" form:"pageNum" binding:"required"`

View File

@@ -21,11 +21,11 @@ func Setup(router *gin.Engine) {
{ {
kpiGroup.GET("/title", kpiGroup.GET("/title",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewPerfKPI.Title, controller.NewKPI.KPITitle,
) )
kpiGroup.GET("/data", kpiGroup.GET("/data",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewPerfKPI.GoldKPI, controller.NewKPI.KPIData,
) )
} }
@@ -36,7 +36,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewAlarm.List, controller.NewAlarm.List,
) )
alarmGroup.DELETE("/:alarmIds", alarmGroup.DELETE("/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewAlarm.Remove, controller.NewAlarm.Remove,
) )
@@ -62,7 +62,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewIMS.CDRList, controller.NewIMS.CDRList,
) )
imsGroup.DELETE("/cdr/:cdrIds", imsGroup.DELETE("/cdr/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.imsCDR", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.imsCDR", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewIMS.CDRRemove, controller.NewIMS.CDRRemove,
@@ -89,7 +89,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewSMSC.CDRList, controller.NewSMSC.CDRList,
) )
smscGroup.DELETE("/cdr/:cdrIds", smscGroup.DELETE("/cdr/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smscCDR", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smscCDR", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewSMSC.CDRRemove, controller.NewSMSC.CDRRemove,
@@ -108,7 +108,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewSMF.CDRList, controller.NewSMF.CDRList,
) )
smfGroup.DELETE("/cdr/:cdrIds", smfGroup.DELETE("/cdr/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smfCDR", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smfCDR", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewSMF.CDRRemove, controller.NewSMF.CDRRemove,
@@ -135,7 +135,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewAMF.UEList, controller.NewAMF.UEList,
) )
amfGroup.DELETE("/ue/:ueIds", amfGroup.DELETE("/ue/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.amfUE", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.amfUE", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewAMF.UERemove, controller.NewAMF.UERemove,
@@ -206,7 +206,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmAuth", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmAuth", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewUDMAuth.Removes, controller.NewUDMAuth.Removes,
) )
udmAuthGroup.POST("/export", udmAuthGroup.GET("/export",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmAuth", collectlogs.BUSINESS_TYPE_EXPORT)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmAuth", collectlogs.BUSINESS_TYPE_EXPORT)),
controller.NewUDMAuth.Export, controller.NewUDMAuth.Export,
@@ -260,7 +260,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmSub", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmSub", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewUDMSub.Removes, controller.NewUDMSub.Removes,
) )
udmSubGroup.POST("/export", udmSubGroup.GET("/export",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmSub", collectlogs.BUSINESS_TYPE_EXPORT)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.udmSub", collectlogs.BUSINESS_TYPE_EXPORT)),
controller.NewUDMSub.Export, controller.NewUDMSub.Export,
@@ -279,7 +279,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewMME.UEList, controller.NewMME.UEList,
) )
mmeGroup.DELETE("/ue/:ueIds", mmeGroup.DELETE("/ue/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.mmeUE", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.mmeUE", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewMME.UERemove, controller.NewMME.UERemove,
@@ -306,7 +306,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
controller.NewSGWC.CDRList, controller.NewSGWC.CDRList,
) )
sgwcGroup.DELETE("/cdr/:cdrIds", sgwcGroup.DELETE("/cdr/:id",
middleware.PreAuthorize(nil), middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sgwcCDR", collectlogs.BUSINESS_TYPE_DELETE)), collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.sgwcCDR", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewSGWC.CDRRemove, controller.NewSGWC.CDRRemove,

View File

@@ -0,0 +1,194 @@
package repository
import (
"strings"
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 Alarm 结构体
var NewAlarm = &Alarm{}
// Alarm 告警 数据层处理
type Alarm struct{}
// SelectByPage 分页查询集合
func (r Alarm) SelectByPage(query model.AlarmQuery) ([]model.Alarm, int64) {
tx := db.DB("").Model(&model.Alarm{})
// 查询条件拼接
if query.NeType != "" {
tx = tx.Where("ne_type = ?", query.NeType)
}
if query.NeID != "" {
tx = tx.Where("ne_id = ?", query.NeID)
}
if query.NeName != "" {
tx = tx.Where("ne_name = ?", query.NeName)
}
if query.PvFlag != "" {
tx = tx.Where("pv_flag = ?", query.PvFlag)
}
if query.AlarmCode != "" {
tx = tx.Where("alarm_code = ?", query.AlarmCode)
}
if query.AlarmType != "" {
tx = tx.Where("alarm_type in (?)", strings.Split(query.AlarmType, ","))
}
if query.AlarmStatus != "" {
tx = tx.Where("alarm_status = ?", query.AlarmStatus)
}
if query.OrigSeverity != "" {
tx = tx.Where("orig_severity in (?)", strings.Split(query.OrigSeverity, ","))
}
if query.BeginTime != 0 {
tx = tx.Where("event_time >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("event_time <= ?", query.EndTime)
}
// 查询结果
var total int64 = 0
rows := []model.Alarm{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 排序
if query.SortField != "" {
sortField := query.SortField
if query.SortOrder == "desc" {
sortField = sortField + " desc"
}
tx = tx.Order(sortField)
}
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// Select 查询集合
func (r Alarm) Select(param model.Alarm) []model.Alarm {
tx := db.DB("").Model(&model.Alarm{})
// 查询条件拼接
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if param.NeId != "" {
tx = tx.Where("ne_id = ?", param.NeId)
}
if param.NeName != "" {
tx = tx.Where("ne_name = ?", param.NeName)
}
if param.AlarmCode > 0 {
tx = tx.Where("alarm_code = ?", param.AlarmCode)
}
if param.AlarmType != "" {
tx = tx.Where("alarm_type = ?", param.AlarmType)
}
if param.AlarmId != "" {
tx = tx.Where("alarm_id = ?", param.AlarmId)
}
if param.OrigSeverity != "" {
eventTypes := strings.Split(param.OrigSeverity, ",")
tx = tx.Where("orig_severity in (%s)", eventTypes)
}
if param.PvFlag != "" {
tx = tx.Where("pv_flag = ?", param.PvFlag)
}
// 查询数据
rows := []model.Alarm{}
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// SelectByIds 通过ID查询
func (r Alarm) SelectByIds(ids []int64) []model.Alarm {
rows := []model.Alarm{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.Alarm{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息 返回新增数据ID
func (r Alarm) Insert(param model.Alarm) int64 {
if param.Timestamp == 0 {
param.Timestamp = time.Now().UnixMilli()
}
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}
// Update 修改信息 返回受影响的行数
func (r Alarm) Update(param model.Alarm) int64 {
if param.ID <= 0 {
return 0
}
tx := db.DB("").Model(&model.Alarm{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id", "timestamp")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r Alarm) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.Alarm{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// SelectAlarmSeqLast 查询网元告警最后一条序号
func (r Alarm) SelectAlarmSeqLast(neType, neId string) int64 {
tx := db.DB("").Model(&model.Alarm{})
tx = tx.Where("ne_type=? and ne_id=?", neType, neId)
tx = tx.Select("alarm_seq").Order("alarm_seq DESC")
// 查询数据
var alarmSeq int64 = 0
if err := tx.Limit(1).Find(&alarmSeq).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return alarmSeq
}
return alarmSeq
}

View File

@@ -0,0 +1,169 @@
package repository
import (
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 AlarmEvent 结构体
var NewAlarmEvent = &AlarmEvent{}
// AlarmEvent 告警 数据层处理
type AlarmEvent struct{}
// SelectByPage 分页查询集合
func (r AlarmEvent) SelectByPage(query model.AlarmEventQuery) ([]model.AlarmEvent, int64) {
tx := db.DB("").Model(&model.AlarmEvent{})
// 查询条件拼接
if query.NeType != "" {
tx = tx.Where("ne_type = ?", query.NeType)
}
if query.NeID != "" {
tx = tx.Where("ne_id = ?", query.NeID)
}
if query.AlarmCode != "" {
tx = tx.Where("alarm_code = ?", query.AlarmCode)
}
if query.AlarmStatus != "" {
tx = tx.Where("alarm_status = ?", query.AlarmStatus)
}
if query.BeginTime != 0 {
tx = tx.Where("event_time >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("event_time <= ?", query.EndTime)
}
// 查询结果
var total int64 = 0
rows := []model.AlarmEvent{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 排序
if query.SortField != "" {
sortField := query.SortField
if query.SortOrder == "desc" {
sortField = sortField + " desc"
}
tx = tx.Order(sortField)
}
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// Select 查询集合
func (r AlarmEvent) Select(param model.AlarmEvent) []model.AlarmEvent {
tx := db.DB("").Model(&model.AlarmEvent{})
// 查询条件拼接
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if param.NeId != "" {
tx = tx.Where("ne_id = ?", param.NeId)
}
if param.AlarmId != "" {
tx = tx.Where("alarm_id = ?", param.AlarmId)
}
if param.AlarmCode != 0 {
tx = tx.Where("alarm_code = ?", param.AlarmCode)
}
if param.AlarmStatus != "" {
tx = tx.Where("alarm_status = ?", param.AlarmStatus)
}
// 查询数据
rows := []model.AlarmEvent{}
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// SelectByIds 通过ID查询
func (r AlarmEvent) SelectByIds(ids []int64) []model.AlarmEvent {
rows := []model.AlarmEvent{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.AlarmEvent{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息 返回新增数据ID
func (r AlarmEvent) Insert(param model.AlarmEvent) int64 {
if param.Timestamp == 0 {
param.Timestamp = time.Now().UnixMilli()
}
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}
// Update 修改信息 返回受影响的行数
func (r AlarmEvent) Update(param model.AlarmEvent) int64 {
if param.ID <= 0 {
return 0
}
tx := db.DB("").Model(&model.AlarmEvent{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id", "timestamp")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r AlarmEvent) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.AlarmEvent{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// SelectAlarmEventSeqLast 查询网元告警最后一条序号
func (r AlarmEvent) SelectAlarmEventSeqLast(neType, neId string) int64 {
tx := db.DB("").Model(&model.AlarmEvent{})
tx = tx.Where("ne_type=? and ne_id=?", neType, neId)
tx = tx.Select("alarm_seq").Order("alarm_seq DESC")
// 查询数据
var AlarmEventSeq int64 = 0
if err := tx.Limit(1).Find(&AlarmEventSeq).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return AlarmEventSeq
}
return AlarmEventSeq
}

View File

@@ -0,0 +1,104 @@
package repository
import (
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 AlarmForwardLog 结构体
var NewAlarmForwardLog = &AlarmForwardLog{}
// AlarmForwardLog 基站状态记录表 数据层处理
type AlarmForwardLog struct{}
// SelectByPage 分页查询集合
func (r AlarmForwardLog) SelectByPage(query model.AlarmForwardLogQuery) ([]model.AlarmForwardLog, int64) {
tx := db.DB("").Model(&model.AlarmForwardLog{})
// 查询条件拼接
if query.NeType != "" {
tx = tx.Where("ne_type = ?", query.NeType)
}
if query.NeID != "" {
tx = tx.Where("ne_id = ?", query.NeID)
}
if query.BeginTime != 0 {
tx = tx.Where("create_time >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("create_time <= ?", query.EndTime)
}
// 查询结果
var total int64 = 0
rows := []model.AlarmForwardLog{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 排序
if query.SortField != "" {
sortField := query.SortField
if query.SortOrder == "desc" {
sortField = sortField + " desc"
}
tx = tx.Order(sortField)
}
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// SelectByIds 通过ID查询
func (r AlarmForwardLog) SelectByIds(ids []int64) []model.AlarmForwardLog {
rows := []model.AlarmForwardLog{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.AlarmForwardLog{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r AlarmForwardLog) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.AlarmForwardLog{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// Insert 新增信息
func (r AlarmForwardLog) Insert(param model.AlarmForwardLog) int64 {
if param.CreatedAt == 0 {
param.CreatedAt = time.Now().UnixMilli()
}
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}

View File

@@ -0,0 +1,104 @@
package repository
import (
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 AlarmLog 结构体
var NewAlarmLog = &AlarmLog{}
// AlarmLog 基站状态记录表 数据层处理
type AlarmLog struct{}
// SelectByPage 分页查询集合
func (r AlarmLog) SelectByPage(query model.AlarmLogQuery) ([]model.AlarmLog, int64) {
tx := db.DB("").Model(&model.AlarmLog{})
// 查询条件拼接
if query.NeType != "" {
tx = tx.Where("ne_type = ?", query.NeType)
}
if query.NeID != "" {
tx = tx.Where("ne_id = ?", query.NeID)
}
if query.BeginTime != 0 {
tx = tx.Where("create_time >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("create_time <= ?", query.EndTime)
}
// 查询结果
var total int64 = 0
rows := []model.AlarmLog{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 排序
if query.SortField != "" {
sortField := query.SortField
if query.SortOrder == "desc" {
sortField = sortField + " desc"
}
tx = tx.Order(sortField)
}
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// SelectByIds 通过ID查询
func (r AlarmLog) SelectByIds(ids []int64) []model.AlarmLog {
rows := []model.AlarmLog{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.AlarmLog{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r AlarmLog) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.AlarmLog{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// Insert 新增信息
func (r AlarmLog) Insert(param model.AlarmLog) int64 {
if param.CreatedAt == 0 {
param.CreatedAt = time.Now().UnixMilli()
}
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}

View File

@@ -1,103 +0,0 @@
package repository
import (
"strings"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 Alarm 结构体
var NewAlarm = &Alarm{}
// Alarm 告警 数据层处理
type Alarm struct{}
// SelectByPage 分页查询集合
func (r Alarm) SelectByPage(querys model.AlarmQuery) ([]model.Alarm, int64) {
tx := datasource.DB("").Model(&model.Alarm{})
// 查询条件拼接
if querys.NeType != "" {
tx = tx.Where("ne_type = ?", querys.NeType)
}
if querys.RmUID != "" {
tx = tx.Where("rm_uid = ?", querys.RmUID)
}
if querys.StartTime != "" {
startTime := querys.StartTime
if len(startTime) == 13 {
startTime = startTime[:10]
}
tx = tx.Where("timestamp >= ?", startTime)
}
if querys.EndTime != "" {
endTime := querys.EndTime
if len(endTime) == 13 {
endTime = endTime[:10]
}
tx = tx.Where("timestamp <= ?", endTime)
}
if querys.OrigSeverity != "" {
eventTypes := strings.Split(querys.OrigSeverity, ",")
tx = tx.Where("orig_severity in (%s)", eventTypes)
}
// 查询结果
var total int64 = 0
rows := []model.Alarm{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
// 排序
if querys.SortField != "" {
sortField := querys.SortField
if querys.SortOrder == "desc" {
sortField = sortField + " desc"
}
tx = tx.Order(sortField)
}
// 查询数据分页
pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return rows, total
}
// SelectByIds 通过ID查询
func (r *Alarm) SelectByIds(ids []string) []model.Alarm {
rows := []model.Alarm{}
if len(ids) <= 0 {
return rows
}
tx := datasource.DB("").Model(&model.Alarm{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *Alarm) DeleteByIds(ids []string) int64 {
if len(ids) <= 0 {
return 0
}
tx := datasource.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.Alarm{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}

View File

@@ -1,131 +0,0 @@
package repository
import (
"fmt"
"strings"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 PerfKPI 结构体
var NewPerfKPI = &PerfKPI{}
// PerfKPI 性能统计 数据层处理
type PerfKPI struct{}
// SelectGoldKPI 通过网元指标数据信息
func (r *PerfKPI) SelectGoldKPI(query model.GoldKPIQuery, kpiIds []string) []map[string]any {
// 查询条件拼接
var conditions []string
var params []any
var tableName string = "kpi_report_"
if query.RmUID != "" {
conditions = append(conditions, "gk.rm_uid = ?")
params = append(params, query.RmUID)
}
if query.NeType != "" {
//conditions = append(conditions, "gk.ne_type = ?")
// params = append(params, query.NeType)
tableName += strings.ToLower(query.NeType)
}
if query.StartTime != "" {
conditions = append(conditions, "gk.created_at >= ?")
params = append(params, query.StartTime)
}
if query.EndTime != "" {
conditions = append(conditions, "gk.created_at <= ?")
params = append(params, query.EndTime)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询字段列
var fields = []string{
// fmt.Sprintf("FROM_UNIXTIME(FLOOR(gk.created_at / (%d * 1000)) * %d) AS timeGroup", query.Interval, query.Interval),
fmt.Sprintf("CONCAT(FLOOR(gk.created_at / (%d * 1000)) * (%d * 1000)) AS timeGroup", query.Interval, query.Interval), // 时间戳毫秒
"min(CASE WHEN gk.index != '' THEN gk.index ELSE 0 END) AS startIndex",
"min(CASE WHEN gk.ne_type != '' THEN gk.ne_type ELSE 0 END) AS neType",
"min(CASE WHEN gk.ne_name != '' THEN gk.ne_name ELSE 0 END) AS neName",
}
for i, kid := range kpiIds {
// 特殊字段只取最后一次收到的非0值
if kid == "AMF.01" || kid == "UDM.01" || kid == "UDM.02" || kid == "UDM.03" || kid == "SMF.01" {
str := fmt.Sprintf("IFNULL(SUBSTRING_INDEX(GROUP_CONCAT( CASE WHEN JSON_EXTRACT(gk.kpi_values, '$[%d].kpi_id') = '%s' THEN JSON_EXTRACT(gk.kpi_values, '$[%d].value') END ), ',', 1), 0) AS '%s'", i, kid, i, kid)
fields = append(fields, str)
} else {
str := fmt.Sprintf("sum(CASE WHEN JSON_EXTRACT(gk.kpi_values, '$[%d].kpi_id') = '%s' THEN JSON_EXTRACT(gk.kpi_values, '$[%d].value') ELSE 0 END) AS '%s'", i, kid, i, kid)
fields = append(fields, str)
}
}
fieldsSql := strings.Join(fields, ",")
// 查询数据
if query.SortField == "" {
query.SortField = "timeGroup"
}
if query.SortOrder == "" {
query.SortOrder = "desc"
}
orderSql := fmt.Sprintf(" order by %s %s", query.SortField, query.SortOrder)
querySql := fmt.Sprintf("SELECT %s FROM %s gk %s GROUP BY timeGroup %s", fieldsSql, tableName, whereSql, orderSql)
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
return results
}
// SelectGoldKPITitle 网元对应的指标名称
func (r *PerfKPI) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
result := []model.GoldKPITitle{}
tx := datasource.DefaultDB().Table("kpi_title").Where("ne_type = ?", neType).Find(&result)
if err := tx.Error; err != nil {
logger.Errorf("Find err => %v", err)
}
return result
}
// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
func (r *PerfKPI) SelectUPFTotalFlow(neType, rmUID, startDate, endDate string) map[string]any {
// 查询条件拼接
var conditions []string
var params []any
if neType != "" {
conditions = append(conditions, "kupf.ne_type = ?")
params = append(params, neType)
}
if rmUID != "" {
conditions = append(conditions, "kupf.rm_uid = ?")
params = append(params, rmUID)
}
if startDate != "" {
conditions = append(conditions, "kupf.created_at >= ?")
params = append(params, startDate)
}
if endDate != "" {
conditions = append(conditions, "kupf.created_at <= ?")
params = append(params, endDate)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := `SELECT
sum( CASE WHEN JSON_EXTRACT(kupf.kpi_values, '$[2].kpi_id') = 'UPF.03' THEN JSON_EXTRACT(kupf.kpi_values, '$[2].value') ELSE 0 END ) AS 'up',
sum( CASE WHEN JSON_EXTRACT(kupf.kpi_values, '$[5].kpi_id') = 'UPF.06' THEN JSON_EXTRACT(kupf.kpi_values, '$[5].value') ELSE 0 END ) AS 'down'
FROM kpi_report_upf kupf`
results, err := datasource.RawDB("", querySql+whereSql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
return results[0]
}

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -16,43 +16,35 @@ var NewCDREventIMS = &CDREventIMS{}
type CDREventIMS struct{} type CDREventIMS struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r CDREventIMS) SelectByPage(querys model.CDREventIMSQuery) ([]model.CDREventIMS, int64) { func (r CDREventIMS) SelectByPage(query model.CDREventIMSQuery) ([]model.CDREventIMS, int64) {
tx := datasource.DB("").Model(&model.CDREventIMS{}) tx := db.DB("").Model(&model.CDREventIMS{})
// 查询条件拼接 // 查询条件拼接
if querys.NeType != "" { if query.NeType != "" {
tx = tx.Where("ne_type = ?", querys.NeType) tx = tx.Where("ne_type = ?", query.NeType)
} }
if querys.RmUID != "" { if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", querys.RmUID) tx = tx.Where("rm_uid = ?", query.RmUID)
} }
if querys.StartTime != "" { if query.BeginTime != 0 {
startTime := querys.StartTime tx = tx.Where("timestamp >= ?", query.BeginTime)
if len(startTime) == 13 {
startTime = startTime[:10]
}
tx = tx.Where("timestamp >= ?", startTime)
} }
if querys.EndTime != "" { if query.EndTime != 0 {
endTime := querys.EndTime tx = tx.Where("timestamp <= ?", query.EndTime)
if len(endTime) == 13 {
endTime = endTime[:10]
}
tx = tx.Where("timestamp <= ?", endTime)
} }
if querys.CallerParty != "" { if query.CallerParty != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.callerParty') = ?", querys.CallerParty) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.callerParty') = ?", query.CallerParty)
} }
if querys.CalledParty != "" { if query.CalledParty != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.calledParty') = ?", querys.CalledParty) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.calledParty') = ?", query.CalledParty)
} }
if querys.RecordType != "" { if query.RecordType != "" {
recordTypes := strings.Split(querys.RecordType, ",") recordTypes := strings.Split(query.RecordType, ",")
var queryStrArr []string var querytrArr []string
for _, recordType := range recordTypes { for _, recordType := range recordTypes {
queryStrArr = append(queryStrArr, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType)) querytrArr = append(querytrArr, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType))
} }
tx = tx.Where(fmt.Sprintf("( %s )", strings.Join(queryStrArr, " OR "))) tx = tx.Where(fmt.Sprintf("( %s )", strings.Join(querytrArr, " OR ")))
} }
// 查询结果 // 查询结果
@@ -65,16 +57,16 @@ func (r CDREventIMS) SelectByPage(querys model.CDREventIMSQuery) ([]model.CDREve
} }
// 排序 // 排序
if querys.SortField != "" { if query.SortField != "" {
sortField := querys.SortField sortField := query.SortField
if querys.SortOrder == "desc" { if query.SortOrder == "desc" {
sortField = sortField + " desc" sortField = sortField + " desc"
} }
tx = tx.Order(sortField) tx = tx.Order(sortField)
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize) pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -85,12 +77,12 @@ func (r CDREventIMS) SelectByPage(querys model.CDREventIMSQuery) ([]model.CDREve
} }
// SelectByIds 通过ID查询 // SelectByIds 通过ID查询
func (r *CDREventIMS) SelectByIds(ids []string) []model.CDREventIMS { func (r *CDREventIMS) SelectByIds(ids []int64) []model.CDREventIMS {
rows := []model.CDREventIMS{} rows := []model.CDREventIMS{}
if len(ids) <= 0 { if len(ids) <= 0 {
return rows return rows
} }
tx := datasource.DB("").Model(&model.CDREventIMS{}) tx := db.DB("").Model(&model.CDREventIMS{})
// 构建查询条件 // 构建查询条件
tx = tx.Where("id in ?", ids) tx = tx.Where("id in ?", ids)
// 查询数据 // 查询数据
@@ -102,11 +94,11 @@ func (r *CDREventIMS) SelectByIds(ids []string) []model.CDREventIMS {
} }
// DeleteByIds 批量删除信息 // DeleteByIds 批量删除信息
func (r *CDREventIMS) DeleteByIds(ids []string) int64 { func (r *CDREventIMS) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 { if len(ids) <= 0 {
return 0 return 0
} }
tx := datasource.DB("").Where("id in ?", ids) tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.CDREventIMS{}).Error; err != nil { if err := tx.Delete(&model.CDREventIMS{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error()) logger.Errorf("delete err => %v", err.Error())
return 0 return 0

View File

@@ -1,7 +1,7 @@
package repository package repository
import ( import (
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -13,34 +13,26 @@ var NewCDREventSGWC = &CDREventSGWC{}
type CDREventSGWC struct{} type CDREventSGWC struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r CDREventSGWC) SelectByPage(querys model.CDREventSGWCQuery) ([]model.CDREventSGWC, int64) { func (r CDREventSGWC) SelectByPage(query model.CDREventSGWCQuery) ([]model.CDREventSGWC, int64) {
tx := datasource.DB("").Model(&model.CDREventSGWC{}) tx := db.DB("").Model(&model.CDREventSGWC{})
// 查询条件拼接 // 查询条件拼接
if querys.NeType != "" { if query.NeType != "" {
tx = tx.Where("ne_type = ?", querys.NeType) tx = tx.Where("ne_type = ?", query.NeType)
} }
if querys.RmUID != "" { if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", querys.RmUID) tx = tx.Where("rm_uid = ?", query.RmUID)
} }
if querys.StartTime != "" { if query.BeginTime != 0 {
startTime := querys.StartTime tx = tx.Where("timestamp >= ?", query.BeginTime)
if len(startTime) == 13 {
startTime = startTime[:10]
}
tx = tx.Where("timestamp >= ?", startTime)
} }
if querys.EndTime != "" { if query.EndTime != 0 {
endTime := querys.EndTime tx = tx.Where("timestamp <= ?", query.EndTime)
if len(endTime) == 13 {
endTime = endTime[:10]
}
tx = tx.Where("timestamp <= ?", endTime)
} }
if querys.IMSI != "" { if query.IMSI != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.servedIMSI') = ?", querys.IMSI) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.servedIMSI') = ?", query.IMSI)
} }
if querys.MSISDN != "" { if query.MSISDN != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.servedMSISDN') = ?", querys.MSISDN) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.servedMSISDN') = ?", query.MSISDN)
} }
// 查询结果 // 查询结果
@@ -53,16 +45,16 @@ func (r CDREventSGWC) SelectByPage(querys model.CDREventSGWCQuery) ([]model.CDRE
} }
// 排序 // 排序
if querys.SortField != "" { if query.SortField != "" {
sortField := querys.SortField sortField := query.SortField
if querys.SortOrder == "desc" { if query.SortOrder == "desc" {
sortField = sortField + " desc" sortField = sortField + " desc"
} }
tx = tx.Order(sortField) tx = tx.Order(sortField)
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize) pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -73,12 +65,12 @@ func (r CDREventSGWC) SelectByPage(querys model.CDREventSGWCQuery) ([]model.CDRE
} }
// SelectByIds 通过ID查询 // SelectByIds 通过ID查询
func (r *CDREventSGWC) SelectByIds(ids []string) []model.CDREventSGWC { func (r *CDREventSGWC) SelectByIds(ids []int64) []model.CDREventSGWC {
rows := []model.CDREventSGWC{} rows := []model.CDREventSGWC{}
if len(ids) <= 0 { if len(ids) <= 0 {
return rows return rows
} }
tx := datasource.DB("").Model(&model.CDREventSGWC{}) tx := db.DB("").Model(&model.CDREventSGWC{})
// 构建查询条件 // 构建查询条件
tx = tx.Where("id in ?", ids) tx = tx.Where("id in ?", ids)
// 查询数据 // 查询数据
@@ -90,11 +82,11 @@ func (r *CDREventSGWC) SelectByIds(ids []string) []model.CDREventSGWC {
} }
// DeleteByIds 批量删除信息 // DeleteByIds 批量删除信息
func (r *CDREventSGWC) DeleteByIds(ids []string) int64 { func (r *CDREventSGWC) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 { if len(ids) <= 0 {
return 0 return 0
} }
tx := datasource.DB("").Where("id in ?", ids) tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.CDREventSGWC{}).Error; err != nil { if err := tx.Delete(&model.CDREventSGWC{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error()) logger.Errorf("delete err => %v", err.Error())
return 0 return 0

View File

@@ -1,7 +1,7 @@
package repository package repository
import ( import (
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -13,37 +13,29 @@ var NewCDREventSMF = &CDREventSMF{}
type CDREventSMF struct{} type CDREventSMF struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r CDREventSMF) SelectByPage(querys model.CDREventSMFQuery) ([]model.CDREventSMF, int64) { func (r CDREventSMF) SelectByPage(query model.CDREventSMFQuery) ([]model.CDREventSMF, int64) {
tx := datasource.DB("").Model(&model.CDREventSMF{}) tx := db.DB("").Model(&model.CDREventSMF{})
// 查询条件拼接 // 查询条件拼接
if querys.NeType != "" { if query.NeType != "" {
tx = tx.Where("ne_type = ?", querys.NeType) tx = tx.Where("ne_type = ?", query.NeType)
} }
if querys.RmUID != "" { if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", querys.RmUID) tx = tx.Where("rm_uid = ?", query.RmUID)
} }
if querys.StartTime != "" { if query.BeginTime != 0 {
startTime := querys.StartTime tx = tx.Where("timestamp >= ?", query.BeginTime)
if len(startTime) == 13 {
startTime = startTime[:10]
}
tx = tx.Where("timestamp >= ?", startTime)
} }
if querys.EndTime != "" { if query.EndTime != 0 {
endTime := querys.EndTime tx = tx.Where("timestamp <= ?", query.EndTime)
if len(endTime) == 13 {
endTime = endTime[:10]
}
tx = tx.Where("timestamp <= ?", endTime)
} }
if querys.RecordType != "" { if query.RecordType != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.recordType') = ?", querys.RecordType) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.recordType') = ?", query.RecordType)
} }
if querys.SubscriberID != "" { if query.SubscriberID != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?", querys.SubscriberID) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?", query.SubscriberID)
} }
if querys.DNN != "" { if query.DNN != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.pDUSessionChargingInformation.dNNID') = ?", querys.DNN) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.pDUSessionChargingInformation.dNNID') = ?", query.DNN)
} }
// 查询结果 // 查询结果
@@ -56,16 +48,16 @@ func (r CDREventSMF) SelectByPage(querys model.CDREventSMFQuery) ([]model.CDREve
} }
// 排序 // 排序
if querys.SortField != "" { if query.SortField != "" {
sortField := querys.SortField sortField := query.SortField
if querys.SortOrder == "desc" { if query.SortOrder == "desc" {
sortField = sortField + " desc" sortField = sortField + " desc"
} }
tx = tx.Order(sortField) tx = tx.Order(sortField)
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize) pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -76,12 +68,12 @@ func (r CDREventSMF) SelectByPage(querys model.CDREventSMFQuery) ([]model.CDREve
} }
// SelectByIds 通过ID查询 // SelectByIds 通过ID查询
func (r *CDREventSMF) SelectByIds(ids []string) []model.CDREventSMF { func (r *CDREventSMF) SelectByIds(ids []int64) []model.CDREventSMF {
rows := []model.CDREventSMF{} rows := []model.CDREventSMF{}
if len(ids) <= 0 { if len(ids) <= 0 {
return rows return rows
} }
tx := datasource.DB("").Model(&model.CDREventSMF{}) tx := db.DB("").Model(&model.CDREventSMF{})
// 构建查询条件 // 构建查询条件
tx = tx.Where("id in ?", ids) tx = tx.Where("id in ?", ids)
// 查询数据 // 查询数据
@@ -93,11 +85,11 @@ func (r *CDREventSMF) SelectByIds(ids []string) []model.CDREventSMF {
} }
// DeleteByIds 批量删除信息 // DeleteByIds 批量删除信息
func (r *CDREventSMF) DeleteByIds(ids []string) int64 { func (r *CDREventSMF) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 { if len(ids) <= 0 {
return 0 return 0
} }
tx := datasource.DB("").Where("id in ?", ids) tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.CDREventSMF{}).Error; err != nil { if err := tx.Delete(&model.CDREventSMF{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error()) logger.Errorf("delete err => %v", err.Error())
return 0 return 0

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -16,43 +16,35 @@ var NewCDREventSMSC = &CDREventSMSC{}
type CDREventSMSC struct{} type CDREventSMSC struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r CDREventSMSC) SelectByPage(querys model.CDREventSMSCQuery) ([]model.CDREventSMSC, int64) { func (r CDREventSMSC) SelectByPage(query model.CDREventSMSCQuery) ([]model.CDREventSMSC, int64) {
tx := datasource.DB("").Model(&model.CDREventSMSC{}) tx := db.DB("").Model(&model.CDREventSMSC{})
// 查询条件拼接 // 查询条件拼接
if querys.NeType != "" { if query.NeType != "" {
tx = tx.Where("ne_type = ?", querys.NeType) tx = tx.Where("ne_type = ?", query.NeType)
} }
if querys.RmUID != "" { if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", querys.RmUID) tx = tx.Where("rm_uid = ?", query.RmUID)
} }
if querys.StartTime != "" { if query.BeginTime != 0 {
startTime := querys.StartTime tx = tx.Where("timestamp >= ?", query.BeginTime)
if len(startTime) == 13 {
startTime = startTime[:10]
}
tx = tx.Where("timestamp >= ?", startTime)
} }
if querys.EndTime != "" { if query.EndTime != 0 {
endTime := querys.EndTime tx = tx.Where("timestamp <= ?", query.EndTime)
if len(endTime) == 13 {
endTime = endTime[:10]
}
tx = tx.Where("timestamp <= ?", endTime)
} }
if querys.CallerParty != "" { if query.CallerParty != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.callerParty') = ?", querys.CallerParty) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.callerParty') = ?", query.CallerParty)
} }
if querys.CalledParty != "" { if query.CalledParty != "" {
tx = tx.Where("JSON_EXTRACT(cdr_json, '$.calledParty') = ?", querys.CalledParty) tx = tx.Where("JSON_EXTRACT(cdr_json, '$.calledParty') = ?", query.CalledParty)
} }
if querys.RecordType != "" { if query.RecordType != "" {
recordTypes := strings.Split(querys.RecordType, ",") recordTypes := strings.Split(query.RecordType, ",")
var queryStrArr []string var querytrArr []string
for _, recordType := range recordTypes { for _, recordType := range recordTypes {
queryStrArr = append(queryStrArr, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType)) querytrArr = append(querytrArr, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType))
} }
tx = tx.Where(fmt.Sprintf("( %s )", strings.Join(queryStrArr, " OR "))) tx = tx.Where(fmt.Sprintf("( %s )", strings.Join(querytrArr, " OR ")))
} }
// 查询结果 // 查询结果
@@ -65,16 +57,16 @@ func (r CDREventSMSC) SelectByPage(querys model.CDREventSMSCQuery) ([]model.CDRE
} }
// 排序 // 排序
if querys.SortField != "" { if query.SortField != "" {
sortField := querys.SortField sortField := query.SortField
if querys.SortOrder == "desc" { if query.SortOrder == "desc" {
sortField = sortField + " desc" sortField = sortField + " desc"
} }
tx = tx.Order(sortField) tx = tx.Order(sortField)
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize) pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -85,12 +77,12 @@ func (r CDREventSMSC) SelectByPage(querys model.CDREventSMSCQuery) ([]model.CDRE
} }
// SelectByIds 通过ID查询 // SelectByIds 通过ID查询
func (r *CDREventSMSC) SelectByIds(ids []string) []model.CDREventSMSC { func (r *CDREventSMSC) SelectByIds(ids []int64) []model.CDREventSMSC {
rows := []model.CDREventSMSC{} rows := []model.CDREventSMSC{}
if len(ids) <= 0 { if len(ids) <= 0 {
return rows return rows
} }
tx := datasource.DB("").Model(&model.CDREventSMSC{}) tx := db.DB("").Model(&model.CDREventSMSC{})
// 构建查询条件 // 构建查询条件
tx = tx.Where("id in ?", ids) tx = tx.Where("id in ?", ids)
// 查询数据 // 查询数据
@@ -102,11 +94,11 @@ func (r *CDREventSMSC) SelectByIds(ids []string) []model.CDREventSMSC {
} }
// DeleteByIds 批量删除信息 // DeleteByIds 批量删除信息
func (r *CDREventSMSC) DeleteByIds(ids []string) int64 { func (r *CDREventSMSC) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 { if len(ids) <= 0 {
return 0 return 0
} }
tx := datasource.DB("").Where("id in ?", ids) tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.CDREventSMSC{}).Error; err != nil { if err := tx.Delete(&model.CDREventSMSC{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error()) logger.Errorf("delete err => %v", err.Error())
return 0 return 0

View File

@@ -0,0 +1,89 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 KpiCReport 结构体
var NewKpiCReport = &KpiCReport{}
// KpiCReport 性能统计 数据层处理
type KpiCReport struct{}
// SelectGoldKPI 通过网元指标数据信息
func (r KpiCReport) SelectKPI(query model.KPIQuery) []model.KpiCReport {
rows := []model.KpiCReport{}
if query.NeType == "" {
return rows
}
tx := db.DB("").Model(&model.KpiCReport{})
// 表名
tableName := fmt.Sprintf("kpi_c_report_%s", strings.ToLower(query.NeType))
tx.Table(tableName)
// 构建查询条件
if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", query.RmUID)
}
if query.BeginTime != 0 {
tx = tx.Where("created_at >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("created_at <= ?", query.EndTime)
}
// 排序
if query.SortField == "" || query.SortField == "timeGroup" {
query.SortField = "created_at"
}
if query.SortOrder == "" {
query.SortOrder = "desc"
}
tx = tx.Order(fmt.Sprintf("%s %s", query.SortField, query.SortOrder))
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息 返回新增数据ID
func (r KpiCReport) Insert(param model.KpiCReport) int64 {
if param.NeType == "" {
return 0
}
if param.CreatedAt == 0 {
param.CreatedAt = time.Now().UnixMilli()
}
// 表名
tableName := fmt.Sprintf("kpi_c_report_%s", strings.ToLower(param.NeType))
// 执行插入
if err := db.DB("").Table(tableName).Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}
// SelectKPITitle 网元对应的指标名称
func (r KpiCReport) SelectKPITitle(neType string) []model.KpiCTitle {
rows := []model.KpiCTitle{}
if neType == "" {
return rows
}
tx := db.DB("").Model(&model.KpiCTitle{})
// 构建查询条件
tx = tx.Where("ne_type =?", neType)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}

View File

@@ -0,0 +1,106 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model"
)
// 实例化数据层 KpiReport 结构体
var NewKpiReport = &KpiReport{}
// KpiReport 性能统计 数据层处理
type KpiReport struct{}
// SelectGoldKPI 通过网元指标数据信息
func (r KpiReport) SelectKPI(query model.KPIQuery) []model.KpiReport {
rows := []model.KpiReport{}
if query.NeType == "" {
return rows
}
tx := db.DB("").Model(&model.KpiReport{})
// 表名
tableName := fmt.Sprintf("kpi_report_%s", strings.ToLower(query.NeType))
tx = tx.Table(tableName)
// 构建查询条件
if query.RmUID != "" {
tx = tx.Where("rm_uid = ?", query.RmUID)
}
if query.BeginTime != 0 {
tx = tx.Where("created_at >= ?", query.BeginTime)
}
if query.EndTime != 0 {
tx = tx.Where("created_at <= ?", query.EndTime)
}
// 排序
if query.SortField == "" || query.SortField == "timeGroup" {
query.SortField = "created_at"
}
if query.SortOrder == "" {
query.SortOrder = "desc"
}
tx = tx.Order(fmt.Sprintf("%s %s", query.SortField, query.SortOrder))
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息 返回新增数据ID
func (r KpiReport) Insert(param model.KpiReport) int64 {
if param.NeType == "" {
return 0
}
if param.CreatedAt == 0 {
param.CreatedAt = time.Now().UnixMilli()
}
// 表名
tableName := fmt.Sprintf("kpi_report_%s", strings.ToLower(param.NeType))
// 执行插入
if err := db.DB("").Table(tableName).Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return param.ID
}
// SelectKPITitle 网元对应的指标名称
func (r KpiReport) SelectKPITitle(neType string) []model.KpiTitle {
rows := []model.KpiTitle{}
if neType == "" {
return rows
}
tx := db.DB("").Model(&model.KpiTitle{})
// 构建查询条件
tx = tx.Where("ne_type =?", neType)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// SelectUPF 查询UPF数据 N3上行,N6下行
func (r KpiReport) SelectUPF(rmUID string, beginTime, endTime int64) []model.KpiReport {
tx := db.DB("").Model(&model.KpiReport{})
// 表名
tx = tx.Table("kpi_report_upf")
tx = tx.Where("rm_uid = ?", rmUID)
tx = tx.Where("created_at >= ?", beginTime)
tx = tx.Where("created_at <= ?", endTime)
// 查询数据
rows := []model.KpiReport{}
if err := tx.Select("kpi_values").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}

View File

@@ -3,7 +3,7 @@ package repository
import ( import (
"time" "time"
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -16,7 +16,7 @@ type NBState struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r NBState) SelectByPage(query model.NBStateQuery) ([]model.NBState, int64) { func (r NBState) SelectByPage(query model.NBStateQuery) ([]model.NBState, int64) {
tx := datasource.DB("").Model(&model.NBState{}) tx := db.DB("").Model(&model.NBState{})
// 查询条件拼接 // 查询条件拼接
if query.NeType != "" { if query.NeType != "" {
tx = tx.Where("ne_type = ?", query.NeType) tx = tx.Where("ne_type = ?", query.NeType)
@@ -64,7 +64,7 @@ func (r NBState) SelectByPage(query model.NBStateQuery) ([]model.NBState, int64)
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(query.PageNum, query.PageSize) pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -80,7 +80,7 @@ func (r NBState) SelectByIds(ids []string) []model.NBState {
if len(ids) <= 0 { if len(ids) <= 0 {
return rows return rows
} }
tx := datasource.DB("").Model(&model.NBState{}) tx := db.DB("").Model(&model.NBState{})
// 构建查询条件 // 构建查询条件
tx = tx.Where("id in ?", ids) tx = tx.Where("id in ?", ids)
// 查询数据 // 查询数据
@@ -96,7 +96,7 @@ func (r NBState) DeleteByIds(ids []string) int64 {
if len(ids) <= 0 { if len(ids) <= 0 {
return 0 return 0
} }
tx := datasource.DB("").Where("id in ?", ids) tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NBState{}).Error; err != nil { if err := tx.Delete(&model.NBState{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error()) logger.Errorf("delete err => %v", err.Error())
return 0 return 0
@@ -108,7 +108,7 @@ func (r NBState) DeleteByIds(ids []string) int64 {
func (r NBState) Insert(param model.NBState) int64 { func (r NBState) Insert(param model.NBState) int64 {
param.CreateTime = time.Now().UnixMilli() param.CreateTime = time.Now().UnixMilli()
// 执行插入 // 执行插入
if err := datasource.DB("").Create(&param).Error; err != nil { if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error()) logger.Errorf("insert err => %v", err.Error())
return 0 return 0
} }

View File

@@ -1,9 +1,8 @@
package repository package repository
import ( import (
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
@@ -17,7 +16,7 @@ type UDMAuthUser struct{}
func (r *UDMAuthUser) ClearAndInsert(neId string, uArr []model.UDMAuthUser) int64 { func (r *UDMAuthUser) ClearAndInsert(neId string, uArr []model.UDMAuthUser) int64 {
// 不指定neID时用 TRUNCATE 清空表快 // 不指定neID时用 TRUNCATE 清空表快
// _, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil) // _, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil)
result := datasource.DB("").Where("ne_id = ?", neId).Unscoped().Delete(&model.UDMAuthUser{}) result := db.DB("").Where("ne_id = ?", neId).Unscoped().Delete(&model.UDMAuthUser{})
if result.Error != nil { if result.Error != nil {
logger.Errorf("Delete err => %v", result.Error) logger.Errorf("Delete err => %v", result.Error)
} }
@@ -25,8 +24,8 @@ func (r *UDMAuthUser) ClearAndInsert(neId string, uArr []model.UDMAuthUser) int6
} }
// SelectPage 根据条件分页查询 // SelectPage 根据条件分页查询
func (r *UDMAuthUser) SelectPage(query map[string]any) (int64, []model.UDMAuthUser) { func (r *UDMAuthUser) SelectPage(query map[string]string) (int64, []model.UDMAuthUser) {
tx := datasource.DB("").Model(&model.UDMAuthUser{}) tx := db.DB("").Model(&model.UDMAuthUser{})
// 查询条件拼接 // 查询条件拼接
if v, ok := query["imsi"]; ok && v != "" { if v, ok := query["imsi"]; ok && v != "" {
tx = tx.Where("imsi like concat(concat('%',?), '%')", v) tx = tx.Where("imsi like concat(concat('%',?), '%')", v)
@@ -48,13 +47,13 @@ func (r *UDMAuthUser) SelectPage(query map[string]any) (int64, []model.UDMAuthUs
} }
// 分页 // 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"]) pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Offset(int(pageNum * pageSize)).Limit(int(pageSize)) tx = tx.Offset(int(pageNum * pageSize)).Limit(int(pageSize))
// 排序 // 排序
if v, ok := query["sortField"]; ok && v != "" { if v, ok := query["sortField"]; ok && v != "" {
sortSql := v.(string) sortSql := v
if o, ok := query["sortOrder"]; ok && o != nil && v != "" { if o, ok := query["sortOrder"]; ok && o != "" {
if o == "desc" { if o == "desc" {
sortSql += " desc " sortSql += " desc "
} else { } else {
@@ -74,7 +73,7 @@ func (r *UDMAuthUser) SelectPage(query map[string]any) (int64, []model.UDMAuthUs
// SelectList 根据实体查询 // SelectList 根据实体查询
func (r *UDMAuthUser) SelectList(u model.UDMAuthUser) []model.UDMAuthUser { func (r *UDMAuthUser) SelectList(u model.UDMAuthUser) []model.UDMAuthUser {
tx := datasource.DB("").Model(&model.UDMAuthUser{}) tx := db.DB("").Model(&model.UDMAuthUser{})
// 查询条件拼接 // 查询条件拼接
if u.IMSI != "" { if u.IMSI != "" {
tx = tx.Where("imsi = ?", u.IMSI) tx = tx.Where("imsi = ?", u.IMSI)
@@ -93,7 +92,7 @@ func (r *UDMAuthUser) SelectList(u model.UDMAuthUser) []model.UDMAuthUser {
// SelectByIMSIAndNeID 通过imsi和ne_id查询 // SelectByIMSIAndNeID 通过imsi和ne_id查询
func (r *UDMAuthUser) SelectByIMSIAndNeID(imsi, neId string) model.UDMAuthUser { func (r *UDMAuthUser) SelectByIMSIAndNeID(imsi, neId string) model.UDMAuthUser {
tx := datasource.DB("").Model(&model.UDMAuthUser{}) tx := db.DB("").Model(&model.UDMAuthUser{})
item := model.UDMAuthUser{} item := model.UDMAuthUser{}
// 查询条件拼接 // 查询条件拼接
tx = tx.Where("imsi = ? and ne_id = ?", imsi, neId) tx = tx.Where("imsi = ? and ne_id = ?", imsi, neId)
@@ -106,7 +105,7 @@ func (r *UDMAuthUser) SelectByIMSIAndNeID(imsi, neId string) model.UDMAuthUser {
// Insert 批量添加 // Insert 批量添加
func (r *UDMAuthUser) Inserts(uArr []model.UDMAuthUser) int64 { func (r *UDMAuthUser) Inserts(uArr []model.UDMAuthUser) int64 {
tx := datasource.DB("").CreateInBatches(uArr, 3000) tx := db.DB("").CreateInBatches(uArr, 3000)
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err) logger.Errorf("CreateInBatches err => %v", err)
} }
@@ -115,7 +114,7 @@ func (r *UDMAuthUser) Inserts(uArr []model.UDMAuthUser) int64 {
// Delete 删除实体 // Delete 删除实体
func (r *UDMAuthUser) Delete(imsi, neId string) int64 { func (r *UDMAuthUser) Delete(imsi, neId string) int64 {
tx := datasource.DefaultDB().Where("imsi = ? and ne_id = ?", imsi, neId).Delete(&model.UDMAuthUser{}) tx := db.DB("").Where("imsi = ? and ne_id = ?", imsi, neId).Delete(&model.UDMAuthUser{})
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("Delete err => %v", err) logger.Errorf("Delete err => %v", err)
} }
@@ -124,7 +123,7 @@ func (r *UDMAuthUser) Delete(imsi, neId string) int64 {
// DeletePrefixByIMSI 删除前缀匹配的实体 // DeletePrefixByIMSI 删除前缀匹配的实体
func (r *UDMAuthUser) DeletePrefixByIMSI(neId, imsi string) int64 { func (r *UDMAuthUser) DeletePrefixByIMSI(neId, imsi string) int64 {
tx := datasource.DefaultDB().Where("imsi like concat(?, '%') and ne_id = ?", imsi, neId).Delete(&model.UDMAuthUser{}) tx := db.DB("").Where("imsi like concat(?, '%') and ne_id = ?", imsi, neId).Delete(&model.UDMAuthUser{})
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("DeletePrefixByIMSI err => %v", err) logger.Errorf("DeletePrefixByIMSI err => %v", err)
} }

View File

@@ -1,20 +1,20 @@
package repository package repository
import ( import (
"be.ems/src/framework/datasource" "be.ems/src/framework/database/db"
"be.ems/src/framework/logger" "be.ems/src/framework/logger"
"be.ems/src/modules/network_data/model" "be.ems/src/modules/network_data/model"
) )
// 实例化数据层 UDMUserInfo 结构体 // 实例化数据层 UDMExtend 结构体
var NewUDMUserInfo = &UDMUserInfo{} var NewUDMExtend = &UDMExtend{}
// UDMUserInfo UDM鉴权信息表 数据层处理 // UDMExtend UDM鉴权信息表 数据层处理
type UDMUserInfo struct{} type UDMExtend struct{}
// SelectByPage 分页查询集合 // SelectByPage 分页查询集合
func (r UDMUserInfo) SelectByPage(query map[string]string) ([]model.UDMUserInfo, int64) { func (r UDMExtend) SelectByPage(query map[string]string) ([]model.UDMExtend, int64) {
tx := datasource.DB("").Model(&model.UDMUserInfo{}) tx := db.DB("").Model(&model.UDMExtend{})
// 查询条件拼接 // 查询条件拼接
if v, ok := query["imsi"]; ok && v != "" { if v, ok := query["imsi"]; ok && v != "" {
tx = tx.Where("imsi like concat(concat('%', ?), '%')", v) tx = tx.Where("imsi like concat(concat('%', ?), '%')", v)
@@ -25,7 +25,7 @@ func (r UDMUserInfo) SelectByPage(query map[string]string) ([]model.UDMUserInfo,
// 查询结果 // 查询结果
var total int64 = 0 var total int64 = 0
rows := []model.UDMUserInfo{} rows := []model.UDMExtend{}
// 查询数量为0直接返回 // 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 { if err := tx.Count(&total).Error; err != nil || total <= 0 {
@@ -42,7 +42,7 @@ func (r UDMUserInfo) SelectByPage(query map[string]string) ([]model.UDMUserInfo,
} }
// 查询数据分页 // 查询数据分页
pageNum, pageSize := datasource.PageNumSize(query["pageNum"], query["pageSize"]) pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum) tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error err := tx.Find(&rows).Error
if err != nil { if err != nil {
@@ -53,8 +53,8 @@ func (r UDMUserInfo) SelectByPage(query map[string]string) ([]model.UDMUserInfo,
} }
// SelectList 根据实体查询 // SelectList 根据实体查询
func (r *UDMUserInfo) SelectList(u model.UDMUserInfo) []model.UDMUserInfo { func (r *UDMExtend) SelectList(u model.UDMExtend) []model.UDMExtend {
tx := datasource.DB("").Model(&model.UDMUserInfo{}) tx := db.DB("").Model(&model.UDMExtend{})
// 构建查询条件 // 构建查询条件
if u.IMSI != "" { if u.IMSI != "" {
tx = tx.Where("imsi = ?", u.IMSI) tx = tx.Where("imsi = ?", u.IMSI)
@@ -64,7 +64,7 @@ func (r *UDMUserInfo) SelectList(u model.UDMUserInfo) []model.UDMUserInfo {
} }
tx = tx.Order("imsi asc") tx = tx.Order("imsi asc")
// 查询数据 // 查询数据
rows := []model.UDMUserInfo{} rows := []model.UDMExtend{}
if err := tx.Find(&rows).Error; err != nil { if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error()) logger.Errorf("query find err => %v", err.Error())
return rows return rows
@@ -73,8 +73,8 @@ func (r *UDMUserInfo) SelectList(u model.UDMUserInfo) []model.UDMUserInfo {
} }
// SelectByIMSIAndNeID 通过imsi和ne_id查询 neId为%时模糊imsi查询 // SelectByIMSIAndNeID 通过imsi和ne_id查询 neId为%时模糊imsi查询
func (r *UDMUserInfo) SelectByIMSIAndNeID(imsi, neId string) model.UDMUserInfo { func (r *UDMExtend) SelectByIMSIAndNeID(imsi, neId string) model.UDMExtend {
tx := datasource.DB("").Model(&model.UDMUserInfo{}) tx := db.DB("").Model(&model.UDMExtend{})
// 构建查询条件 // 构建查询条件
if neId == "%" { if neId == "%" {
tx = tx.Where("imsi like concat(?, '%')", imsi) tx = tx.Where("imsi like concat(?, '%')", imsi)
@@ -82,19 +82,19 @@ func (r *UDMUserInfo) SelectByIMSIAndNeID(imsi, neId string) model.UDMUserInfo {
tx = tx.Where(" imsi = ? and ne_id = ?", imsi, neId) tx = tx.Where(" imsi = ? and ne_id = ?", imsi, neId)
} }
// 查询数据 // 查询数据
rows := []model.UDMUserInfo{} rows := []model.UDMExtend{}
if err := tx.Limit(1).Find(&rows).Error; err != nil { if err := tx.Limit(1).Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error()) logger.Errorf("query find err => %v", err.Error())
} }
if len(rows) > 0 { if len(rows) > 0 {
return rows[0] return rows[0]
} }
return model.UDMUserInfo{} return model.UDMExtend{}
} }
// Insert 批量添加 // Insert 批量添加
func (r *UDMUserInfo) Inserts(uArr []model.UDMUserInfo) int64 { func (r *UDMExtend) Inserts(uArr []model.UDMExtend) int64 {
tx := datasource.DefaultDB().CreateInBatches(uArr, 3000) tx := db.DB("").CreateInBatches(uArr, 3000)
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err) logger.Errorf("CreateInBatches err => %v", err)
} }
@@ -102,14 +102,14 @@ func (r *UDMUserInfo) Inserts(uArr []model.UDMUserInfo) int64 {
} }
// Delete 删除实体 neId为%时模糊imsi前缀 // Delete 删除实体 neId为%时模糊imsi前缀
func (r *UDMUserInfo) Delete(imsi, neId string) int64 { func (r *UDMExtend) Delete(imsi, neId string) int64 {
tx := datasource.DefaultDB() tx := db.DB("")
if neId == "%" { if neId == "%" {
tx = tx.Where("imsi like concat(?, '%')", imsi) tx = tx.Where("imsi like concat(?, '%')", imsi)
} else { } else {
tx = tx.Where(" imsi = ? and ne_id = ?", imsi, neId) tx = tx.Where(" imsi = ? and ne_id = ?", imsi, neId)
} }
tx = tx.Delete(&model.UDMUserInfo{}) tx = tx.Delete(&model.UDMExtend{})
if err := tx.Error; err != nil { if err := tx.Error; err != nil {
logger.Errorf("Delete err => %v", err) logger.Errorf("Delete err => %v", err)
} }

Some files were not shown because too many files have changed in this diff Show More