Merge branch 'main' into multi-tenant
This commit is contained in:
@@ -13,10 +13,8 @@ import (
|
||||
func Setup(router *gin.Engine) {
|
||||
logger.Infof("开始加载 ====> chart 模块路由")
|
||||
|
||||
chartGroup := router.Group("/chart")
|
||||
|
||||
// 关系图
|
||||
chartGraphGroup := chartGroup.Group("/graph")
|
||||
// G6关系图
|
||||
chartGraphGroup := router.Group("/chart/graph")
|
||||
{
|
||||
chartGraphGroup.GET("",
|
||||
middleware.PreAuthorize(nil),
|
||||
|
||||
@@ -4,14 +4,14 @@ import (
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/utils/ctx"
|
||||
"be.ems/src/framework/vo/result"
|
||||
chartService "be.ems/src/modules/chart/service"
|
||||
"be.ems/src/modules/chart/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
)
|
||||
|
||||
// 实例化控制层 ChartGraphController 结构体
|
||||
var NewChartGraph = &ChartGraphController{
|
||||
chartGraphService: chartService.NewChartGraphImpl,
|
||||
chartGraphService: service.NewChartGraph,
|
||||
}
|
||||
|
||||
// G6关系图
|
||||
@@ -19,7 +19,7 @@ var NewChartGraph = &ChartGraphController{
|
||||
// PATH /graph
|
||||
type ChartGraphController struct {
|
||||
// G6关系图数据表服务
|
||||
chartGraphService chartService.IChartGraph
|
||||
chartGraphService *service.ChartGraph
|
||||
}
|
||||
|
||||
// 获取关系图组名
|
||||
|
||||
@@ -1,31 +1,32 @@
|
||||
package model
|
||||
|
||||
// ChartGraph G6关系图数据对象 chart_graph
|
||||
// ChartGraph 图表-G6关系图数据对象 chart_graph
|
||||
type ChartGraph struct {
|
||||
RowID int64 `json:"rowId,omitempty" gorm:"column:row_id;primaryKey;autoIncrement"` // 记录ID
|
||||
RowType string `json:"rowType,omitempty" gorm:"column:row_type"` // 记录类型(node/edge/combo)
|
||||
RowGroup string `json:"rowGroup,omitempty" gorm:"column:row_group"` // 记录组名
|
||||
ID string `json:"id,omitempty" gorm:"column:id"` // 元素ID
|
||||
Type string `json:"type,omitempty" gorm:"column:type"` // node/combo 类型
|
||||
Depth int `json:"depth,omitempty" gorm:"column:depth"` // node/combo 深度
|
||||
X float64 `json:"x,omitempty" gorm:"column:x"` // node/combo 横向坐标
|
||||
Y float64 `json:"y,omitempty" gorm:"column:y"` // node/combo 纵向坐标
|
||||
Size string `json:"size,omitempty" gorm:"column:size"` // node/combo 大小-JSON数组
|
||||
Icon string `json:"icon,omitempty" gorm:"column:icon"` // node-部分类型支持图标JSON配置
|
||||
Img string `json:"img,omitempty" gorm:"column:img"` // node-img 图片
|
||||
ClipCfg string `json:"clipCfg,omitempty" gorm:"column:clip_cfg"` // node-img 图片裁剪JSON配置
|
||||
Direction string `json:"direction,omitempty" gorm:"column:direction"` // node-triangle 三角形的方向(up/down/left/right)
|
||||
Source string `json:"source,omitempty" gorm:"column:source"` // edge-边起始
|
||||
Target string `json:"target,omitempty" gorm:"column:target"` // edge-边目标
|
||||
ComboID string `json:"combo_id,omitempty" gorm:"column:combo_id"` // combo-分组
|
||||
Padding string `json:"padding,omitempty" gorm:"column:padding"` // combo-JSON分组内边距
|
||||
ParentID string `json:"parentId,omitempty" gorm:"column:parent_id"` // combo-父级分组
|
||||
Children string `json:"children,omitempty" gorm:"column:children"` // combo-JSON分组内含元素
|
||||
Style string `json:"style,omitempty" gorm:"column:style"` // 元素样式-JONS配置
|
||||
Label string `json:"label,omitempty" gorm:"column:label"` // 标签文本
|
||||
LabelCfg string `json:"labelCfg,omitempty" gorm:"column:label_cfg"` // 标签文本-JSON配置
|
||||
RowType string `json:"rowType" gorm:"row_type"` // 记录类型
|
||||
RowGroup string `json:"rowGroup" gorm:"row_group"` // 记录组名
|
||||
ID string `json:"id" gorm:"id"` // 元素ID
|
||||
Type string `json:"type" gorm:"type"` // node/combo 类型
|
||||
Depth int64 `json:"depth" gorm:"depth"` // node/combo 深度
|
||||
X float64 `json:"x" gorm:"x"` // node/combo 横向坐标
|
||||
Y float64 `json:"y" gorm:"y"` // node/combo 纵向坐标
|
||||
Size string `json:"size" gorm:"size"` // node/combo 大小-JSON数组
|
||||
Icon string `json:"icon" gorm:"icon"` // node-部分类型支持图标JSON配置
|
||||
Img string `json:"img" gorm:"img"` // node-img 图片
|
||||
ClipCfg string `json:"clipCfg" gorm:"clip_cfg"` // node-img 图片裁剪JSON配置
|
||||
Direction string `json:"direction" gorm:"direction"` // node-triangle 三角形的方向
|
||||
Source string `json:"source" gorm:"source"` // edge-边起始
|
||||
Target string `json:"target" gorm:"target"` // edge-边目标
|
||||
ComboId string `json:"comboId" gorm:"combo_id"` // combo-分组
|
||||
Padding string `json:"padding" gorm:"padding"` // combo-JSON分组内边距
|
||||
ParentId string `json:"parentId" gorm:"parent_id"` // combo-父级分组
|
||||
Children string `json:"children" gorm:"children"` // combo-JSON分组内含元素
|
||||
Style string `json:"style" gorm:"style"` // 元素样式-JONS配置
|
||||
Label string `json:"label" gorm:"label"` // 标签文本
|
||||
LabelCfg string `json:"labelCfg" gorm:"label_cfg"` // 标签文本-JSON配置
|
||||
}
|
||||
|
||||
func (ChartGraph) TableName() string {
|
||||
// TableName 表名称
|
||||
func (*ChartGraph) TableName() string {
|
||||
return "chart_graph"
|
||||
}
|
||||
|
||||
@@ -1,21 +1,194 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/chart/model"
|
||||
import (
|
||||
"strings"
|
||||
|
||||
// G6关系图数据 数据层接口
|
||||
type IChartGraph interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/chart/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(graph model.ChartGraph) []model.ChartGraph
|
||||
// 实例化数据层 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`,
|
||||
|
||||
// SelectGroup 查询组名
|
||||
SelectGroup() []string
|
||||
|
||||
// Insert 批量添加
|
||||
Inserts(graphs []model.ChartGraph) int64
|
||||
|
||||
// Delete 删除组数据
|
||||
DeleteGroup(rowGroup string) int64
|
||||
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关系图数据表 数据层处理
|
||||
type ChartGraph struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *ChartGraph) convertResultRows(rows []map[string]any) []model.ChartGraph {
|
||||
arr := make([]model.ChartGraph, 0)
|
||||
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 != "" {
|
||||
conditions = append(conditions, "row_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["rowGroup"]; ok && v != "" {
|
||||
conditions = append(conditions, "row_group = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.ChartGraph{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from chart_graph"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *ChartGraph) SelectList(graph model.ChartGraph) []model.ChartGraph {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if graph.RowType != "" {
|
||||
conditions = append(conditions, "row_type = ?")
|
||||
params = append(params, graph.RowType)
|
||||
}
|
||||
if graph.RowGroup != "" {
|
||||
conditions = append(conditions, "row_group = ?")
|
||||
params = append(params, graph.RowGroup)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by depth asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectGroup 查询组名
|
||||
func (r *ChartGraph) SelectGroup() []string {
|
||||
rows := []string{}
|
||||
// 查询数量 长度为0直接返回
|
||||
querySql := "select row_group as 'str' from chart_graph GROUP BY row_group"
|
||||
strRows, err := datasource.RawDB("", querySql, nil)
|
||||
if err != nil {
|
||||
logger.Errorf("Query err => %v", err)
|
||||
return rows
|
||||
}
|
||||
for _, v := range strRows {
|
||||
rows = append(rows, v["str"].(string))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// Insert 批量添加
|
||||
func (r *ChartGraph) Inserts(graphs []model.ChartGraph) int64 {
|
||||
tx := datasource.DefaultDB().CreateInBatches(graphs, 2000)
|
||||
if err := tx.Error; err != nil {
|
||||
logger.Errorf("CreateInBatches err => %v", err)
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
|
||||
// Delete 删除组数据
|
||||
func (r *ChartGraph) DeleteGroup(rowGroup string) int64 {
|
||||
tx := datasource.DefaultDB().Where("row_group = ?", rowGroup).Delete(&model.ChartGraph{})
|
||||
if err := tx.Error; err != nil {
|
||||
logger.Errorf("Delete err => %v", err)
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"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/chart/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewChartGraphImpl 结构体
|
||||
var NewChartGraphImpl = &ChartGraphImpl{
|
||||
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",
|
||||
},
|
||||
}
|
||||
|
||||
// ChartGraphImpl G6关系图数据表 数据层处理
|
||||
type ChartGraphImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *ChartGraphImpl) convertResultRows(rows []map[string]any) []model.ChartGraph {
|
||||
arr := make([]model.ChartGraph, 0)
|
||||
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 *ChartGraphImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["rowType"]; ok && v != "" {
|
||||
conditions = append(conditions, "row_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["rowGroup"]; ok && v != "" {
|
||||
conditions = append(conditions, "row_group = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.ChartGraph{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from chart_graph"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *ChartGraphImpl) SelectList(graph model.ChartGraph) []model.ChartGraph {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if graph.RowType != "" {
|
||||
conditions = append(conditions, "row_type = ?")
|
||||
params = append(params, graph.RowType)
|
||||
}
|
||||
if graph.RowGroup != "" {
|
||||
conditions = append(conditions, "row_group = ?")
|
||||
params = append(params, graph.RowGroup)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by depth asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectGroup 查询组名
|
||||
func (r *ChartGraphImpl) SelectGroup() []string {
|
||||
rows := []string{}
|
||||
// 查询数量 长度为0直接返回
|
||||
querySql := "select row_group as 'str' from chart_graph GROUP BY row_group"
|
||||
strRows, err := datasource.RawDB("", querySql, nil)
|
||||
if err != nil {
|
||||
logger.Errorf("Query err => %v", err)
|
||||
return rows
|
||||
}
|
||||
for _, v := range strRows {
|
||||
rows = append(rows, v["str"].(string))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// Insert 批量添加
|
||||
func (r *ChartGraphImpl) Inserts(graphs []model.ChartGraph) int64 {
|
||||
tx := datasource.DefaultDB().CreateInBatches(graphs, 2000)
|
||||
if err := tx.Error; err != nil {
|
||||
logger.Errorf("CreateInBatches err => %v", err)
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
|
||||
// Delete 删除组数据
|
||||
func (r *ChartGraphImpl) DeleteGroup(rowGroup string) int64 {
|
||||
tx := datasource.DefaultDB().Where("row_group = ?", rowGroup).Delete(&model.ChartGraph{})
|
||||
if err := tx.Error; err != nil {
|
||||
logger.Errorf("Delete err => %v", err)
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
@@ -1,16 +1,359 @@
|
||||
package service
|
||||
|
||||
// G6关系图数据 服务层接口
|
||||
type IChartGraph interface {
|
||||
// SelectGroup 查询组名
|
||||
SelectGroup() []string
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
// LoadData 查询所组图数据
|
||||
LoadData(rowGroup, rowType string) map[string]any
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/chart/model"
|
||||
"be.ems/src/modules/chart/repository"
|
||||
)
|
||||
|
||||
// SaveData 添加组图数据
|
||||
SaveData(rowGroup string, data map[string]any) int64
|
||||
|
||||
// DeleteGroup 删除所组图数据
|
||||
DeleteGroup(rowGroup string) int64
|
||||
// 实例化服务层 ChartGraph 结构体
|
||||
var NewChartGraph = &ChartGraph{
|
||||
graphRepository: repository.NewChartGraph,
|
||||
}
|
||||
|
||||
// ChartGraph G6关系图数据表 服务层处理
|
||||
type ChartGraph struct {
|
||||
// G6关系图数据服务
|
||||
graphRepository *repository.ChartGraph
|
||||
}
|
||||
|
||||
// SelectGroup 查询组名
|
||||
func (s *ChartGraph) SelectGroup() []string {
|
||||
return s.graphRepository.SelectGroup()
|
||||
}
|
||||
|
||||
// LoadData 查询所组图数据
|
||||
func (s *ChartGraph) LoadData(rowGroup, rowType string) map[string]any {
|
||||
// 查询数据
|
||||
graph := model.ChartGraph{
|
||||
RowGroup: rowGroup,
|
||||
}
|
||||
if rowType != "" {
|
||||
graph.RowType = rowType
|
||||
}
|
||||
data := s.graphRepository.SelectList(graph)
|
||||
|
||||
// 数据项
|
||||
nodes := []map[string]any{}
|
||||
edges := []map[string]any{}
|
||||
combos := []map[string]any{}
|
||||
|
||||
for _, v := range data {
|
||||
if v.RowType == "node" {
|
||||
nodes = append(nodes, s.loadNode(v))
|
||||
}
|
||||
if v.RowType == "edge" {
|
||||
edges = append(edges, s.loadEdge(v))
|
||||
}
|
||||
if v.RowType == "combo" {
|
||||
combos = append(combos, s.loadCombo(v))
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
"combos": combos,
|
||||
}
|
||||
}
|
||||
|
||||
// loadNode 图数据Node
|
||||
func (s *ChartGraph) loadNode(v model.ChartGraph) map[string]any {
|
||||
node := map[string]any{
|
||||
"id": v.ID,
|
||||
"comboId": v.ComboId,
|
||||
"x": v.X,
|
||||
"y": v.Y,
|
||||
"type": v.Type,
|
||||
"depth": v.Depth,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
node["style"] = style
|
||||
|
||||
// 元素大小
|
||||
if strings.Contains(v.Size, "[") {
|
||||
sizeArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Size), &sizeArr)
|
||||
node["size"] = sizeArr
|
||||
} else {
|
||||
node["size"] = parse.Number(v.Size)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
node["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
node["labelCfg"] = labelCfg
|
||||
|
||||
// 三角形属性
|
||||
if v.Type == "triangle" {
|
||||
node["direction"] = v.Direction
|
||||
}
|
||||
|
||||
// 图片属性
|
||||
if strings.Index(v.Type, "image") == 0 {
|
||||
node["img"] = v.Img
|
||||
clipCfg := map[string]any{}
|
||||
if len(v.ClipCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.ClipCfg), &clipCfg)
|
||||
}
|
||||
node["clipCfg"] = clipCfg
|
||||
}
|
||||
|
||||
// 图标属性
|
||||
if v.Icon != "" {
|
||||
icon := map[string]any{}
|
||||
if len(v.Icon) > 7 {
|
||||
json.Unmarshal([]byte(v.Icon), &icon)
|
||||
}
|
||||
node["icon"] = icon
|
||||
}
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
// loadEdge 图数据Edge
|
||||
func (s *ChartGraph) loadEdge(v model.ChartGraph) map[string]any {
|
||||
edge := map[string]any{
|
||||
"id": v.ID,
|
||||
"source": v.Source,
|
||||
"target": v.Target,
|
||||
"type": v.Type,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
edge["style"] = style
|
||||
|
||||
// 标签文本
|
||||
edge["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
edge["labelCfg"] = labelCfg
|
||||
|
||||
return edge
|
||||
}
|
||||
|
||||
// loadCombo 图数据Combo
|
||||
func (s *ChartGraph) loadCombo(v model.ChartGraph) map[string]any {
|
||||
combo := map[string]any{
|
||||
"id": v.ID,
|
||||
"x": v.X,
|
||||
"y": v.Y,
|
||||
"type": v.Type,
|
||||
"depth": v.Depth,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
combo["style"] = style
|
||||
|
||||
// 元素大小
|
||||
if strings.Contains(v.Size, "[") {
|
||||
sizeArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Size), &sizeArr)
|
||||
combo["size"] = sizeArr
|
||||
} else {
|
||||
combo["size"] = parse.Number(v.Size)
|
||||
}
|
||||
|
||||
// 元素内边距
|
||||
if strings.Contains(v.Padding, "[") {
|
||||
paddingArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Padding), &paddingArr)
|
||||
combo["padding"] = paddingArr
|
||||
} else {
|
||||
combo["padding"] = parse.Number(v.Padding)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
combo["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
combo["labelCfg"] = labelCfg
|
||||
|
||||
// 分组内元素
|
||||
if v.Children != "" {
|
||||
children := []map[string]any{}
|
||||
if len(v.Children) > 7 {
|
||||
json.Unmarshal([]byte(v.Children), &children)
|
||||
}
|
||||
combo["children"] = children
|
||||
}
|
||||
|
||||
return combo
|
||||
}
|
||||
|
||||
// SaveData 添加组图数据
|
||||
func (s *ChartGraph) SaveData(rowGroup string, data map[string]any) int64 {
|
||||
graphs := []model.ChartGraph{}
|
||||
nodes := data["nodes"].([]map[string]any)
|
||||
graphNodes := s.saveNode(rowGroup, nodes)
|
||||
graphs = append(graphs, graphNodes...)
|
||||
edges := data["edges"].([]map[string]any)
|
||||
graphEdges := s.saveEdge(rowGroup, edges)
|
||||
graphs = append(graphs, graphEdges...)
|
||||
combos := data["combos"].([]map[string]any)
|
||||
graphCombos := s.saveCombo(rowGroup, combos)
|
||||
graphs = append(graphs, graphCombos...)
|
||||
// 删除组数据后插入
|
||||
if len(graphs) > 0 {
|
||||
s.graphRepository.DeleteGroup(rowGroup)
|
||||
}
|
||||
return s.graphRepository.Inserts(graphs)
|
||||
}
|
||||
|
||||
// saveNode 图数据Node
|
||||
func (s *ChartGraph) saveNode(rowGroup string, nodes []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range nodes {
|
||||
node := model.ChartGraph{
|
||||
RowType: "node",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
X: v["x"].(float64),
|
||||
Y: v["y"].(float64),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
if comboId, ok := v["comboId"]; ok && comboId != nil {
|
||||
node.ComboId = comboId.(string)
|
||||
}
|
||||
if depth, ok := v["depth"]; ok && depth != nil {
|
||||
node.Depth = int64(depth.(float64))
|
||||
}
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
node.Style = string(styleByte)
|
||||
}
|
||||
|
||||
// 元素大小
|
||||
if sizeByte, err := json.Marshal(v["size"]); err == nil {
|
||||
node.Size = string(sizeByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
node.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
node.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
// 三角形属性
|
||||
if direction, ok := v["direction"]; ok && direction != nil && node.Type == "triangle" {
|
||||
node.Direction = direction.(string)
|
||||
}
|
||||
// 图片属性
|
||||
if img, ok := v["img"]; ok && img != nil {
|
||||
node.Img = img.(string)
|
||||
if clipCfgByte, err := json.Marshal(v["clipCfg"]); err == nil {
|
||||
node.ClipCfg = string(clipCfgByte)
|
||||
}
|
||||
}
|
||||
// 图标属性
|
||||
if icon, ok := v["icon"]; ok && icon != nil {
|
||||
if iconByte, err := json.Marshal(icon); err == nil {
|
||||
node.Icon = string(iconByte)
|
||||
}
|
||||
}
|
||||
|
||||
graphs = append(graphs, node)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// saveEdge 图数据Edge
|
||||
func (s *ChartGraph) saveEdge(rowGroup string, edges []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range edges {
|
||||
edge := model.ChartGraph{
|
||||
RowType: "edge",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
Source: v["source"].(string),
|
||||
Target: v["target"].(string),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
edge.Style = string(styleByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
edge.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
edge.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
|
||||
graphs = append(graphs, edge)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// saveCombo 图数据Combo
|
||||
func (s *ChartGraph) saveCombo(rowGroup string, combos []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range combos {
|
||||
combo := model.ChartGraph{
|
||||
RowType: "combo",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
X: v["x"].(float64),
|
||||
Y: v["y"].(float64),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
if depth, ok := v["depth"]; ok && depth != nil {
|
||||
combo.Depth = int64(depth.(float64))
|
||||
}
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
combo.Style = string(styleByte)
|
||||
}
|
||||
if paddingByte, err := json.Marshal(v["padding"]); err == nil {
|
||||
combo.Padding = string(paddingByte)
|
||||
}
|
||||
if childrenByte, err := json.Marshal(v["children"]); err == nil {
|
||||
combo.Children = string(childrenByte)
|
||||
}
|
||||
|
||||
// 元素大小
|
||||
if sizeByte, err := json.Marshal(v["size"]); err == nil {
|
||||
combo.Size = string(sizeByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
combo.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
combo.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
|
||||
graphs = append(graphs, combo)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// Delete 删除所组图数据
|
||||
func (s *ChartGraph) DeleteGroup(rowGroup string) int64 {
|
||||
return s.graphRepository.DeleteGroup(rowGroup)
|
||||
}
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/chart/model"
|
||||
chartRepository "be.ems/src/modules/chart/repository"
|
||||
"github.com/goccy/go-json"
|
||||
)
|
||||
|
||||
// 实例化服务层 ChartGraphImpl 结构体
|
||||
var NewChartGraphImpl = &ChartGraphImpl{
|
||||
graphRepository: chartRepository.NewChartGraphImpl,
|
||||
}
|
||||
|
||||
// ChartGraphImpl G6关系图数据表 服务层处理
|
||||
type ChartGraphImpl struct {
|
||||
// G6关系图数据服务
|
||||
graphRepository chartRepository.IChartGraph
|
||||
}
|
||||
|
||||
// SelectGroup 查询组名
|
||||
func (s *ChartGraphImpl) SelectGroup() []string {
|
||||
return s.graphRepository.SelectGroup()
|
||||
}
|
||||
|
||||
// LoadData 查询所组图数据
|
||||
func (s *ChartGraphImpl) LoadData(rowGroup, rowType string) map[string]any {
|
||||
// 查询数据
|
||||
graph := model.ChartGraph{
|
||||
RowGroup: rowGroup,
|
||||
}
|
||||
if rowType != "" {
|
||||
graph.RowType = rowType
|
||||
}
|
||||
data := s.graphRepository.SelectList(graph)
|
||||
|
||||
// 数据项
|
||||
nodes := []map[string]any{}
|
||||
edges := []map[string]any{}
|
||||
combos := []map[string]any{}
|
||||
|
||||
for _, v := range data {
|
||||
if v.RowType == "node" {
|
||||
nodes = append(nodes, s.loadNode(v))
|
||||
}
|
||||
if v.RowType == "edge" {
|
||||
edges = append(edges, s.loadEdge(v))
|
||||
}
|
||||
if v.RowType == "combo" {
|
||||
combos = append(combos, s.loadCombo(v))
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
"combos": combos,
|
||||
}
|
||||
}
|
||||
|
||||
// loadNode 图数据Node
|
||||
func (s *ChartGraphImpl) loadNode(v model.ChartGraph) map[string]any {
|
||||
node := map[string]any{
|
||||
"id": v.ID,
|
||||
"comboId": v.ComboID,
|
||||
"x": v.X,
|
||||
"y": v.Y,
|
||||
"type": v.Type,
|
||||
"depth": v.Depth,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
node["style"] = style
|
||||
|
||||
// 元素大小
|
||||
if strings.Contains(v.Size, "[") {
|
||||
sizeArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Size), &sizeArr)
|
||||
node["size"] = sizeArr
|
||||
} else {
|
||||
node["size"] = parse.Number(v.Size)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
node["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
node["labelCfg"] = labelCfg
|
||||
|
||||
// 三角形属性
|
||||
if v.Type == "triangle" {
|
||||
node["direction"] = v.Direction
|
||||
}
|
||||
|
||||
// 图片属性
|
||||
if strings.Index(v.Type, "image") == 0 {
|
||||
node["img"] = v.Img
|
||||
clipCfg := map[string]any{}
|
||||
if len(v.ClipCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.ClipCfg), &clipCfg)
|
||||
}
|
||||
node["clipCfg"] = clipCfg
|
||||
}
|
||||
|
||||
// 图标属性
|
||||
if v.Icon != "" {
|
||||
icon := map[string]any{}
|
||||
if len(v.Icon) > 7 {
|
||||
json.Unmarshal([]byte(v.Icon), &icon)
|
||||
}
|
||||
node["icon"] = icon
|
||||
}
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
// loadEdge 图数据Edge
|
||||
func (s *ChartGraphImpl) loadEdge(v model.ChartGraph) map[string]any {
|
||||
edge := map[string]any{
|
||||
"id": v.ID,
|
||||
"source": v.Source,
|
||||
"target": v.Target,
|
||||
"type": v.Type,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
edge["style"] = style
|
||||
|
||||
// 标签文本
|
||||
edge["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
edge["labelCfg"] = labelCfg
|
||||
|
||||
return edge
|
||||
}
|
||||
|
||||
// loadCombo 图数据Combo
|
||||
func (s *ChartGraphImpl) loadCombo(v model.ChartGraph) map[string]any {
|
||||
combo := map[string]any{
|
||||
"id": v.ID,
|
||||
"x": v.X,
|
||||
"y": v.Y,
|
||||
"type": v.Type,
|
||||
"depth": v.Depth,
|
||||
}
|
||||
|
||||
// 元素样式
|
||||
style := map[string]any{}
|
||||
if len(v.Style) > 7 {
|
||||
json.Unmarshal([]byte(v.Style), &style)
|
||||
}
|
||||
combo["style"] = style
|
||||
|
||||
// 元素大小
|
||||
if strings.Contains(v.Size, "[") {
|
||||
sizeArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Size), &sizeArr)
|
||||
combo["size"] = sizeArr
|
||||
} else {
|
||||
combo["size"] = parse.Number(v.Size)
|
||||
}
|
||||
|
||||
// 元素内边距
|
||||
if strings.Contains(v.Padding, "[") {
|
||||
paddingArr := []int64{}
|
||||
json.Unmarshal([]byte(v.Padding), &paddingArr)
|
||||
combo["padding"] = paddingArr
|
||||
} else {
|
||||
combo["padding"] = parse.Number(v.Padding)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
combo["label"] = v.Label
|
||||
labelCfg := map[string]any{}
|
||||
if len(v.LabelCfg) > 7 {
|
||||
json.Unmarshal([]byte(v.LabelCfg), &labelCfg)
|
||||
}
|
||||
combo["labelCfg"] = labelCfg
|
||||
|
||||
// 分组内元素
|
||||
if v.Children != "" {
|
||||
children := []map[string]any{}
|
||||
if len(v.Children) > 7 {
|
||||
json.Unmarshal([]byte(v.Children), &children)
|
||||
}
|
||||
combo["children"] = children
|
||||
}
|
||||
|
||||
return combo
|
||||
}
|
||||
|
||||
// SaveData 添加组图数据
|
||||
func (s *ChartGraphImpl) SaveData(rowGroup string, data map[string]any) int64 {
|
||||
graphs := []model.ChartGraph{}
|
||||
nodes := data["nodes"].([]map[string]any)
|
||||
graphNodes := s.saveNode(rowGroup, nodes)
|
||||
graphs = append(graphs, graphNodes...)
|
||||
edges := data["edges"].([]map[string]any)
|
||||
graphEdges := s.saveEdge(rowGroup, edges)
|
||||
graphs = append(graphs, graphEdges...)
|
||||
combos := data["combos"].([]map[string]any)
|
||||
graphCombos := s.saveCombo(rowGroup, combos)
|
||||
graphs = append(graphs, graphCombos...)
|
||||
// 删除组数据后插入
|
||||
if len(graphs) > 0 {
|
||||
s.graphRepository.DeleteGroup(rowGroup)
|
||||
}
|
||||
return s.graphRepository.Inserts(graphs)
|
||||
}
|
||||
|
||||
// saveNode 图数据Node
|
||||
func (s *ChartGraphImpl) saveNode(rowGroup string, nodes []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range nodes {
|
||||
node := model.ChartGraph{
|
||||
RowType: "node",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
X: v["x"].(float64),
|
||||
Y: v["y"].(float64),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
if comboId, ok := v["comboId"]; ok && comboId != nil {
|
||||
node.ComboID = comboId.(string)
|
||||
}
|
||||
if depth, ok := v["depth"]; ok && depth != nil {
|
||||
node.Depth = int(depth.(float64))
|
||||
}
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
node.Style = string(styleByte)
|
||||
}
|
||||
|
||||
// 元素大小
|
||||
if sizeByte, err := json.Marshal(v["size"]); err == nil {
|
||||
node.Size = string(sizeByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
node.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
node.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
// 三角形属性
|
||||
if direction, ok := v["direction"]; ok && direction != nil && node.Type == "triangle" {
|
||||
node.Direction = direction.(string)
|
||||
}
|
||||
// 图片属性
|
||||
if img, ok := v["img"]; ok && img != nil {
|
||||
node.Img = img.(string)
|
||||
if clipCfgByte, err := json.Marshal(v["clipCfg"]); err == nil {
|
||||
node.ClipCfg = string(clipCfgByte)
|
||||
}
|
||||
}
|
||||
// 图标属性
|
||||
if icon, ok := v["icon"]; ok && icon != nil {
|
||||
if iconByte, err := json.Marshal(icon); err == nil {
|
||||
node.Icon = string(iconByte)
|
||||
}
|
||||
}
|
||||
|
||||
graphs = append(graphs, node)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// saveEdge 图数据Edge
|
||||
func (s *ChartGraphImpl) saveEdge(rowGroup string, edges []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range edges {
|
||||
edge := model.ChartGraph{
|
||||
RowType: "edge",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
Source: v["source"].(string),
|
||||
Target: v["target"].(string),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
edge.Style = string(styleByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
edge.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
edge.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
|
||||
graphs = append(graphs, edge)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// saveCombo 图数据Combo
|
||||
func (s *ChartGraphImpl) saveCombo(rowGroup string, combos []map[string]any) []model.ChartGraph {
|
||||
var graphs []model.ChartGraph
|
||||
for _, v := range combos {
|
||||
combo := model.ChartGraph{
|
||||
RowType: "combo",
|
||||
RowGroup: rowGroup,
|
||||
ID: v["id"].(string),
|
||||
X: v["x"].(float64),
|
||||
Y: v["y"].(float64),
|
||||
Type: v["type"].(string),
|
||||
}
|
||||
if depth, ok := v["depth"]; ok && depth != nil {
|
||||
combo.Depth = int(depth.(float64))
|
||||
}
|
||||
if styleByte, err := json.Marshal(v["style"]); err == nil {
|
||||
combo.Style = string(styleByte)
|
||||
}
|
||||
if paddingByte, err := json.Marshal(v["padding"]); err == nil {
|
||||
combo.Padding = string(paddingByte)
|
||||
}
|
||||
if childrenByte, err := json.Marshal(v["children"]); err == nil {
|
||||
combo.Children = string(childrenByte)
|
||||
}
|
||||
|
||||
// 元素大小
|
||||
if sizeByte, err := json.Marshal(v["size"]); err == nil {
|
||||
combo.Size = string(sizeByte)
|
||||
}
|
||||
|
||||
// 标签文本
|
||||
if label, ok := v["label"]; ok && label != nil {
|
||||
combo.Label = label.(string)
|
||||
}
|
||||
if labelCfgByte, err := json.Marshal(v["labelCfg"]); err == nil {
|
||||
combo.LabelCfg = string(labelCfgByte)
|
||||
}
|
||||
|
||||
graphs = append(graphs, combo)
|
||||
}
|
||||
return graphs
|
||||
}
|
||||
|
||||
// Delete 删除所组图数据
|
||||
func (s *ChartGraphImpl) DeleteGroup(rowGroup string) int64 {
|
||||
return s.graphRepository.DeleteGroup(rowGroup)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
|
||||
// 实例化控制层 AccountController 结构体
|
||||
var NewAccount = &AccountController{
|
||||
accountService: commonService.NewAccountImpl,
|
||||
accountService: commonService.NewAccount,
|
||||
sysLogLoginService: systemService.NewSysLogLoginImpl,
|
||||
}
|
||||
|
||||
@@ -25,8 +25,7 @@ var NewAccount = &AccountController{
|
||||
//
|
||||
// PATH /
|
||||
type AccountController struct {
|
||||
// 账号身份操作服务
|
||||
accountService commonService.IAccount
|
||||
accountService *commonService.Account // 账号身份操作服务
|
||||
// 系统登录访问
|
||||
sysLogLoginService systemService.ISysLogLogin
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
// 实例化控制层 BootloaderController 结构体
|
||||
var NewBootloader = &BootloaderController{
|
||||
accountService: commonService.NewAccountImpl,
|
||||
accountService: commonService.NewAccount,
|
||||
sysUserService: systemService.NewSysUserImpl,
|
||||
}
|
||||
|
||||
@@ -26,8 +26,7 @@ var NewBootloader = &BootloaderController{
|
||||
//
|
||||
// PATH /bootloader
|
||||
type BootloaderController struct {
|
||||
// 账号身份操作服务
|
||||
accountService commonService.IAccount
|
||||
accountService *commonService.Account // 账号身份操作服务
|
||||
// 用户信息服务
|
||||
sysUserService systemService.ISysUser
|
||||
}
|
||||
|
||||
@@ -1,24 +1,194 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/framework/vo"
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
// 账号身份操作服务 服务层接口
|
||||
type IAccount interface {
|
||||
// ValidateCaptcha 校验验证码
|
||||
ValidateCaptcha(code, uuid string) error
|
||||
"be.ems/src/framework/config"
|
||||
adminConstants "be.ems/src/framework/constants/admin"
|
||||
"be.ems/src/framework/constants/cachekey"
|
||||
"be.ems/src/framework/constants/common"
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/framework/utils/crypto"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/framework/vo"
|
||||
"be.ems/src/modules/system/model"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
)
|
||||
|
||||
// LoginByUsername 登录生成token
|
||||
LoginByUsername(username, password string) (vo.LoginUser, error)
|
||||
|
||||
// UpdateLoginDateAndIP 更新登录时间和IP
|
||||
UpdateLoginDateAndIP(loginUser *vo.LoginUser) bool
|
||||
|
||||
// ClearLoginRecordCache 清除错误记录次数
|
||||
ClearLoginRecordCache(username string) bool
|
||||
|
||||
// RoleAndMenuPerms 角色和菜单数据权限
|
||||
RoleAndMenuPerms(userId string, isAdmin bool) ([]string, []string)
|
||||
|
||||
// RouteMenus 前端路由所需要的菜单
|
||||
RouteMenus(userId string, isAdmin bool) []vo.Router
|
||||
// 实例化服务层 Account 结构体
|
||||
var NewAccount = &Account{
|
||||
sysUserService: systemService.NewSysUserImpl,
|
||||
sysConfigService: systemService.NewSysConfigImpl,
|
||||
sysRoleService: systemService.NewSysRoleImpl,
|
||||
sysMenuService: systemService.NewSysMenuImpl,
|
||||
}
|
||||
|
||||
// 账号身份操作服务 服务层处理
|
||||
type Account struct {
|
||||
// 用户信息服务
|
||||
sysUserService systemService.ISysUser
|
||||
// 参数配置服务
|
||||
sysConfigService systemService.ISysConfig
|
||||
// 角色服务
|
||||
sysRoleService systemService.ISysRole
|
||||
// 菜单服务
|
||||
sysMenuService systemService.ISysMenu
|
||||
}
|
||||
|
||||
// ValidateCaptcha 校验验证码
|
||||
func (s *Account) 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("captcha.err")
|
||||
}
|
||||
verifyKey := cachekey.CAPTCHA_CODE_KEY + uuid
|
||||
captcha, _ := redis.Get("", verifyKey)
|
||||
if captcha == "" {
|
||||
// 验证码已失效
|
||||
return fmt.Errorf("captcha.errValid")
|
||||
}
|
||||
redis.Del("", verifyKey)
|
||||
if captcha != code {
|
||||
// 验证码错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoginByUsername 登录创建用户信息
|
||||
func (s *Account) LoginByUsername(username, password string) (vo.LoginUser, error) {
|
||||
loginUser := vo.LoginUser{}
|
||||
|
||||
// 检查密码重试次数
|
||||
retrykey, retryCount, lockTime, err := s.passwordRetryCount(username)
|
||||
if err != nil {
|
||||
return loginUser, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.SelectUserByUserName(username)
|
||||
if sysUser.UserName != username {
|
||||
return loginUser, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == common.STATUS_YES {
|
||||
// 对不起,您的账号已被删除
|
||||
return loginUser, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.Status == common.STATUS_NO {
|
||||
return loginUser, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 检验用户密码
|
||||
compareBool := crypto.BcryptCompare(password, sysUser.Password)
|
||||
if !compareBool {
|
||||
redis.SetByExpire("", retrykey, retryCount+1, lockTime)
|
||||
// 用户不存在或密码错误
|
||||
return loginUser, fmt.Errorf("login.errNameOrPasswd")
|
||||
} else {
|
||||
// 清除错误记录次数
|
||||
s.ClearLoginRecordCache(username)
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
loginUser.UserID = sysUser.UserID
|
||||
loginUser.DeptID = sysUser.DeptID
|
||||
loginUser.User = sysUser
|
||||
// 用户权限组标识
|
||||
isAdmin := config.IsAdmin(sysUser.UserID)
|
||||
if isAdmin {
|
||||
loginUser.Permissions = []string{adminConstants.PERMISSION}
|
||||
} else {
|
||||
perms := s.sysMenuService.SelectMenuPermsByUserId(sysUser.UserID)
|
||||
loginUser.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return loginUser, nil
|
||||
}
|
||||
|
||||
// UpdateLoginDateAndIP 更新登录时间和IP
|
||||
func (s *Account) UpdateLoginDateAndIP(loginUser *vo.LoginUser) bool {
|
||||
sysUser := loginUser.User
|
||||
userInfo := model.SysUser{
|
||||
UserID: sysUser.UserID,
|
||||
LoginIP: sysUser.LoginIP,
|
||||
LoginDate: sysUser.LoginDate,
|
||||
UpdateBy: sysUser.UserName,
|
||||
Sex: sysUser.Sex,
|
||||
PhoneNumber: sysUser.PhoneNumber,
|
||||
Email: sysUser.Email,
|
||||
Remark: sysUser.Remark,
|
||||
}
|
||||
rows := s.sysUserService.UpdateUser(userInfo)
|
||||
return rows > 0
|
||||
}
|
||||
|
||||
// ClearLoginRecordCache 清除错误记录次数
|
||||
func (s *Account) ClearLoginRecordCache(username string) bool {
|
||||
cacheKey := cachekey.PWD_ERR_CNT_KEY + username
|
||||
hasKey, _ := redis.Has("", cacheKey)
|
||||
if hasKey {
|
||||
delOk, _ := redis.Del("", cacheKey)
|
||||
return delOk
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// passwordRetryCount 密码重试次数
|
||||
func (s *Account) passwordRetryCount(username string) (string, int64, time.Duration, error) {
|
||||
// 从数据库配置获取登录次数和错误锁定时间
|
||||
maxRetryCountStr := s.sysConfigService.SelectConfigValueByKey("sys.user.maxRetryCount")
|
||||
lockTimeStr := s.sysConfigService.SelectConfigValueByKey("sys.user.lockTime")
|
||||
|
||||
// 验证登录次数和错误锁定时间
|
||||
maxRetryCount := parse.Number(maxRetryCountStr)
|
||||
lockTime := parse.Number(lockTimeStr)
|
||||
// 验证缓存记录次数
|
||||
retrykey := cachekey.PWD_ERR_CNT_KEY + username
|
||||
retryCount, err := redis.Get("", retrykey)
|
||||
if retryCount == "" || err != nil {
|
||||
retryCount = "0"
|
||||
}
|
||||
// 是否超过错误值
|
||||
retryCountInt64 := parse.Number(retryCount)
|
||||
if retryCountInt64 >= maxRetryCount {
|
||||
// 密码输入错误多次,帐户已被锁定
|
||||
errorMsg := fmt.Errorf("login.errRetryPasswd")
|
||||
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, errorMsg
|
||||
}
|
||||
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil
|
||||
}
|
||||
|
||||
// RoleAndMenuPerms 角色和菜单数据权限
|
||||
func (s *Account) RoleAndMenuPerms(userId string, isAdmin bool) ([]string, []string) {
|
||||
if isAdmin {
|
||||
return []string{adminConstants.ROLE_KEY}, []string{adminConstants.PERMISSION}
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
|
||||
// RouteMenus 前端路由所需要的菜单
|
||||
func (s *Account) RouteMenus(userId string, isAdmin bool) []vo.Router {
|
||||
var buildMenus []vo.Router
|
||||
if isAdmin {
|
||||
menus := s.sysMenuService.SelectMenuTreeByUserId("*")
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
} else {
|
||||
menus := s.sysMenuService.SelectMenuTreeByUserId(userId)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
}
|
||||
return buildMenus
|
||||
}
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
adminConstants "be.ems/src/framework/constants/admin"
|
||||
"be.ems/src/framework/constants/cachekey"
|
||||
"be.ems/src/framework/constants/common"
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/framework/utils/crypto"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/framework/vo"
|
||||
"be.ems/src/modules/system/model"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
)
|
||||
|
||||
// 实例化服务层 AccountImpl 结构体
|
||||
var NewAccountImpl = &AccountImpl{
|
||||
sysUserService: systemService.NewSysUserImpl,
|
||||
sysConfigService: systemService.NewSysConfigImpl,
|
||||
sysRoleService: systemService.NewSysRoleImpl,
|
||||
sysMenuService: systemService.NewSysMenuImpl,
|
||||
}
|
||||
|
||||
// 账号身份操作服务 服务层处理
|
||||
type AccountImpl struct {
|
||||
// 用户信息服务
|
||||
sysUserService systemService.ISysUser
|
||||
// 参数配置服务
|
||||
sysConfigService systemService.ISysConfig
|
||||
// 角色服务
|
||||
sysRoleService systemService.ISysRole
|
||||
// 菜单服务
|
||||
sysMenuService systemService.ISysMenu
|
||||
}
|
||||
|
||||
// ValidateCaptcha 校验验证码
|
||||
func (s *AccountImpl) 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("captcha.err")
|
||||
}
|
||||
verifyKey := cachekey.CAPTCHA_CODE_KEY + uuid
|
||||
captcha, _ := redis.Get("", verifyKey)
|
||||
if captcha == "" {
|
||||
// 验证码已失效
|
||||
return fmt.Errorf("captcha.errValid")
|
||||
}
|
||||
redis.Del("", verifyKey)
|
||||
if captcha != code {
|
||||
// 验证码错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoginByUsername 登录创建用户信息
|
||||
func (s *AccountImpl) LoginByUsername(username, password string) (vo.LoginUser, error) {
|
||||
loginUser := vo.LoginUser{}
|
||||
|
||||
// 检查密码重试次数
|
||||
retrykey, retryCount, lockTime, err := s.passwordRetryCount(username)
|
||||
if err != nil {
|
||||
return loginUser, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.SelectUserByUserName(username)
|
||||
if sysUser.UserName != username {
|
||||
return loginUser, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == common.STATUS_YES {
|
||||
// 对不起,您的账号已被删除
|
||||
return loginUser, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.Status == common.STATUS_NO {
|
||||
return loginUser, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 检验用户密码
|
||||
compareBool := crypto.BcryptCompare(password, sysUser.Password)
|
||||
if !compareBool {
|
||||
redis.SetByExpire("", retrykey, retryCount+1, lockTime)
|
||||
// 用户不存在或密码错误
|
||||
return loginUser, fmt.Errorf("login.errNameOrPasswd")
|
||||
} else {
|
||||
// 清除错误记录次数
|
||||
s.ClearLoginRecordCache(username)
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
loginUser.UserID = sysUser.UserID
|
||||
loginUser.DeptID = sysUser.DeptID
|
||||
loginUser.User = sysUser
|
||||
// 用户权限组标识
|
||||
isAdmin := config.IsAdmin(sysUser.UserID)
|
||||
if isAdmin {
|
||||
loginUser.Permissions = []string{adminConstants.PERMISSION}
|
||||
} else {
|
||||
perms := s.sysMenuService.SelectMenuPermsByUserId(sysUser.UserID)
|
||||
loginUser.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return loginUser, nil
|
||||
}
|
||||
|
||||
// UpdateLoginDateAndIP 更新登录时间和IP
|
||||
func (s *AccountImpl) UpdateLoginDateAndIP(loginUser *vo.LoginUser) bool {
|
||||
sysUser := loginUser.User
|
||||
userInfo := model.SysUser{
|
||||
UserID: sysUser.UserID,
|
||||
LoginIP: sysUser.LoginIP,
|
||||
LoginDate: sysUser.LoginDate,
|
||||
UpdateBy: sysUser.UserName,
|
||||
}
|
||||
rows := s.sysUserService.UpdateUser(userInfo)
|
||||
return rows > 0
|
||||
}
|
||||
|
||||
// ClearLoginRecordCache 清除错误记录次数
|
||||
func (s *AccountImpl) ClearLoginRecordCache(username string) bool {
|
||||
cacheKey := cachekey.PWD_ERR_CNT_KEY + username
|
||||
hasKey, _ := redis.Has("", cacheKey)
|
||||
if hasKey {
|
||||
delOk, _ := redis.Del("", cacheKey)
|
||||
return delOk
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// passwordRetryCount 密码重试次数
|
||||
func (s *AccountImpl) passwordRetryCount(username string) (string, int64, time.Duration, error) {
|
||||
// 从数据库配置获取登录次数和错误锁定时间
|
||||
maxRetryCountStr := s.sysConfigService.SelectConfigValueByKey("sys.user.maxRetryCount")
|
||||
lockTimeStr := s.sysConfigService.SelectConfigValueByKey("sys.user.lockTime")
|
||||
|
||||
// 验证登录次数和错误锁定时间
|
||||
maxRetryCount := parse.Number(maxRetryCountStr)
|
||||
lockTime := parse.Number(lockTimeStr)
|
||||
// 验证缓存记录次数
|
||||
retrykey := cachekey.PWD_ERR_CNT_KEY + username
|
||||
retryCount, err := redis.Get("", retrykey)
|
||||
if retryCount == "" || err != nil {
|
||||
retryCount = "0"
|
||||
}
|
||||
// 是否超过错误值
|
||||
retryCountInt64 := parse.Number(retryCount)
|
||||
if retryCountInt64 >= maxRetryCount {
|
||||
// 密码输入错误多次,帐户已被锁定
|
||||
errorMsg := fmt.Errorf("login.errRetryPasswd")
|
||||
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, errorMsg
|
||||
}
|
||||
return retrykey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil
|
||||
}
|
||||
|
||||
// RoleAndMenuPerms 角色和菜单数据权限
|
||||
func (s *AccountImpl) RoleAndMenuPerms(userId string, isAdmin bool) ([]string, []string) {
|
||||
if isAdmin {
|
||||
return []string{adminConstants.ROLE_KEY}, []string{adminConstants.PERMISSION}
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
|
||||
// RouteMenus 前端路由所需要的菜单
|
||||
func (s *AccountImpl) RouteMenus(userId string, isAdmin bool) []vo.Router {
|
||||
var buildMenus []vo.Router
|
||||
if isAdmin {
|
||||
menus := s.sysMenuService.SelectMenuTreeByUserId("*")
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
} else {
|
||||
menus := s.sysMenuService.SelectMenuTreeByUserId(userId)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
}
|
||||
return buildMenus
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
var NewProcessor = &MonitorSysResourceProcessor{
|
||||
monitorService: monitorService.NewMonitorImpl,
|
||||
monitorService: monitorService.NewMonitor,
|
||||
count: 0,
|
||||
openDataCancel: false,
|
||||
}
|
||||
@@ -18,7 +18,7 @@ var NewProcessor = &MonitorSysResourceProcessor{
|
||||
// MonitorSysResourceProcessor 系统资源CPU/IO/Netword收集
|
||||
type MonitorSysResourceProcessor struct {
|
||||
// 服务器系统相关信息服务
|
||||
monitorService monitorService.IMonitor
|
||||
monitorService *monitorService.Monitor
|
||||
// 执行次数
|
||||
count int
|
||||
// 是否已经开启数据通道
|
||||
|
||||
@@ -11,19 +11,16 @@ import (
|
||||
)
|
||||
|
||||
var NewProcessor = &NeConfigBackupProcessor{
|
||||
neConfigBackupService: neService.NewNeConfigBackupImpl,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neConfigBackupService: neService.NewNeConfigBackup,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
count: 0,
|
||||
}
|
||||
|
||||
// NeConfigBackupProcessor 网元配置文件定期备份
|
||||
type NeConfigBackupProcessor struct {
|
||||
// 网元配置文件备份记录服务
|
||||
neConfigBackupService neService.INeConfigBackup
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// 执行次数
|
||||
count int
|
||||
neConfigBackupService *neService.NeConfigBackup // 网元配置文件备份记录服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
count int // 执行次数
|
||||
}
|
||||
|
||||
func (s *NeConfigBackupProcessor) Execute(data any) (any, error) {
|
||||
|
||||
@@ -11,15 +11,14 @@ import (
|
||||
|
||||
// 实例化控制层 MonitorInfoController 结构体
|
||||
var NewMonitor = &MonitorController{
|
||||
monitorService: service.NewMonitorImpl,
|
||||
monitorService: service.NewMonitor,
|
||||
}
|
||||
|
||||
// 服务器资源监控信息
|
||||
//
|
||||
// PATH /monitor
|
||||
type MonitorController struct {
|
||||
// 服务器系统相关信息服务
|
||||
monitorService service.IMonitor
|
||||
monitorService *service.Monitor // 服务器系统相关信息服务
|
||||
}
|
||||
|
||||
// 资源监控信息加载
|
||||
|
||||
@@ -22,18 +22,16 @@ import (
|
||||
|
||||
// 实例化控制层 SysJobLogController 结构体
|
||||
var NewSysJob = &SysJobController{
|
||||
sysJobService: service.NewSysJobImpl,
|
||||
sysDictDataService: systemService.NewSysDictDataImpl,
|
||||
sysJobService: service.NewSysJob,
|
||||
sysDictDataService: systemService.NewSysDictData,
|
||||
}
|
||||
|
||||
// 调度任务信息
|
||||
//
|
||||
// PATH /monitor/job
|
||||
type SysJobController struct {
|
||||
// 调度任务服务
|
||||
sysJobService service.ISysJob
|
||||
// 字典数据服务
|
||||
sysDictDataService systemService.ISysDictData
|
||||
sysJobService *service.SysJob // 调度任务服务
|
||||
sysDictDataService *systemService.SysDictData // 字典数据服务
|
||||
}
|
||||
|
||||
// 调度任务列表
|
||||
|
||||
@@ -21,18 +21,16 @@ import (
|
||||
|
||||
// 实例化控制层 SysJobLogController 结构体
|
||||
var NewSysJobLog = &SysJobLogController{
|
||||
sysJobLogService: service.NewSysJobLogImpl,
|
||||
sysDictDataService: systemService.NewSysDictDataImpl,
|
||||
sysJobLogService: service.NewSysJobLog,
|
||||
sysDictDataService: systemService.NewSysDictData,
|
||||
}
|
||||
|
||||
// 调度任务日志信息
|
||||
//
|
||||
// PATH /monitor/jobLog
|
||||
type SysJobLogController struct {
|
||||
// 调度任务日志服务
|
||||
sysJobLogService service.ISysJobLog
|
||||
// 字典数据服务
|
||||
sysDictDataService systemService.ISysDictData
|
||||
sysJobLogService *service.SysJobLog // 调度任务日志服务
|
||||
sysDictDataService *systemService.SysDictData // 字典数据服务
|
||||
}
|
||||
|
||||
// 调度任务日志列表
|
||||
@@ -44,7 +42,7 @@ func (s *SysJobLogController) List(c *gin.Context) {
|
||||
querys := ctx.QueryMap(c)
|
||||
// 任务ID优先级更高
|
||||
if v, ok := querys["jobId"]; ok && v != nil {
|
||||
jobInfo := service.NewSysJobImpl.SelectJobById(v.(string))
|
||||
jobInfo := service.NewSysJob.SelectJobById(v.(string))
|
||||
querys["jobName"] = jobInfo.JobName
|
||||
querys["jobGroup"] = jobInfo.JobGroup
|
||||
}
|
||||
|
||||
@@ -19,15 +19,14 @@ import (
|
||||
|
||||
// 实例化控制层 SysUserOnlineController 结构体
|
||||
var NewSysUserOnline = &SysUserOnlineController{
|
||||
sysUserOnlineService: service.NewSysUserOnlineImpl,
|
||||
sysUserOnlineService: service.NewSysUserOnline,
|
||||
}
|
||||
|
||||
// 在线用户监控
|
||||
//
|
||||
// PATH /monitor/online
|
||||
type SysUserOnlineController struct {
|
||||
// 在线用户服务
|
||||
sysUserOnlineService service.ISysUserOnline
|
||||
sysUserOnlineService *service.SysUserOnline // 在线用户服务
|
||||
}
|
||||
|
||||
// 在线用户列表
|
||||
|
||||
@@ -9,15 +9,14 @@ import (
|
||||
|
||||
// 实例化控制层 SystemInfoController 结构体
|
||||
var NewSystemInfo = &SystemInfoController{
|
||||
systemInfogService: service.NewSystemInfoImpl,
|
||||
systemInfogService: service.NewSystemInfo,
|
||||
}
|
||||
|
||||
// 服务器监控信息
|
||||
//
|
||||
// PATH /monitor/system-info
|
||||
type SystemInfoController struct {
|
||||
// 服务器系统相关信息服务
|
||||
systemInfogService service.ISystemInfo
|
||||
systemInfogService *service.SystemInfo // 服务器系统相关信息服务
|
||||
}
|
||||
|
||||
// 服务器信息
|
||||
|
||||
@@ -165,5 +165,5 @@ func InitLoad() {
|
||||
// 初始化定时任务处理
|
||||
processor.InitCronQueue()
|
||||
// 启动时,初始化调度任务
|
||||
service.NewSysJobImpl.ResetQueueJob()
|
||||
service.NewSysJob.ResetQueueJob()
|
||||
}
|
||||
|
||||
@@ -1,14 +1,274 @@
|
||||
package service
|
||||
|
||||
// IMonitor 服务器系统相关信息 服务层接口
|
||||
type IMonitor interface {
|
||||
// RunMonitor 执行资源监控
|
||||
RunMonitor()
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
// RunMonitorDataCancel 启动资源监控数据存储io/network通道 移除之前的chan上下文后在设置新的均值
|
||||
// interval 采集的平均值(分钟)
|
||||
RunMonitorDataCancel(removeBefore bool, interval float64)
|
||||
"be.ems/src/framework/logger"
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/shirou/gopsutil/v4/load"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
)
|
||||
|
||||
// SelectMonitorInfo 查询监控资源信息
|
||||
SelectMonitorInfo(query map[string]any) map[string]any
|
||||
// 实例化服务层 Monitor 结构体
|
||||
var NewMonitor = &Monitor{
|
||||
sysConfigService: systemService.NewSysConfigImpl,
|
||||
monitorRepository: repository.NewMonitorImpl,
|
||||
diskIO: make(chan []disk.IOCountersStat, 2),
|
||||
netIO: make(chan []net.IOCountersStat, 2),
|
||||
}
|
||||
|
||||
// Monitor 服务器系统相关信息 服务层处理
|
||||
type Monitor struct {
|
||||
// 参数配置服务
|
||||
sysConfigService systemService.ISysConfig
|
||||
// 监控服务资源数据信息
|
||||
monitorRepository repository.IMonitor
|
||||
// 磁盘网络IO 数据通道
|
||||
diskIO chan ([]disk.IOCountersStat)
|
||||
netIO chan ([]net.IOCountersStat)
|
||||
}
|
||||
|
||||
// RunMonitor 执行资源监控
|
||||
func (s *Monitor) RunMonitor() {
|
||||
var itemBase model.MonitorBase
|
||||
itemBase.CreateTime = time.Now().UnixMilli()
|
||||
itemBase.NeType = "#"
|
||||
itemBase.NeID = "#"
|
||||
loadInfo, _ := load.Avg()
|
||||
itemBase.CPULoad1 = loadInfo.Load1
|
||||
itemBase.CPULoad5 = loadInfo.Load5
|
||||
itemBase.CPULoad15 = loadInfo.Load15
|
||||
totalPercent, _ := cpu.Percent(3*time.Second, false)
|
||||
if len(totalPercent) > 0 {
|
||||
itemBase.CPU = totalPercent[0]
|
||||
}
|
||||
cpuCount, _ := cpu.Counts(false)
|
||||
cpuAvg := (float64(cpuCount*2) * 0.75) * 100
|
||||
itemBase.LoadUsage = 0
|
||||
if cpuAvg > 0 {
|
||||
itemBase.LoadUsage = loadInfo.Load1 / cpuAvg
|
||||
}
|
||||
|
||||
memoryInfo, _ := mem.VirtualMemory()
|
||||
itemBase.Memory = memoryInfo.UsedPercent
|
||||
|
||||
if err := s.monitorRepository.CreateMonitorBase(itemBase); err != nil {
|
||||
logger.Errorf("CreateMonitorBase err: %v", err)
|
||||
}
|
||||
|
||||
// 将当前资源发送到chan中处理保存
|
||||
s.loadDiskIO()
|
||||
s.loadNetIO()
|
||||
|
||||
// 监控系统资源-保留天数
|
||||
storeDays := s.sysConfigService.SelectConfigValueByKey("monitor.sysResource.storeDays")
|
||||
if storeDays != "" {
|
||||
storeDays, _ := strconv.Atoi(storeDays)
|
||||
ltTime := time.Now().AddDate(0, 0, -storeDays).UnixMilli()
|
||||
_ = s.monitorRepository.DelMonitorBase(ltTime)
|
||||
_ = s.monitorRepository.DelMonitorIO(ltTime)
|
||||
_ = s.monitorRepository.DelMonitorNet(ltTime)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Monitor) loadDiskIO() {
|
||||
ioStat, _ := disk.IOCounters()
|
||||
var diskIOList []disk.IOCountersStat
|
||||
for _, io := range ioStat {
|
||||
diskIOList = append(diskIOList, io)
|
||||
}
|
||||
s.diskIO <- diskIOList
|
||||
}
|
||||
|
||||
func (s *Monitor) loadNetIO() {
|
||||
netStat, _ := net.IOCounters(true)
|
||||
netStatAll, _ := net.IOCounters(false)
|
||||
var netList []net.IOCountersStat
|
||||
netList = append(netList, netStat...)
|
||||
netList = append(netList, netStatAll...)
|
||||
s.netIO <- netList
|
||||
}
|
||||
|
||||
// monitorCancel 监控搜集IO/Network上下文
|
||||
var monitorCancel context.CancelFunc
|
||||
|
||||
// RunMonitorDataCancel 启动资源监控数据存储io/network通道 移除之前的chan上下文后在设置新的均值
|
||||
// interval 采集的平均值(分钟)
|
||||
func (s *Monitor) RunMonitorDataCancel(removeBefore bool, interval float64) {
|
||||
// 是否取消之前的
|
||||
if removeBefore {
|
||||
monitorCancel()
|
||||
}
|
||||
|
||||
// 上下文控制
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
monitorCancel = cancel
|
||||
|
||||
// chanl 通道进行存储数据
|
||||
go s.saveIODataToDB(ctx, interval)
|
||||
go s.saveNetDataToDB(ctx, interval)
|
||||
}
|
||||
|
||||
func (s *Monitor) saveIODataToDB(ctx context.Context, interval float64) {
|
||||
defer close(s.diskIO)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ioStat := <-s.diskIO:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ioStat2 := <-s.diskIO:
|
||||
var ioList []model.MonitorIO
|
||||
timeMilli := time.Now().UnixMilli()
|
||||
for _, io2 := range ioStat2 {
|
||||
for _, io1 := range ioStat {
|
||||
if io2.Name == io1.Name {
|
||||
var itemIO model.MonitorIO
|
||||
itemIO.CreateTime = timeMilli
|
||||
itemIO.NeType = "#"
|
||||
itemIO.NeID = "#"
|
||||
itemIO.Name = io1.Name
|
||||
|
||||
if io2.ReadBytes != 0 && io1.ReadBytes != 0 && io2.ReadBytes > io1.ReadBytes {
|
||||
itemIO.Read = int64(float64(io2.ReadBytes-io1.ReadBytes) / interval / 60)
|
||||
}
|
||||
if io2.WriteBytes != 0 && io1.WriteBytes != 0 && io2.WriteBytes > io1.WriteBytes {
|
||||
itemIO.Write = int64(float64(io2.WriteBytes-io1.WriteBytes) / interval / 60)
|
||||
}
|
||||
|
||||
if io2.ReadCount != 0 && io1.ReadCount != 0 && io2.ReadCount > io1.ReadCount {
|
||||
itemIO.Count = int64(float64(io2.ReadCount-io1.ReadCount) / interval / 60)
|
||||
}
|
||||
writeCount := int64(0)
|
||||
if io2.WriteCount != 0 && io1.WriteCount != 0 && io2.WriteCount > io1.WriteCount {
|
||||
writeCount = int64(float64(io2.WriteCount-io1.WriteCount) / interval * 60)
|
||||
}
|
||||
if writeCount > itemIO.Count {
|
||||
itemIO.Count = writeCount
|
||||
}
|
||||
|
||||
if io2.ReadTime != 0 && io1.ReadTime != 0 && io2.ReadTime > io1.ReadTime {
|
||||
itemIO.Time = int64(float64(io2.ReadTime-io1.ReadTime) / interval / 60)
|
||||
}
|
||||
writeTime := int64(0)
|
||||
if io2.WriteTime != 0 && io1.WriteTime != 0 && io2.WriteTime > io1.WriteTime {
|
||||
writeTime = int64(float64(io2.WriteTime-io1.WriteTime) / interval / 60)
|
||||
}
|
||||
if writeTime > itemIO.Time {
|
||||
itemIO.Time = writeTime
|
||||
}
|
||||
ioList = append(ioList, itemIO)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.monitorRepository.BatchCreateMonitorIO(ioList); err != nil {
|
||||
logger.Errorf("BatchCreateMonitorIO err: %v", err)
|
||||
}
|
||||
s.diskIO <- ioStat2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Monitor) saveNetDataToDB(ctx context.Context, interval float64) {
|
||||
defer close(s.netIO)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case netStat := <-s.netIO:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case netStat2 := <-s.netIO:
|
||||
var netList []model.MonitorNetwork
|
||||
timeMilli := time.Now().UnixMilli()
|
||||
for _, net2 := range netStat2 {
|
||||
for _, net1 := range netStat {
|
||||
if net2.Name == net1.Name {
|
||||
var itemNet model.MonitorNetwork
|
||||
itemNet.CreateTime = timeMilli
|
||||
itemNet.NeType = "#"
|
||||
itemNet.NeID = "#"
|
||||
itemNet.Name = net1.Name
|
||||
|
||||
if net2.BytesSent != 0 && net1.BytesSent != 0 && net2.BytesSent > net1.BytesSent {
|
||||
itemNet.Up = float64(net2.BytesSent-net1.BytesSent) / 1024 / interval / 60
|
||||
}
|
||||
if net2.BytesRecv != 0 && net1.BytesRecv != 0 && net2.BytesRecv > net1.BytesRecv {
|
||||
itemNet.Down = float64(net2.BytesRecv-net1.BytesRecv) / 1024 / interval / 60
|
||||
}
|
||||
netList = append(netList, itemNet)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.monitorRepository.BatchCreateMonitorNet(netList); err != nil {
|
||||
logger.Errorf("BatchCreateMonitorNet err: %v", err)
|
||||
}
|
||||
s.netIO <- netStat2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SelectMonitorInfo 查询监控资源信息
|
||||
func (s *Monitor) SelectMonitorInfo(query map[string]any) map[string]any {
|
||||
infoType := query["type"]
|
||||
startTimeMilli := query["startTime"]
|
||||
endTimeMilli := query["endTime"]
|
||||
neType := query["neType"]
|
||||
neId := query["neId"]
|
||||
name := query["name"]
|
||||
|
||||
// 返回数据
|
||||
backDatas := map[string]any{}
|
||||
|
||||
// 基本信息
|
||||
if infoType == "all" || infoType == "load" || infoType == "cpu" || infoType == "memory" {
|
||||
rows := s.monitorRepository.SelectMonitorBase(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
})
|
||||
backDatas["base"] = rows
|
||||
}
|
||||
|
||||
// 磁盘IO
|
||||
if infoType == "all" || infoType == "io" {
|
||||
rows := s.monitorRepository.SelectMonitorIO(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
"name": name,
|
||||
})
|
||||
backDatas["io"] = rows
|
||||
}
|
||||
|
||||
// 网络
|
||||
if infoType == "all" || infoType == "network" {
|
||||
rows := s.monitorRepository.SelectMonitorNetwork(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
"name": name,
|
||||
})
|
||||
backDatas["network"] = rows
|
||||
}
|
||||
|
||||
return backDatas
|
||||
}
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/logger"
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/shirou/gopsutil/v4/load"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
)
|
||||
|
||||
// 实例化服务层 MonitorImpl 结构体
|
||||
var NewMonitorImpl = &MonitorImpl{
|
||||
sysConfigService: systemService.NewSysConfigImpl,
|
||||
monitorRepository: repository.NewMonitorImpl,
|
||||
diskIO: make(chan []disk.IOCountersStat, 2),
|
||||
netIO: make(chan []net.IOCountersStat, 2),
|
||||
}
|
||||
|
||||
// MonitorImpl 服务器系统相关信息 服务层处理
|
||||
type MonitorImpl struct {
|
||||
// 参数配置服务
|
||||
sysConfigService systemService.ISysConfig
|
||||
// 监控服务资源数据信息
|
||||
monitorRepository repository.IMonitor
|
||||
// 磁盘网络IO 数据通道
|
||||
diskIO chan ([]disk.IOCountersStat)
|
||||
netIO chan ([]net.IOCountersStat)
|
||||
}
|
||||
|
||||
// RunMonitor 执行资源监控
|
||||
func (s *MonitorImpl) RunMonitor() {
|
||||
var itemBase model.MonitorBase
|
||||
itemBase.CreateTime = time.Now().UnixMilli()
|
||||
itemBase.NeType = "#"
|
||||
itemBase.NeID = "#"
|
||||
loadInfo, _ := load.Avg()
|
||||
itemBase.CPULoad1 = loadInfo.Load1
|
||||
itemBase.CPULoad5 = loadInfo.Load5
|
||||
itemBase.CPULoad15 = loadInfo.Load15
|
||||
totalPercent, _ := cpu.Percent(3*time.Second, false)
|
||||
if len(totalPercent) == 1 {
|
||||
itemBase.CPU = totalPercent[0]
|
||||
}
|
||||
cpuCount, _ := cpu.Counts(false)
|
||||
cpuAvg := (float64(cpuCount*2) * 0.75) * 100
|
||||
itemBase.LoadUsage = 0
|
||||
if cpuAvg > 0 {
|
||||
itemBase.LoadUsage = loadInfo.Load1 / cpuAvg
|
||||
}
|
||||
|
||||
memoryInfo, _ := mem.VirtualMemory()
|
||||
itemBase.Memory = memoryInfo.UsedPercent
|
||||
|
||||
if err := s.monitorRepository.CreateMonitorBase(itemBase); err != nil {
|
||||
logger.Errorf("CreateMonitorBase err: %v", err)
|
||||
}
|
||||
|
||||
// 将当前资源发送到chan中处理保存
|
||||
s.loadDiskIO()
|
||||
s.loadNetIO()
|
||||
|
||||
// 监控系统资源-保留天数
|
||||
storeDays := s.sysConfigService.SelectConfigValueByKey("monitor.sysResource.storeDays")
|
||||
if storeDays != "" {
|
||||
storeDays, _ := strconv.Atoi(storeDays)
|
||||
ltTime := time.Now().AddDate(0, 0, -storeDays).UnixMilli()
|
||||
_ = s.monitorRepository.DelMonitorBase(ltTime)
|
||||
_ = s.monitorRepository.DelMonitorIO(ltTime)
|
||||
_ = s.monitorRepository.DelMonitorNet(ltTime)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MonitorImpl) loadDiskIO() {
|
||||
ioStat, _ := disk.IOCounters()
|
||||
var diskIOList []disk.IOCountersStat
|
||||
for _, io := range ioStat {
|
||||
diskIOList = append(diskIOList, io)
|
||||
}
|
||||
s.diskIO <- diskIOList
|
||||
}
|
||||
|
||||
func (s *MonitorImpl) loadNetIO() {
|
||||
netStat, _ := net.IOCounters(true)
|
||||
netStatAll, _ := net.IOCounters(false)
|
||||
var netList []net.IOCountersStat
|
||||
netList = append(netList, netStat...)
|
||||
netList = append(netList, netStatAll...)
|
||||
s.netIO <- netList
|
||||
}
|
||||
|
||||
// monitorCancel 监控搜集IO/Network上下文
|
||||
var monitorCancel context.CancelFunc
|
||||
|
||||
// RunMonitorDataCancel 启动资源监控数据存储io/network通道 移除之前的chan上下文后在设置新的均值
|
||||
// interval 采集的平均值(分钟)
|
||||
func (s *MonitorImpl) RunMonitorDataCancel(removeBefore bool, interval float64) {
|
||||
// 是否取消之前的
|
||||
if removeBefore {
|
||||
monitorCancel()
|
||||
}
|
||||
|
||||
// 上下文控制
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
monitorCancel = cancel
|
||||
|
||||
// chanl 通道进行存储数据
|
||||
go s.saveIODataToDB(ctx, interval)
|
||||
go s.saveNetDataToDB(ctx, interval)
|
||||
}
|
||||
|
||||
func (s *MonitorImpl) saveIODataToDB(ctx context.Context, interval float64) {
|
||||
defer close(s.diskIO)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ioStat := <-s.diskIO:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ioStat2 := <-s.diskIO:
|
||||
var ioList []model.MonitorIO
|
||||
timeMilli := time.Now().UnixMilli()
|
||||
for _, io2 := range ioStat2 {
|
||||
for _, io1 := range ioStat {
|
||||
if io2.Name == io1.Name {
|
||||
var itemIO model.MonitorIO
|
||||
itemIO.CreateTime = timeMilli
|
||||
itemIO.NeType = "#"
|
||||
itemIO.NeID = "#"
|
||||
itemIO.Name = io1.Name
|
||||
|
||||
if io2.ReadBytes != 0 && io1.ReadBytes != 0 && io2.ReadBytes > io1.ReadBytes {
|
||||
itemIO.Read = int64(float64(io2.ReadBytes-io1.ReadBytes) / interval / 60)
|
||||
}
|
||||
if io2.WriteBytes != 0 && io1.WriteBytes != 0 && io2.WriteBytes > io1.WriteBytes {
|
||||
itemIO.Write = int64(float64(io2.WriteBytes-io1.WriteBytes) / interval / 60)
|
||||
}
|
||||
|
||||
if io2.ReadCount != 0 && io1.ReadCount != 0 && io2.ReadCount > io1.ReadCount {
|
||||
itemIO.Count = int64(float64(io2.ReadCount-io1.ReadCount) / interval / 60)
|
||||
}
|
||||
writeCount := int64(0)
|
||||
if io2.WriteCount != 0 && io1.WriteCount != 0 && io2.WriteCount > io1.WriteCount {
|
||||
writeCount = int64(float64(io2.WriteCount-io1.WriteCount) / interval * 60)
|
||||
}
|
||||
if writeCount > itemIO.Count {
|
||||
itemIO.Count = writeCount
|
||||
}
|
||||
|
||||
if io2.ReadTime != 0 && io1.ReadTime != 0 && io2.ReadTime > io1.ReadTime {
|
||||
itemIO.Time = int64(float64(io2.ReadTime-io1.ReadTime) / interval / 60)
|
||||
}
|
||||
writeTime := int64(0)
|
||||
if io2.WriteTime != 0 && io1.WriteTime != 0 && io2.WriteTime > io1.WriteTime {
|
||||
writeTime = int64(float64(io2.WriteTime-io1.WriteTime) / interval / 60)
|
||||
}
|
||||
if writeTime > itemIO.Time {
|
||||
itemIO.Time = writeTime
|
||||
}
|
||||
ioList = append(ioList, itemIO)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.monitorRepository.BatchCreateMonitorIO(ioList); err != nil {
|
||||
logger.Errorf("BatchCreateMonitorIO err: %v", err)
|
||||
}
|
||||
s.diskIO <- ioStat2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MonitorImpl) saveNetDataToDB(ctx context.Context, interval float64) {
|
||||
defer close(s.netIO)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case netStat := <-s.netIO:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case netStat2 := <-s.netIO:
|
||||
var netList []model.MonitorNetwork
|
||||
timeMilli := time.Now().UnixMilli()
|
||||
for _, net2 := range netStat2 {
|
||||
for _, net1 := range netStat {
|
||||
if net2.Name == net1.Name {
|
||||
var itemNet model.MonitorNetwork
|
||||
itemNet.CreateTime = timeMilli
|
||||
itemNet.NeType = "#"
|
||||
itemNet.NeID = "#"
|
||||
itemNet.Name = net1.Name
|
||||
|
||||
if net2.BytesSent != 0 && net1.BytesSent != 0 && net2.BytesSent > net1.BytesSent {
|
||||
itemNet.Up = float64(net2.BytesSent-net1.BytesSent) / 1024 / interval / 60
|
||||
}
|
||||
if net2.BytesRecv != 0 && net1.BytesRecv != 0 && net2.BytesRecv > net1.BytesRecv {
|
||||
itemNet.Down = float64(net2.BytesRecv-net1.BytesRecv) / 1024 / interval / 60
|
||||
}
|
||||
netList = append(netList, itemNet)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.monitorRepository.BatchCreateMonitorNet(netList); err != nil {
|
||||
logger.Errorf("BatchCreateMonitorNet err: %v", err)
|
||||
}
|
||||
s.netIO <- netStat2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SelectMonitorInfo 查询监控资源信息
|
||||
func (s *MonitorImpl) SelectMonitorInfo(query map[string]any) map[string]any {
|
||||
infoType := query["type"]
|
||||
startTimeMilli := query["startTime"]
|
||||
endTimeMilli := query["endTime"]
|
||||
neType := query["neType"]
|
||||
neId := query["neId"]
|
||||
name := query["name"]
|
||||
|
||||
// 返回数据
|
||||
backDatas := map[string]any{}
|
||||
|
||||
// 基本信息
|
||||
if infoType == "all" || infoType == "load" || infoType == "cpu" || infoType == "memory" {
|
||||
rows := s.monitorRepository.SelectMonitorBase(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
})
|
||||
backDatas["base"] = rows
|
||||
}
|
||||
|
||||
// 磁盘IO
|
||||
if infoType == "all" || infoType == "io" {
|
||||
rows := s.monitorRepository.SelectMonitorIO(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
"name": name,
|
||||
})
|
||||
backDatas["io"] = rows
|
||||
}
|
||||
|
||||
// 网络
|
||||
if infoType == "all" || infoType == "network" {
|
||||
rows := s.monitorRepository.SelectMonitorNetwork(map[string]any{
|
||||
"startTime": startTimeMilli,
|
||||
"endTime": endTimeMilli,
|
||||
"neType": neType,
|
||||
"neId": neId,
|
||||
"name": name,
|
||||
})
|
||||
backDatas["network"] = rows
|
||||
}
|
||||
|
||||
return backDatas
|
||||
}
|
||||
@@ -12,10 +12,6 @@ import (
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
||||
}
|
||||
|
||||
func TestInfo(t *testing.T) {
|
||||
s := MonitorInfo{}
|
||||
s.load(0.5) // 0.5 半分钟
|
||||
@@ -36,17 +32,21 @@ func (m *MonitorInfo) load(interval float64) {
|
||||
var itemBase MonitorBase
|
||||
itemBase.CreateTime = time.Now().UnixMilli()
|
||||
|
||||
totalPercent, _ := cpu.Percent(3*time.Second, false)
|
||||
if len(totalPercent) == 1 {
|
||||
itemBase.CPU = totalPercent[0]
|
||||
}
|
||||
cpuCount, _ := cpu.Counts(false)
|
||||
|
||||
loadInfo, _ := load.Avg()
|
||||
itemBase.CPULoad1 = loadInfo.Load1
|
||||
itemBase.CPULoad5 = loadInfo.Load5
|
||||
itemBase.CPULoad15 = loadInfo.Load15
|
||||
itemBase.LoadUsage = loadInfo.Load1 / (float64(cpuCount*2) * 0.75) * 100
|
||||
|
||||
totalPercent, _ := cpu.Percent(3*time.Second, false)
|
||||
if len(totalPercent) > 0 {
|
||||
itemBase.CPU = totalPercent[0]
|
||||
}
|
||||
cpuCount, _ := cpu.Counts(false)
|
||||
cpuAvg := (float64(cpuCount*2) * 0.75) * 100
|
||||
itemBase.LoadUsage = 0
|
||||
if cpuAvg > 0 {
|
||||
itemBase.LoadUsage = loadInfo.Load1 / cpuAvg
|
||||
}
|
||||
|
||||
memoryInfo, _ := mem.VirtualMemory()
|
||||
itemBase.Memory = memoryInfo.UsedPercent
|
||||
|
||||
@@ -1,35 +1,169 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/constants/common"
|
||||
"be.ems/src/framework/cron"
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
)
|
||||
|
||||
// ISysJob 调度任务信息 服务层接口
|
||||
type ISysJob interface {
|
||||
// SelectJobPage 分页查询调度任务集合
|
||||
SelectJobPage(query map[string]any) map[string]any
|
||||
|
||||
// SelectJobList 查询调度任务集合
|
||||
SelectJobList(sysJob model.SysJob) []model.SysJob
|
||||
|
||||
// SelectJobById 通过调度ID查询调度任务信息
|
||||
SelectJobById(jobId string) model.SysJob
|
||||
|
||||
// CheckUniqueJobName 校验调度任务名称和组是否唯一
|
||||
CheckUniqueJobName(jobName, jobGroup, jobId string) bool
|
||||
|
||||
// InsertJob 新增调度任务信息
|
||||
InsertJob(sysJob model.SysJob) string
|
||||
|
||||
// UpdateJob 修改调度任务信息
|
||||
UpdateJob(sysJob model.SysJob) int64
|
||||
|
||||
// DeleteJobByIds 批量删除调度任务信息
|
||||
DeleteJobByIds(jobIds []string) (int64, error)
|
||||
|
||||
// RunQueueJob 立即运行一次调度任务
|
||||
RunQueueJob(sysJob model.SysJob) bool
|
||||
|
||||
// ResetQueueJob 重置初始调度任务
|
||||
ResetQueueJob()
|
||||
// 实例化服务层 SysJob 结构体
|
||||
var NewSysJob = &SysJob{
|
||||
sysJobRepository: repository.NewSysJobImpl,
|
||||
}
|
||||
|
||||
// SysJob 调度任务 服务层处理
|
||||
type SysJob struct {
|
||||
// 调度任务数据信息
|
||||
sysJobRepository repository.ISysJob
|
||||
}
|
||||
|
||||
// SelectJobPage 分页查询调度任务集合
|
||||
func (r *SysJob) SelectJobPage(query map[string]any) map[string]any {
|
||||
return r.sysJobRepository.SelectJobPage(query)
|
||||
}
|
||||
|
||||
// SelectJobList 查询调度任务集合
|
||||
func (r *SysJob) SelectJobList(sysJob model.SysJob) []model.SysJob {
|
||||
return r.sysJobRepository.SelectJobList(sysJob)
|
||||
}
|
||||
|
||||
// SelectJobById 通过调度ID查询调度任务信息
|
||||
func (r *SysJob) SelectJobById(jobId string) model.SysJob {
|
||||
if jobId == "" {
|
||||
return model.SysJob{}
|
||||
}
|
||||
jobs := r.sysJobRepository.SelectJobByIds([]string{jobId})
|
||||
if len(jobs) > 0 {
|
||||
return jobs[0]
|
||||
}
|
||||
return model.SysJob{}
|
||||
}
|
||||
|
||||
// CheckUniqueJobName 校验调度任务名称和组是否唯一
|
||||
func (r *SysJob) CheckUniqueJobName(jobName, jobGroup, jobId string) bool {
|
||||
uniqueId := r.sysJobRepository.CheckUniqueJob(model.SysJob{
|
||||
JobName: jobName,
|
||||
JobGroup: jobGroup,
|
||||
})
|
||||
if uniqueId == jobId {
|
||||
return true
|
||||
}
|
||||
return uniqueId == ""
|
||||
}
|
||||
|
||||
// InsertJob 新增调度任务信息
|
||||
func (r *SysJob) InsertJob(sysJob model.SysJob) string {
|
||||
insertId := r.sysJobRepository.InsertJob(sysJob)
|
||||
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 添加调度任务
|
||||
func (r *SysJob) insertQueueJob(sysJob model.SysJob, repeat bool) bool {
|
||||
// 获取队列 Processor
|
||||
queue := cron.GetQueue(sysJob.InvokeTarget)
|
||||
if queue.Name != sysJob.InvokeTarget {
|
||||
return false
|
||||
}
|
||||
|
||||
// 给执行任务数据参数
|
||||
options := cron.JobData{
|
||||
Repeat: repeat,
|
||||
SysJob: sysJob,
|
||||
}
|
||||
|
||||
// 不是重复任务的情况,立即执行一次
|
||||
if !repeat {
|
||||
// 执行单次任务
|
||||
status := queue.RunJob(options, cron.JobOptions{
|
||||
JobId: sysJob.JobID,
|
||||
})
|
||||
// 执行中或等待中的都返回正常
|
||||
return status == cron.Active || status == cron.Waiting
|
||||
}
|
||||
|
||||
// 执行重复任务
|
||||
queue.RunJob(options, cron.JobOptions{
|
||||
JobId: sysJob.JobID,
|
||||
Cron: sysJob.CronExpression,
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// deleteQueueJob 删除调度任务
|
||||
func (r *SysJob) deleteQueueJob(sysJob model.SysJob) bool {
|
||||
// 获取队列 Processor
|
||||
queue := cron.GetQueue(sysJob.InvokeTarget)
|
||||
if queue.Name != sysJob.InvokeTarget {
|
||||
return false
|
||||
}
|
||||
return queue.RemoveJob(sysJob.JobID)
|
||||
}
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/constants/common"
|
||||
"be.ems/src/framework/cron"
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
)
|
||||
|
||||
// 实例化服务层 SysJobImpl 结构体
|
||||
var NewSysJobImpl = &SysJobImpl{
|
||||
sysJobRepository: repository.NewSysJobImpl,
|
||||
}
|
||||
|
||||
// SysJobImpl 调度任务 服务层处理
|
||||
type SysJobImpl struct {
|
||||
// 调度任务数据信息
|
||||
sysJobRepository repository.ISysJob
|
||||
}
|
||||
|
||||
// SelectJobPage 分页查询调度任务集合
|
||||
func (r *SysJobImpl) SelectJobPage(query map[string]any) map[string]any {
|
||||
return r.sysJobRepository.SelectJobPage(query)
|
||||
}
|
||||
|
||||
// SelectJobList 查询调度任务集合
|
||||
func (r *SysJobImpl) SelectJobList(sysJob model.SysJob) []model.SysJob {
|
||||
return r.sysJobRepository.SelectJobList(sysJob)
|
||||
}
|
||||
|
||||
// SelectJobById 通过调度ID查询调度任务信息
|
||||
func (r *SysJobImpl) SelectJobById(jobId string) model.SysJob {
|
||||
if jobId == "" {
|
||||
return model.SysJob{}
|
||||
}
|
||||
jobs := r.sysJobRepository.SelectJobByIds([]string{jobId})
|
||||
if len(jobs) > 0 {
|
||||
return jobs[0]
|
||||
}
|
||||
return model.SysJob{}
|
||||
}
|
||||
|
||||
// CheckUniqueJobName 校验调度任务名称和组是否唯一
|
||||
func (r *SysJobImpl) CheckUniqueJobName(jobName, jobGroup, jobId string) bool {
|
||||
uniqueId := r.sysJobRepository.CheckUniqueJob(model.SysJob{
|
||||
JobName: jobName,
|
||||
JobGroup: jobGroup,
|
||||
})
|
||||
if uniqueId == jobId {
|
||||
return true
|
||||
}
|
||||
return uniqueId == ""
|
||||
}
|
||||
|
||||
// InsertJob 新增调度任务信息
|
||||
func (r *SysJobImpl) InsertJob(sysJob model.SysJob) string {
|
||||
insertId := r.sysJobRepository.InsertJob(sysJob)
|
||||
if insertId == "" && sysJob.Status == common.STATUS_YES {
|
||||
sysJob.JobID = insertId
|
||||
r.insertQueueJob(sysJob, true)
|
||||
}
|
||||
return insertId
|
||||
}
|
||||
|
||||
// UpdateJob 修改调度任务信息
|
||||
func (r *SysJobImpl) 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 *SysJobImpl) 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 *SysJobImpl) 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 *SysJobImpl) RunQueueJob(sysJob model.SysJob) bool {
|
||||
return r.insertQueueJob(sysJob, false)
|
||||
}
|
||||
|
||||
// insertQueueJob 添加调度任务
|
||||
func (r *SysJobImpl) insertQueueJob(sysJob model.SysJob, repeat bool) bool {
|
||||
// 获取队列 Processor
|
||||
queue := cron.GetQueue(sysJob.InvokeTarget)
|
||||
if queue.Name != sysJob.InvokeTarget {
|
||||
return false
|
||||
}
|
||||
|
||||
// 给执行任务数据参数
|
||||
options := cron.JobData{
|
||||
Repeat: repeat,
|
||||
SysJob: sysJob,
|
||||
}
|
||||
|
||||
// 不是重复任务的情况,立即执行一次
|
||||
if !repeat {
|
||||
// 执行单次任务
|
||||
status := queue.RunJob(options, cron.JobOptions{
|
||||
JobId: sysJob.JobID,
|
||||
})
|
||||
// 执行中或等待中的都返回正常
|
||||
return status == cron.Active || status == cron.Waiting
|
||||
}
|
||||
|
||||
// 执行重复任务
|
||||
queue.RunJob(options, cron.JobOptions{
|
||||
JobId: sysJob.JobID,
|
||||
Cron: sysJob.CronExpression,
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// deleteQueueJob 删除调度任务
|
||||
func (r *SysJobImpl) deleteQueueJob(sysJob model.SysJob) bool {
|
||||
// 获取队列 Processor
|
||||
queue := cron.GetQueue(sysJob.InvokeTarget)
|
||||
if queue.Name != sysJob.InvokeTarget {
|
||||
return false
|
||||
}
|
||||
return queue.RemoveJob(sysJob.JobID)
|
||||
}
|
||||
@@ -2,22 +2,41 @@ package service
|
||||
|
||||
import (
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
)
|
||||
|
||||
// ISysJobLog 调度任务日志 服务层接口
|
||||
type ISysJobLog interface {
|
||||
// SelectJobLogPage 分页查询调度任务日志集合
|
||||
SelectJobLogPage(query map[string]any) map[string]any
|
||||
|
||||
// SelectJobLogList 查询调度任务日志集合
|
||||
SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog
|
||||
|
||||
// SelectJobLogById 通过调度ID查询调度任务日志信息
|
||||
SelectJobLogById(jobLogId string) model.SysJobLog
|
||||
|
||||
// DeleteJobLogByIds 批量删除调度任务日志信息
|
||||
DeleteJobLogByIds(jobLogIds []string) int64
|
||||
|
||||
// CleanJobLog 清空调度任务日志
|
||||
CleanJobLog() error
|
||||
// 实例化服务层 SysJobLog 结构体
|
||||
var NewSysJobLog = &SysJobLog{
|
||||
sysJobLogRepository: repository.NewSysJobLogImpl,
|
||||
}
|
||||
|
||||
// SysJobLog 调度任务日志 服务层处理
|
||||
type SysJobLog struct {
|
||||
// 调度任务日志数据信息
|
||||
sysJobLogRepository repository.ISysJobLog
|
||||
}
|
||||
|
||||
// SelectJobLogPage 分页查询调度任务日志集合
|
||||
func (s *SysJobLog) SelectJobLogPage(query map[string]any) map[string]any {
|
||||
return s.sysJobLogRepository.SelectJobLogPage(query)
|
||||
}
|
||||
|
||||
// SelectJobLogList 查询调度任务日志集合
|
||||
func (s *SysJobLog) SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog {
|
||||
return s.sysJobLogRepository.SelectJobLogList(sysJobLog)
|
||||
}
|
||||
|
||||
// SelectJobLogById 通过调度ID查询调度任务日志信息
|
||||
func (s *SysJobLog) SelectJobLogById(jobLogId string) model.SysJobLog {
|
||||
return s.sysJobLogRepository.SelectJobLogById(jobLogId)
|
||||
}
|
||||
|
||||
// DeleteJobLogByIds 批量删除调度任务日志信息
|
||||
func (s *SysJobLog) DeleteJobLogByIds(jobLogIds []string) int64 {
|
||||
return s.sysJobLogRepository.DeleteJobLogByIds(jobLogIds)
|
||||
}
|
||||
|
||||
// CleanJobLog 清空调度任务日志
|
||||
func (s *SysJobLog) CleanJobLog() error {
|
||||
return s.sysJobLogRepository.CleanJobLog()
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"be.ems/src/modules/monitor/model"
|
||||
"be.ems/src/modules/monitor/repository"
|
||||
)
|
||||
|
||||
// 实例化服务层 SysJobLogImpl 结构体
|
||||
var NewSysJobLogImpl = &SysJobLogImpl{
|
||||
sysJobLogRepository: repository.NewSysJobLogImpl,
|
||||
}
|
||||
|
||||
// SysJobLogImpl 调度任务日志 服务层处理
|
||||
type SysJobLogImpl struct {
|
||||
// 调度任务日志数据信息
|
||||
sysJobLogRepository repository.ISysJobLog
|
||||
}
|
||||
|
||||
// SelectJobLogPage 分页查询调度任务日志集合
|
||||
func (s *SysJobLogImpl) SelectJobLogPage(query map[string]any) map[string]any {
|
||||
return s.sysJobLogRepository.SelectJobLogPage(query)
|
||||
}
|
||||
|
||||
// SelectJobLogList 查询调度任务日志集合
|
||||
func (s *SysJobLogImpl) SelectJobLogList(sysJobLog model.SysJobLog) []model.SysJobLog {
|
||||
return s.sysJobLogRepository.SelectJobLogList(sysJobLog)
|
||||
}
|
||||
|
||||
// SelectJobLogById 通过调度ID查询调度任务日志信息
|
||||
func (s *SysJobLogImpl) SelectJobLogById(jobLogId string) model.SysJobLog {
|
||||
return s.sysJobLogRepository.SelectJobLogById(jobLogId)
|
||||
}
|
||||
|
||||
// DeleteJobLogByIds 批量删除调度任务日志信息
|
||||
func (s *SysJobLogImpl) DeleteJobLogByIds(jobLogIds []string) int64 {
|
||||
return s.sysJobLogRepository.DeleteJobLogByIds(jobLogIds)
|
||||
}
|
||||
|
||||
// CleanJobLog 清空调度任务日志
|
||||
func (s *SysJobLogImpl) CleanJobLog() error {
|
||||
return s.sysJobLogRepository.CleanJobLog()
|
||||
}
|
||||
@@ -5,8 +5,29 @@ import (
|
||||
"be.ems/src/modules/monitor/model"
|
||||
)
|
||||
|
||||
// ISysUserOnline 在线用户 服务层接口
|
||||
type ISysUserOnline interface {
|
||||
// LoginUserToUserOnline 设置在线用户信息
|
||||
LoginUserToUserOnline(loginUser vo.LoginUser) model.SysUserOnline
|
||||
// 实例化服务层 SysUserOnline 结构体
|
||||
var NewSysUserOnline = &SysUserOnline{}
|
||||
|
||||
// SysUserOnline 在线用户 服务层处理
|
||||
type SysUserOnline struct{}
|
||||
|
||||
// LoginUserToUserOnline 设置在线用户信息
|
||||
func (r *SysUserOnline) LoginUserToUserOnline(loginUser vo.LoginUser) model.SysUserOnline {
|
||||
if loginUser.UserID == "" {
|
||||
return model.SysUserOnline{}
|
||||
}
|
||||
|
||||
sysUserOnline := model.SysUserOnline{
|
||||
TokenID: loginUser.UUID,
|
||||
UserName: loginUser.User.UserName,
|
||||
IPAddr: loginUser.IPAddr,
|
||||
LoginLocation: loginUser.LoginLocation,
|
||||
Browser: loginUser.Browser,
|
||||
OS: loginUser.OS,
|
||||
LoginTime: loginUser.LoginTime,
|
||||
}
|
||||
if loginUser.User.DeptID != "" {
|
||||
sysUserOnline.DeptName = loginUser.User.Dept.DeptName
|
||||
}
|
||||
return sysUserOnline
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"be.ems/src/framework/vo"
|
||||
"be.ems/src/modules/monitor/model"
|
||||
)
|
||||
|
||||
// 实例化服务层 SysUserOnlineImpl 结构体
|
||||
var NewSysUserOnlineImpl = &SysUserOnlineImpl{}
|
||||
|
||||
// SysUserOnlineImpl 在线用户 服务层处理
|
||||
type SysUserOnlineImpl struct{}
|
||||
|
||||
// LoginUserToUserOnline 设置在线用户信息
|
||||
func (r *SysUserOnlineImpl) LoginUserToUserOnline(loginUser vo.LoginUser) model.SysUserOnline {
|
||||
if loginUser.UserID == "" {
|
||||
return model.SysUserOnline{}
|
||||
}
|
||||
|
||||
sysUserOnline := model.SysUserOnline{
|
||||
TokenID: loginUser.UUID,
|
||||
UserName: loginUser.User.UserName,
|
||||
IPAddr: loginUser.IPAddr,
|
||||
LoginLocation: loginUser.LoginLocation,
|
||||
Browser: loginUser.Browser,
|
||||
OS: loginUser.OS,
|
||||
LoginTime: loginUser.LoginTime,
|
||||
}
|
||||
if loginUser.User.DeptID != "" {
|
||||
sysUserOnline.DeptName = loginUser.User.Dept.DeptName
|
||||
}
|
||||
return sysUserOnline
|
||||
}
|
||||
@@ -1,22 +1,177 @@
|
||||
package service
|
||||
|
||||
// ISystemInfo 服务器系统相关信息 服务层接口
|
||||
type ISystemInfo interface {
|
||||
// SystemInfo 系统信息
|
||||
SystemInfo() map[string]any
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// TimeInfo 系统时间信息
|
||||
TimeInfo() map[string]string
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
|
||||
// MemoryInfo 内存信息
|
||||
MemoryInfo() map[string]any
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/shirou/gopsutil/v4/host"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
)
|
||||
|
||||
// CPUInfo CPU信息
|
||||
CPUInfo() map[string]any
|
||||
// 实例化服务层 SystemInfo 结构体
|
||||
var NewSystemInfo = &SystemInfo{}
|
||||
|
||||
// NetworkInfo 网络信息
|
||||
NetworkInfo() map[string]string
|
||||
// SystemInfo 服务器系统相关信息 服务层处理
|
||||
type SystemInfo struct{}
|
||||
|
||||
// DiskInfo 磁盘信息
|
||||
DiskInfo() []map[string]string
|
||||
// SystemInfo 系统信息
|
||||
func (s *SystemInfo) SystemInfo() map[string]any {
|
||||
info, err := host.Info()
|
||||
if err != nil {
|
||||
info.Platform = err.Error()
|
||||
}
|
||||
// 获取主机运行时间
|
||||
bootTime := time.Since(time.Unix(int64(info.BootTime), 0)).Seconds()
|
||||
// 获取程序运行时间
|
||||
runTime := time.Since(config.RunTime()).Abs().Seconds()
|
||||
return map[string]any{
|
||||
"platform": info.Platform,
|
||||
"platformVersion": info.PlatformVersion,
|
||||
"arch": info.KernelArch,
|
||||
"archVersion": info.KernelVersion,
|
||||
"os": info.OS,
|
||||
"hostname": info.Hostname,
|
||||
"bootTime": int64(bootTime),
|
||||
"processId": os.Getpid(),
|
||||
"runArch": runtime.GOARCH,
|
||||
"runVersion": runtime.Version(),
|
||||
"runTime": int64(runTime),
|
||||
}
|
||||
}
|
||||
|
||||
// TimeInfo 系统时间信息
|
||||
func (s *SystemInfo) TimeInfo() map[string]string {
|
||||
now := time.Now()
|
||||
// 获取当前时间
|
||||
current := now.Format("2006-01-02 15:04:05")
|
||||
// 获取时区
|
||||
timezone := now.Format("-0700 MST")
|
||||
// 获取时区名称
|
||||
timezoneName := now.Format("MST")
|
||||
|
||||
return map[string]string{
|
||||
"current": current,
|
||||
"timezone": timezone,
|
||||
"timezoneName": timezoneName,
|
||||
}
|
||||
}
|
||||
|
||||
// MemoryInfo 内存信息
|
||||
func (s *SystemInfo) MemoryInfo() map[string]any {
|
||||
memInfo, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
memInfo.UsedPercent = 0
|
||||
memInfo.Available = 0
|
||||
memInfo.Total = 0
|
||||
}
|
||||
|
||||
var memStats runtime.MemStats
|
||||
runtime.ReadMemStats(&memStats)
|
||||
|
||||
return map[string]any{
|
||||
"usage": fmt.Sprintf("%.2f", memInfo.UsedPercent), // 内存利用率
|
||||
"freemem": parse.Bit(float64(memInfo.Available)), // 可用内存大小(GB)
|
||||
"totalmem": parse.Bit(float64(memInfo.Total)), // 总内存大小(GB)
|
||||
"rss": parse.Bit(float64(memStats.Sys)), // 常驻内存大小(RSS)
|
||||
"heapTotal": parse.Bit(float64(memStats.HeapSys)), // 堆总大小
|
||||
"heapUsed": parse.Bit(float64(memStats.HeapAlloc)), // 堆已使用大小
|
||||
"external": parse.Bit(float64(memStats.Sys - memStats.HeapSys)), // 外部内存大小(非堆)
|
||||
}
|
||||
}
|
||||
|
||||
// CPUInfo CPU信息
|
||||
func (s *SystemInfo) CPUInfo() map[string]any {
|
||||
var core int = 0
|
||||
var speed string = "未知"
|
||||
var model string = "未知"
|
||||
cpuInfo, err := cpu.Info()
|
||||
if err == nil {
|
||||
core = runtime.NumCPU()
|
||||
speed = fmt.Sprintf("%.0fMHz", cpuInfo[0].Mhz)
|
||||
model = strings.TrimSpace(cpuInfo[0].ModelName)
|
||||
}
|
||||
|
||||
useds := []string{}
|
||||
cpuPercent, err := cpu.Percent(0, true)
|
||||
if err == nil {
|
||||
for _, v := range cpuPercent {
|
||||
useds = append(useds, fmt.Sprintf("%.2f", v))
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"model": model,
|
||||
"speed": speed,
|
||||
"core": core,
|
||||
"coreUsed": useds,
|
||||
}
|
||||
}
|
||||
|
||||
// NetworkInfo 网络信息
|
||||
func (s *SystemInfo) NetworkInfo() map[string]string {
|
||||
ipAddrs := make(map[string]string)
|
||||
interfaces, err := net.Interfaces()
|
||||
if err == nil {
|
||||
for _, iface := range interfaces {
|
||||
name := iface.Name
|
||||
if name[len(name)-1] == '0' {
|
||||
name = name[0 : len(name)-1]
|
||||
name = strings.Trim(name, "")
|
||||
}
|
||||
// ignore localhost
|
||||
if name == "lo" {
|
||||
continue
|
||||
}
|
||||
var addrs []string
|
||||
for _, v := range iface.Addrs {
|
||||
prefix := strings.Split(v.Addr, "/")[0]
|
||||
if strings.Contains(prefix, "::") {
|
||||
addrs = append(addrs, fmt.Sprintf("IPv6 %s", prefix))
|
||||
}
|
||||
if strings.Contains(prefix, ".") {
|
||||
addrs = append(addrs, fmt.Sprintf("IPv4 %s", prefix))
|
||||
}
|
||||
}
|
||||
ipAddrs[name] = strings.Join(addrs, " / ")
|
||||
}
|
||||
}
|
||||
return ipAddrs
|
||||
}
|
||||
|
||||
// DiskInfo 磁盘信息
|
||||
func (s *SystemInfo) DiskInfo() []map[string]string {
|
||||
disks := make([]map[string]string, 0)
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
partitions, err := disk.PartitionsWithContext(ctx, false)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
return disks
|
||||
}
|
||||
|
||||
for _, partition := range partitions {
|
||||
usage, err := disk.Usage(partition.Mountpoint)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
disks = append(disks, map[string]string{
|
||||
"size": parse.Bit(float64(usage.Total)),
|
||||
"used": parse.Bit(float64(usage.Used)),
|
||||
"avail": parse.Bit(float64(usage.Free)),
|
||||
"pcent": fmt.Sprintf("%.1f%%", usage.UsedPercent),
|
||||
"target": partition.Device,
|
||||
})
|
||||
}
|
||||
return disks
|
||||
}
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/shirou/gopsutil/v4/host"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
)
|
||||
|
||||
// 实例化服务层 SystemInfoImpl 结构体
|
||||
var NewSystemInfoImpl = &SystemInfoImpl{}
|
||||
|
||||
// SystemInfoImpl 服务器系统相关信息 服务层处理
|
||||
type SystemInfoImpl struct{}
|
||||
|
||||
// SystemInfo 系统信息
|
||||
func (s *SystemInfoImpl) SystemInfo() map[string]any {
|
||||
info, err := host.Info()
|
||||
if err != nil {
|
||||
info.Platform = err.Error()
|
||||
}
|
||||
// 获取主机运行时间
|
||||
bootTime := time.Since(time.Unix(int64(info.BootTime), 0)).Seconds()
|
||||
// 获取程序运行时间
|
||||
runTime := time.Since(config.RunTime()).Abs().Seconds()
|
||||
return map[string]any{
|
||||
"platform": info.Platform,
|
||||
"platformVersion": info.PlatformVersion,
|
||||
"arch": info.KernelArch,
|
||||
"archVersion": info.KernelVersion,
|
||||
"os": info.OS,
|
||||
"hostname": info.Hostname,
|
||||
"bootTime": int64(bootTime),
|
||||
"processId": os.Getpid(),
|
||||
"runArch": runtime.GOARCH,
|
||||
"runVersion": runtime.Version(),
|
||||
"runTime": int64(runTime),
|
||||
}
|
||||
}
|
||||
|
||||
// TimeInfo 系统时间信息
|
||||
func (s *SystemInfoImpl) TimeInfo() map[string]string {
|
||||
now := time.Now()
|
||||
// 获取当前时间
|
||||
current := now.Format("2006-01-02 15:04:05")
|
||||
// 获取时区
|
||||
timezone := now.Format("-0700 MST")
|
||||
// 获取时区名称
|
||||
timezoneName := now.Format("MST")
|
||||
|
||||
return map[string]string{
|
||||
"current": current,
|
||||
"timezone": timezone,
|
||||
"timezoneName": timezoneName,
|
||||
}
|
||||
}
|
||||
|
||||
// MemoryInfo 内存信息
|
||||
func (s *SystemInfoImpl) MemoryInfo() map[string]any {
|
||||
memInfo, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
memInfo.UsedPercent = 0
|
||||
memInfo.Available = 0
|
||||
memInfo.Total = 0
|
||||
}
|
||||
|
||||
var memStats runtime.MemStats
|
||||
runtime.ReadMemStats(&memStats)
|
||||
|
||||
return map[string]any{
|
||||
"usage": fmt.Sprintf("%.2f", memInfo.UsedPercent), // 内存利用率
|
||||
"freemem": parse.Bit(float64(memInfo.Available)), // 可用内存大小(GB)
|
||||
"totalmem": parse.Bit(float64(memInfo.Total)), // 总内存大小(GB)
|
||||
"rss": parse.Bit(float64(memStats.Sys)), // 常驻内存大小(RSS)
|
||||
"heapTotal": parse.Bit(float64(memStats.HeapSys)), // 堆总大小
|
||||
"heapUsed": parse.Bit(float64(memStats.HeapAlloc)), // 堆已使用大小
|
||||
"external": parse.Bit(float64(memStats.Sys - memStats.HeapSys)), // 外部内存大小(非堆)
|
||||
}
|
||||
}
|
||||
|
||||
// CPUInfo CPU信息
|
||||
func (s *SystemInfoImpl) CPUInfo() map[string]any {
|
||||
var core int = 0
|
||||
var speed string = "未知"
|
||||
var model string = "未知"
|
||||
cpuInfo, err := cpu.Info()
|
||||
if err == nil {
|
||||
core = runtime.NumCPU()
|
||||
speed = fmt.Sprintf("%.0fMHz", cpuInfo[0].Mhz)
|
||||
model = strings.TrimSpace(cpuInfo[0].ModelName)
|
||||
}
|
||||
|
||||
useds := []string{}
|
||||
cpuPercent, err := cpu.Percent(0, true)
|
||||
if err == nil {
|
||||
for _, v := range cpuPercent {
|
||||
useds = append(useds, fmt.Sprintf("%.2f", v))
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"model": model,
|
||||
"speed": speed,
|
||||
"core": core,
|
||||
"coreUsed": useds,
|
||||
}
|
||||
}
|
||||
|
||||
// NetworkInfo 网络信息
|
||||
func (s *SystemInfoImpl) NetworkInfo() map[string]string {
|
||||
ipAddrs := make(map[string]string)
|
||||
interfaces, err := net.Interfaces()
|
||||
if err == nil {
|
||||
for _, iface := range interfaces {
|
||||
name := iface.Name
|
||||
if name[len(name)-1] == '0' {
|
||||
name = name[0 : len(name)-1]
|
||||
name = strings.Trim(name, "")
|
||||
}
|
||||
// ignore localhost
|
||||
if name == "lo" {
|
||||
continue
|
||||
}
|
||||
var addrs []string
|
||||
for _, v := range iface.Addrs {
|
||||
prefix := strings.Split(v.Addr, "/")[0]
|
||||
if strings.Contains(prefix, "::") {
|
||||
addrs = append(addrs, fmt.Sprintf("IPv6 %s", prefix))
|
||||
}
|
||||
if strings.Contains(prefix, ".") {
|
||||
addrs = append(addrs, fmt.Sprintf("IPv4 %s", prefix))
|
||||
}
|
||||
}
|
||||
ipAddrs[name] = strings.Join(addrs, " / ")
|
||||
}
|
||||
}
|
||||
return ipAddrs
|
||||
}
|
||||
|
||||
// DiskInfo 磁盘信息
|
||||
func (s *SystemInfoImpl) DiskInfo() []map[string]string {
|
||||
disks := make([]map[string]string, 0)
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
partitions, err := disk.PartitionsWithContext(ctx, false)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
return disks
|
||||
}
|
||||
|
||||
for _, partition := range partitions {
|
||||
usage, err := disk.Usage(partition.Mountpoint)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
disks = append(disks, map[string]string{
|
||||
"size": parse.Bit(float64(usage.Total)),
|
||||
"used": parse.Bit(float64(usage.Used)),
|
||||
"avail": parse.Bit(float64(usage.Free)),
|
||||
"pcent": fmt.Sprintf("%.1f%%", usage.UsedPercent),
|
||||
"target": partition.Device,
|
||||
})
|
||||
}
|
||||
return disks
|
||||
}
|
||||
@@ -15,19 +15,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 AlarmController 结构体
|
||||
var NewAlarmController = &AlarmController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
alarmService: neDataService.NewAlarmImpl,
|
||||
var NewAlarm = &AlarmController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
alarmService: neDataService.NewAlarm,
|
||||
}
|
||||
|
||||
// 告警数据
|
||||
//
|
||||
// PATH /alarm
|
||||
type AlarmController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// 告警信息服务
|
||||
alarmService neDataService.IAlarm
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
alarmService *neDataService.Alarm // 告警信息服务
|
||||
}
|
||||
|
||||
// 告警列表
|
||||
|
||||
@@ -16,19 +16,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 PerfKPIController 结构体
|
||||
var NewPerfKPIController = &PerfKPIController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
perfKPIService: neDataService.NewPerfKPIImpl,
|
||||
var NewPerfKPI = &PerfKPIController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
perfKPIService: neDataService.NewPerfKPI,
|
||||
}
|
||||
|
||||
// 性能统计
|
||||
//
|
||||
// PATH /kpi
|
||||
type PerfKPIController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// 统计信息服务
|
||||
perfKPIService neDataService.IPerfKPI
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
perfKPIService *neDataService.PerfKPI // 统计信息服务
|
||||
}
|
||||
|
||||
// 获取统计数据
|
||||
|
||||
@@ -22,19 +22,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 AMFController 结构体
|
||||
var NewAMFController = &AMFController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
ueEventService: neDataService.NewUEEventAMFImpl,
|
||||
var NewAMF = &AMFController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
ueEventService: neDataService.NewUEEventAMF,
|
||||
}
|
||||
|
||||
// 网元AMF
|
||||
//
|
||||
// PATH /amf
|
||||
type AMFController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// UE会话事件服务
|
||||
ueEventService neDataService.IUEEventAMF
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
ueEventService *neDataService.UEEventAMF // UE会话事件服务
|
||||
}
|
||||
|
||||
// UE会话列表
|
||||
@@ -127,11 +125,11 @@ func (s *AMFController) UEExport(c *gin.Context) {
|
||||
"F1": "Tenant Name",
|
||||
}
|
||||
// 读取字典数据 UE 事件类型
|
||||
dictUEEventType := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_event_type")
|
||||
dictUEEventType := sysService.NewSysDictData.SelectDictDataByType("ue_event_type")
|
||||
// 读取字典数据 UE 事件认证代码类型
|
||||
dictUEAauthCode := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_auth_code")
|
||||
dictUEAauthCode := sysService.NewSysDictData.SelectDictDataByType("ue_auth_code")
|
||||
// 读取字典数据 UE 事件CM状态
|
||||
dictUEEventCmState := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_event_cm_state")
|
||||
dictUEEventCmState := sysService.NewSysDictData.SelectDictDataByType("ue_event_cm_state")
|
||||
// 从第二行开始的数据
|
||||
dataCells := make([]map[string]any, 0)
|
||||
for i, row := range rows {
|
||||
|
||||
@@ -23,19 +23,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 IMSController 结构体
|
||||
var NewIMSController = &IMSController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
cdrEventService: neDataService.NewCDREventIMSImpl,
|
||||
var NewIMS = &IMSController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
cdrEventService: neDataService.NewCDREventIMS,
|
||||
}
|
||||
|
||||
// 网元IMS
|
||||
//
|
||||
// PATH /ims
|
||||
type IMSController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// CDR会话事件服务
|
||||
cdrEventService neDataService.ICDREventIMS
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
cdrEventService *neDataService.CDREventIMS // CDR会话事件服务
|
||||
}
|
||||
|
||||
// CDR会话列表
|
||||
@@ -138,9 +136,9 @@ func (s *IMSController) CDRExport(c *gin.Context) {
|
||||
"I1": "Tenant Name", // for multi-tenancy
|
||||
}
|
||||
// 读取字典数据 CDR SIP响应代码类别类型
|
||||
dictCDRSipCode := sysService.NewSysDictDataImpl.SelectDictDataByType("cdr_sip_code")
|
||||
dictCDRSipCode := sysService.NewSysDictData.SelectDictDataByType("cdr_sip_code")
|
||||
// 读取字典数据 CDR 呼叫类型
|
||||
dictCDRCallType := sysService.NewSysDictDataImpl.SelectDictDataByType("cdr_call_type")
|
||||
dictCDRCallType := sysService.NewSysDictData.SelectDictDataByType("cdr_call_type")
|
||||
// 从第二行开始的数据
|
||||
dataCells := make([]map[string]any, 0)
|
||||
for i, row := range rows {
|
||||
|
||||
@@ -23,19 +23,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 MMEController 结构体
|
||||
var NewMMEController = &MMEController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
ueEventService: neDataService.NewUEEventMMEImpl,
|
||||
var NewMME = &MMEController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
ueEventService: neDataService.NewUEEventMME,
|
||||
}
|
||||
|
||||
// 网元MME
|
||||
//
|
||||
// PATH /mme
|
||||
type MMEController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// UE会话事件服务
|
||||
ueEventService neDataService.IUEEventMME
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
ueEventService *neDataService.UEEventMME // UE会话事件服务
|
||||
}
|
||||
|
||||
// UE会话列表
|
||||
@@ -128,11 +126,11 @@ func (s *MMEController) UEExport(c *gin.Context) {
|
||||
"F1": "Tenant Name",
|
||||
}
|
||||
// 读取字典数据 UE 事件类型
|
||||
dictUEEventType := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_event_type")
|
||||
dictUEEventType := sysService.NewSysDictData.SelectDictDataByType("ue_event_type")
|
||||
// 读取字典数据 UE 事件认证代码类型
|
||||
dictUEAauthCode := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_auth_code")
|
||||
dictUEAauthCode := sysService.NewSysDictData.SelectDictDataByType("ue_auth_code")
|
||||
// 读取字典数据 UE 事件CM状态
|
||||
dictUEEventCmState := sysService.NewSysDictDataImpl.SelectDictDataByType("ue_event_cm_state")
|
||||
dictUEEventCmState := sysService.NewSysDictData.SelectDictDataByType("ue_event_cm_state")
|
||||
// 从第二行开始的数据
|
||||
dataCells := make([]map[string]any, 0)
|
||||
for i, row := range rows {
|
||||
|
||||
@@ -22,22 +22,19 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 SMFController 结构体
|
||||
var NewSMFController = &SMFController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
cdrEventService: neDataService.NewCDREventSMFImpl,
|
||||
udmUserInfoService: *neDataService.NewUDMUserInfo,
|
||||
var NewSMF = &SMFController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
cdrEventService: neDataService.NewCDREventSMF,
|
||||
udmUserInfoService: neDataService.NewUDMUserInfo,
|
||||
}
|
||||
|
||||
// 网元SMF
|
||||
//
|
||||
// PATH /smf
|
||||
type SMFController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// CDR会话事件服务
|
||||
cdrEventService neDataService.ICDREventSMF
|
||||
// UDM用户信息服务
|
||||
udmUserInfoService neDataService.UDMUserInfo
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
cdrEventService *neDataService.CDREventSMF // CDR会话事件服务
|
||||
udmUserInfoService *neDataService.UDMUserInfo // UDM用户信息服务
|
||||
}
|
||||
|
||||
// CDR会话列表
|
||||
@@ -131,18 +128,31 @@ func (s *SMFController) CDRExport(c *gin.Context) {
|
||||
headerCells := map[string]string{
|
||||
"A1": "ID",
|
||||
"B1": "Charging ID",
|
||||
"C1": "Subscriber ID Data",
|
||||
"D1": "Subscriber ID Type",
|
||||
"E1": "Data Volume Uplink",
|
||||
"F1": "Data Volume Downlink",
|
||||
"G1": "Data Total Volume",
|
||||
"H1": "Duration",
|
||||
"I1": "Invocation Time",
|
||||
"J1": "PDU Session Charging Information",
|
||||
"K1": "Tenant Name", // for multi-tenancy
|
||||
"C1": "NE Name",
|
||||
"D1": "Resource Unique ID",
|
||||
"E1": "Subscriber ID Data",
|
||||
"F1": "Subscriber ID Type",
|
||||
"G1": "Data Volume Uplink",
|
||||
"H1": "Data Volume Downlink",
|
||||
"I1": "Data Total Volume",
|
||||
"J1": "Duration",
|
||||
"K1": "Invocation Time",
|
||||
"L1": "User Identifier",
|
||||
"M1": "SSC Mode",
|
||||
"N1": "DNN ID",
|
||||
"O1": "PDU Type",
|
||||
"P1": "RAT Type",
|
||||
"Q1": "PDU IPv4 Address",
|
||||
"R1": "Network Function IPv4",
|
||||
"S1": "PDU IPv6 Address Swith Prefix",
|
||||
"T1": "Record Network Function ID",
|
||||
"U1": "Record Type",
|
||||
"V1": "Record Opening Time",
|
||||
"W1": "Tenant Name", // for multi-tenancy
|
||||
}
|
||||
// 从第二行开始的数据
|
||||
dataCells := make([]map[string]any, 0)
|
||||
|
||||
for i, row := range rows {
|
||||
idx := strconv.Itoa(i + 2)
|
||||
// 解析 JSON 字符串为 map
|
||||
@@ -167,12 +177,22 @@ func (s *SMFController) CDRExport(c *gin.Context) {
|
||||
subscriptionIDData = sub["subscriptionIDData"].(string)
|
||||
}
|
||||
}
|
||||
|
||||
// 网络功能 IPv4 地址
|
||||
networkFunctionIPv4Address := ""
|
||||
if v, ok := cdrJSON["nFunctionConsumerInformation"]; ok && v != nil {
|
||||
if conInfo, conInfoOk := v.(map[string]any); conInfoOk && conInfo != nil {
|
||||
networkFunctionIPv4Address = conInfo["networkFunctionIPv4Address"].(string)
|
||||
}
|
||||
}
|
||||
|
||||
// 数据量上行链路
|
||||
dataVolumeUplink := []string{}
|
||||
// 数据量下行链路
|
||||
dataVolumeDownlink := []string{}
|
||||
// 数据总量
|
||||
dataTotalVolume := []string{}
|
||||
|
||||
if v, ok := cdrJSON["listOfMultipleUnitUsage"]; ok && v != nil {
|
||||
usageList := v.([]any)
|
||||
if len(usageList) > 0 {
|
||||
@@ -207,32 +227,31 @@ func (s *SMFController) CDRExport(c *gin.Context) {
|
||||
invocationTimestamp = v.(string)
|
||||
}
|
||||
// 记录打开时间
|
||||
pduSessionChargingInformation := ""
|
||||
User_Identifier := ""
|
||||
SSC_Mode := ""
|
||||
RAT_Type := ""
|
||||
DNN_ID := ""
|
||||
PDU_Type := ""
|
||||
PDU_IPv4 := ""
|
||||
PDU_IPv6 := ""
|
||||
if v, ok := cdrJSON["pDUSessionChargingInformation"]; ok && v != nil {
|
||||
pduInfo := v.(map[string]any)
|
||||
|
||||
User_Identifier := ""
|
||||
if v, ok := pduInfo["userIdentifier"]; ok && v != nil {
|
||||
User_Identifier = v.(string)
|
||||
}
|
||||
SSC_Mode := ""
|
||||
if v, ok := pduInfo["sSCMode"]; ok && v != nil {
|
||||
SSC_Mode = v.(string)
|
||||
}
|
||||
RAT_Type := ""
|
||||
if v, ok := pduInfo["rATType"]; ok && v != nil {
|
||||
RAT_Type = v.(string)
|
||||
}
|
||||
DNN_ID := ""
|
||||
if v, ok := pduInfo["dNNID"]; ok && v != nil {
|
||||
DNN_ID = v.(string)
|
||||
}
|
||||
PDU_Type := ""
|
||||
if v, ok := pduInfo["pDUType"]; ok && v != nil {
|
||||
PDU_Type = v.(string)
|
||||
}
|
||||
PDU_IPv4 := ""
|
||||
PDU_IPv6 := ""
|
||||
if v, ok := pduInfo["pDUAddress"]; ok && v != nil {
|
||||
pDUAddress := v.(map[string]any)
|
||||
if addr, ok := pDUAddress["pDUIPv4Address"]; ok && addr != nil {
|
||||
@@ -243,11 +262,29 @@ func (s *SMFController) CDRExport(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
pduSessionChargingInformation = fmt.Sprintf(`User Identifier: %s
|
||||
SSC Mode: %s RAT Type: %s DNN ID: %s
|
||||
PDU Type: %s
|
||||
PDU IPv4 Address: %s
|
||||
PDU IPv6 Addres Swith Prefix: %s`, User_Identifier, SSC_Mode, RAT_Type, DNN_ID, PDU_Type, PDU_IPv4, PDU_IPv6)
|
||||
// pduSessionChargingInformation = fmt.Sprintf(`User Identifier: %s
|
||||
// SSC Mode: %s RAT Type: %s DNN ID: %s
|
||||
// PDU Type: %s
|
||||
// PDU IPv4 Address: %s
|
||||
// PDU IPv6 Addres Swith Prefix: %s`, User_Identifier, SSC_Mode, RAT_Type, DNN_ID, PDU_Type, PDU_IPv4, PDU_IPv6)
|
||||
}
|
||||
|
||||
// 记录网络参数ID
|
||||
recordNFID := ""
|
||||
if v, ok := cdrJSON["recordingNetworkFunctionID"]; ok && v != nil {
|
||||
recordNFID = v.(string)
|
||||
}
|
||||
|
||||
//记录开始时间
|
||||
recordOpeningTime := ""
|
||||
if v, ok := cdrJSON["recordOpeningTime"]; ok && v != nil {
|
||||
recordOpeningTime = v.(string)
|
||||
}
|
||||
|
||||
//记录类型
|
||||
recordType := ""
|
||||
if v, ok := cdrJSON["recordType"]; ok && v != nil {
|
||||
recordType = v.(string)
|
||||
}
|
||||
// for multi-tenant, get tenant name
|
||||
tenantName := row.TenantName
|
||||
@@ -255,15 +292,27 @@ PDU IPv6 Addres Swith Prefix: %s`, User_Identifier, SSC_Mode, RAT_Type, DNN_ID,
|
||||
dataCells = append(dataCells, map[string]any{
|
||||
"A" + idx: row.ID,
|
||||
"B" + idx: chargingID,
|
||||
"C" + idx: subscriptionIDData,
|
||||
"D" + idx: subscriptionIDType,
|
||||
"E" + idx: strings.Join(dataVolumeUplink, ","),
|
||||
"F" + idx: strings.Join(dataVolumeDownlink, ","),
|
||||
"G" + idx: strings.Join(dataTotalVolume, ","),
|
||||
"H" + idx: duration,
|
||||
"I" + idx: invocationTimestamp,
|
||||
"J" + idx: pduSessionChargingInformation,
|
||||
"K" + idx: tenantName,
|
||||
"C" + idx: row.NeName,
|
||||
"D" + idx: row.RmUID,
|
||||
"E" + idx: subscriptionIDData,
|
||||
"F" + idx: subscriptionIDType,
|
||||
"G" + idx: strings.Join(dataVolumeUplink, ","),
|
||||
"H" + idx: strings.Join(dataVolumeDownlink, ","),
|
||||
"I" + idx: strings.Join(dataTotalVolume, ","),
|
||||
"J" + idx: duration,
|
||||
"K" + idx: invocationTimestamp,
|
||||
"L" + idx: User_Identifier,
|
||||
"M" + idx: SSC_Mode,
|
||||
"N" + idx: DNN_ID,
|
||||
"O" + idx: PDU_Type,
|
||||
"P" + idx: RAT_Type,
|
||||
"Q" + idx: PDU_IPv4,
|
||||
"R" + idx: networkFunctionIPv4Address,
|
||||
"S" + idx: PDU_IPv6,
|
||||
"T" + idx: recordNFID,
|
||||
"U" + idx: recordType,
|
||||
"V" + idx: recordOpeningTime,
|
||||
"W" + idx: tenantName,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -22,19 +22,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 SMSCController 结构体
|
||||
var NewSMSCController = &SMSCController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
cdrEventService: neDataService.NewCDREventSMSCImpl,
|
||||
var NewSMSC = &SMSCController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
cdrEventService: neDataService.NewCDREventSMSC,
|
||||
}
|
||||
|
||||
// 网元SMSC
|
||||
//
|
||||
// PATH /smsc
|
||||
type SMSCController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// CDR会话事件服务
|
||||
cdrEventService neDataService.ICDREventSMSC
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
cdrEventService *neDataService.CDREventSMSC // CDR会话事件服务
|
||||
}
|
||||
|
||||
// CDR会话列表
|
||||
|
||||
@@ -24,17 +24,15 @@ import (
|
||||
// 实例化控制层 UDMAuthController 结构体
|
||||
var NewUDMAuth = &UDMAuthController{
|
||||
udmAuthService: neDataService.NewUDMAuthUser,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// UDM鉴权用户
|
||||
//
|
||||
// PATH /udm/auth
|
||||
type UDMAuthController struct {
|
||||
// UDM鉴权信息服务
|
||||
udmAuthService *neDataService.UDMAuthUser
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
udmAuthService *neDataService.UDMAuthUser // UDM鉴权信息服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
}
|
||||
|
||||
// UDM鉴权用户重载数据
|
||||
@@ -48,7 +46,6 @@ func (s *UDMAuthController) ResetData(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
neId = ""
|
||||
data := s.udmAuthService.ResetData(neId)
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -58,7 +55,6 @@ func (s *UDMAuthController) ResetData(c *gin.Context) {
|
||||
// GET /list
|
||||
func (s *UDMAuthController) List(c *gin.Context) {
|
||||
querys := ctx.QueryMap(c)
|
||||
querys["neId"] = ""
|
||||
data := s.udmAuthService.SelectPage(querys)
|
||||
c.JSON(200, result.Ok(data))
|
||||
}
|
||||
@@ -102,7 +98,6 @@ func (s *UDMAuthController) Info(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
neId = ""
|
||||
// 解析返回的数据
|
||||
u := s.udmAuthService.ParseInfo(imsi, neId, data)
|
||||
s.udmAuthService.Insert(neId, u)
|
||||
@@ -142,7 +137,8 @@ func (s *UDMAuthController) Add(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("add authdat:imsi=%s,ki=%s,amf=%s,algo=%s,opc=%s", body.IMSI, body.Ki, body.Amf, body.AlgoIndex, body.Opc)
|
||||
cmd := fmt.Sprintf("add authdat:imsi=%s,", body.IMSI)
|
||||
cmd += s.udmAuthService.ParseCommandParams(body)
|
||||
data, err := telnet.ConvertToStr(telnetClient, cmd)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
@@ -151,7 +147,6 @@ func (s *UDMAuthController) Add(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
s.udmAuthService.Insert(neId, body)
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
@@ -191,7 +186,8 @@ func (s *UDMAuthController) Adds(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("baa authdat:start_imsi=%s,sub_num=%s,ki=%s,amf=%s,algo=%s,opc=%s", body.IMSI, num, body.Ki, body.Amf, body.AlgoIndex, body.Opc)
|
||||
cmd := fmt.Sprintf("baa authdat:start_imsi=%s,sub_num=%s,", body.IMSI, num)
|
||||
cmd += s.udmAuthService.ParseCommandParams(body)
|
||||
data, err := telnet.ConvertToStr(telnetClient, cmd)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
@@ -200,8 +196,7 @@ func (s *UDMAuthController) Adds(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
go s.udmAuthService.LoadData(neId, body.IMSI, num)
|
||||
s.udmAuthService.LoadData(neId, body.IMSI, num)
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -239,20 +234,8 @@ func (s *UDMAuthController) Edit(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("mod authdata:imsi=%s", body.IMSI)
|
||||
// 修改的参数名称
|
||||
if body.Ki != "" {
|
||||
cmd += fmt.Sprintf(",ki=%s", body.Ki)
|
||||
}
|
||||
if body.Amf != "" {
|
||||
cmd += fmt.Sprintf(",amf=%s", body.Amf)
|
||||
}
|
||||
if body.AlgoIndex != "" {
|
||||
cmd += fmt.Sprintf(",algo=%s", body.AlgoIndex)
|
||||
}
|
||||
if body.Opc != "" {
|
||||
cmd += fmt.Sprintf(",opc=%s", body.Opc)
|
||||
}
|
||||
cmd := fmt.Sprintf("mod authdata:imsi=%s,", body.IMSI)
|
||||
cmd += s.udmAuthService.ParseCommandParams(body)
|
||||
data, err := telnet.ConvertToStr(telnetClient, cmd)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
@@ -261,7 +244,6 @@ func (s *UDMAuthController) Edit(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
s.udmAuthService.Insert(neId, body)
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
@@ -312,7 +294,6 @@ func (s *UDMAuthController) Remove(c *gin.Context) {
|
||||
}
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
s.udmAuthService.Delete(imsi, neId)
|
||||
}
|
||||
resultData[imsi] = data
|
||||
@@ -358,8 +339,7 @@ func (s *UDMAuthController) Removes(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
go s.udmAuthService.LoadData(neId, imsi, num)
|
||||
s.udmAuthService.LoadData(neId, imsi, num)
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -384,7 +364,6 @@ func (s *UDMAuthController) Export(c *gin.Context) {
|
||||
|
||||
querys["pageNum"] = 1
|
||||
querys["pageSize"] = 10000
|
||||
querys["neId"] = ""
|
||||
data := s.udmAuthService.SelectPage(querys)
|
||||
if parse.Number(data["total"]) == 0 {
|
||||
// 导出数据记录为空
|
||||
@@ -434,8 +413,8 @@ func (s *UDMAuthController) Export(c *gin.Context) {
|
||||
data = append(data, []string{v.IMSI, v.Ki, v.AlgoIndex, v.Amf, opc})
|
||||
}
|
||||
// 输出到文件
|
||||
err := file.WriterFileTXT(data, ",", filePath)
|
||||
if err != nil {
|
||||
|
||||
if err := file.WriterFileTXT(data, ",", filePath); err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -531,13 +510,11 @@ func (s *UDMAuthController) Import(c *gin.Context) {
|
||||
if strings.Contains(resultMsg, "ok") {
|
||||
if strings.HasSuffix(body.UploadPath, ".csv") {
|
||||
data := file.ReadFileCSV(localFilePath)
|
||||
neId := ""
|
||||
go s.udmAuthService.InsertData(neId, "csv", data)
|
||||
go s.udmAuthService.InsertData(neInfo.NeId, "csv", data)
|
||||
}
|
||||
if strings.HasSuffix(body.UploadPath, ".txt") {
|
||||
data := file.ReadFileTXT(",", localFilePath)
|
||||
neId := ""
|
||||
go s.udmAuthService.InsertData(neId, "txt", data)
|
||||
go s.udmAuthService.InsertData(neInfo.NeId, "txt", data)
|
||||
}
|
||||
}
|
||||
c.JSON(200, result.OkMsg(resultMsg))
|
||||
|
||||
@@ -23,17 +23,15 @@ import (
|
||||
// 实例化控制层 UDMSubController 结构体
|
||||
var NewUDMSub = &UDMSubController{
|
||||
udmSubService: neDataService.NewUDMSub,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// UDM签约用户
|
||||
//
|
||||
// PATH /udm/sub
|
||||
type UDMSubController struct {
|
||||
// UDM签约信息服务
|
||||
udmSubService *neDataService.UDMSubUser
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
udmSubService *neDataService.UDMSubUser // UDM签约信息服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
}
|
||||
|
||||
// UDM签约用户重载数据
|
||||
@@ -47,7 +45,6 @@ func (s *UDMSubController) ResetData(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
neId = ""
|
||||
data := s.udmSubService.ResetData(neId)
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -57,7 +54,6 @@ func (s *UDMSubController) ResetData(c *gin.Context) {
|
||||
// GET /list
|
||||
func (s *UDMSubController) List(c *gin.Context) {
|
||||
querys := ctx.QueryMap(c)
|
||||
querys["neId"] = ""
|
||||
querys["userName"] = ctx.LoginUserToUserName(c)
|
||||
data := s.udmSubService.SelectPage(querys)
|
||||
c.JSON(200, result.Ok(data))
|
||||
@@ -102,7 +98,6 @@ func (s *UDMSubController) Info(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
neId = ""
|
||||
// 解析返回的数据
|
||||
u := s.udmSubService.ParseInfo(imsi, neId, data)
|
||||
s.udmSubService.Insert(neId, u)
|
||||
@@ -142,12 +137,8 @@ func (s *UDMSubController) Add(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("add udmuser:imsi=%s,msisdn=%s,ambr=%s,nssai=%s,arfb=%s,sar=%s,rat=%s,cn=%s,smf_sel=%s,sm_data=%s,eps_flag=%s,eps_odb=%s,hplmn_odb=%s,ard=%s,epstpl=%s,context_id=%s,apn_context=%s,cag=%s",
|
||||
body.IMSI, body.MSISDN, body.Ambr, body.Nssai, body.Arfb, body.Sar, body.Rat, body.Cn, body.SmfSel, body.SmData, body.EpsFlag, body.EpsOdb, body.HplmnOdb, body.Ard, body.Epstpl, body.ContextId, body.ApnContext, body.Cag)
|
||||
// static_ip指给4G UE分配的静态IP,没有可不带此字段名,批量添加IP会自动递增
|
||||
if body.StaticIp != "" {
|
||||
cmd += fmt.Sprintf(",static_ip=%s", body.StaticIp)
|
||||
}
|
||||
cmd := fmt.Sprintf("add udmuser:imsi=%s,", body.IMSI)
|
||||
cmd += s.udmSubService.ParseCommandParams(body)
|
||||
data, err := telnet.ConvertToStr(telnetClient, cmd)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
@@ -156,7 +147,6 @@ func (s *UDMSubController) Add(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
body.NeId = neId
|
||||
s.udmSubService.Insert(neId, body)
|
||||
}
|
||||
@@ -197,8 +187,8 @@ func (s *UDMSubController) Adds(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("baa udmuser:start_imsi=%s,start_msisdn=%s,sub_num=%s,ambr=%s,nssai=%s,arfb=%s,sar=%s,rat=%s,cn=%s,smf_sel=%s,sm_data=%s,eps_flag=%s,eps_odb=%s,hplmn_odb=%s,ard=%s,epstpl=%s,context_id=%s,apn_context=%s,cag=%s",
|
||||
body.IMSI, body.MSISDN, num, body.Ambr, body.Nssai, body.Arfb, body.Sar, body.Rat, body.Cn, body.SmfSel, body.SmData, body.EpsFlag, body.EpsOdb, body.HplmnOdb, body.Ard, body.Epstpl, body.ContextId, body.ApnContext, body.Cag)
|
||||
cmd := fmt.Sprintf("baa udmuser:start_imsi=%s,start_msisdn=%s,sub_num=%s,", body.IMSI, body.MSISDN, num)
|
||||
cmd += s.udmSubService.ParseCommandParams(body)
|
||||
// static_ip指给4G UE分配的静态IP,没有可不带此字段名,批量添加IP会自动递增
|
||||
if body.StaticIp != "" {
|
||||
cmd += fmt.Sprintf(",static_ip=%s", body.StaticIp)
|
||||
@@ -211,8 +201,7 @@ func (s *UDMSubController) Adds(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
go s.udmSubService.LoadData(neId, body.IMSI, num, body.Remark)
|
||||
s.udmSubService.LoadData(neId, body.IMSI, num, body.Remark)
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -250,65 +239,8 @@ func (s *UDMSubController) Edit(c *gin.Context) {
|
||||
defer telnetClient.Close()
|
||||
|
||||
// 发送MML
|
||||
cmd := fmt.Sprintf("mod udmuser:imsi=%s", body.IMSI)
|
||||
// 修改的参数名称
|
||||
if body.MSISDN != "" {
|
||||
cmd += fmt.Sprintf(",msisdn=%s", body.MSISDN)
|
||||
}
|
||||
if body.Ambr != "" {
|
||||
cmd += fmt.Sprintf(",ambr=%s", body.Ambr)
|
||||
}
|
||||
if body.Nssai != "" {
|
||||
cmd += fmt.Sprintf(",nssai=%s", body.Nssai)
|
||||
}
|
||||
if body.Arfb != "" {
|
||||
cmd += fmt.Sprintf(",arfb=%s", body.Arfb)
|
||||
}
|
||||
if body.Sar != "" {
|
||||
cmd += fmt.Sprintf(",sar=%s", body.Sar)
|
||||
}
|
||||
if body.Rat != "" {
|
||||
cmd += fmt.Sprintf(",rat=%s", body.Rat)
|
||||
}
|
||||
if body.Cn != "" {
|
||||
cmd += fmt.Sprintf(",cn=%s", body.Cn)
|
||||
}
|
||||
if body.SmfSel != "" {
|
||||
cmd += fmt.Sprintf(",smf_sel=%s", body.SmfSel)
|
||||
}
|
||||
if body.SmData != "" {
|
||||
cmd += fmt.Sprintf(",sm_data=%s", body.SmData)
|
||||
}
|
||||
if body.EpsDat != "" {
|
||||
cmd += fmt.Sprintf(",eps_dat=%s", body.EpsDat)
|
||||
}
|
||||
if body.EpsFlag != "" {
|
||||
cmd += fmt.Sprintf(",eps_flag=%s", body.EpsFlag)
|
||||
}
|
||||
if body.EpsOdb != "" {
|
||||
cmd += fmt.Sprintf(",eps_odb=%s", body.EpsOdb)
|
||||
}
|
||||
if body.HplmnOdb != "" {
|
||||
cmd += fmt.Sprintf(",hplmn_odb=%s", body.HplmnOdb)
|
||||
}
|
||||
if body.Epstpl != "" {
|
||||
cmd += fmt.Sprintf(",epstpl=%s", body.Epstpl)
|
||||
}
|
||||
if body.Ard != "" {
|
||||
cmd += fmt.Sprintf(",ard=%s", body.Ard)
|
||||
}
|
||||
if body.ContextId != "" {
|
||||
cmd += fmt.Sprintf(",context_id=%s", body.ContextId)
|
||||
}
|
||||
if body.ApnContext != "" {
|
||||
cmd += fmt.Sprintf(",apn_context=%s", body.ApnContext)
|
||||
}
|
||||
if body.Cag != "" {
|
||||
cmd += fmt.Sprintf(",cag=%s", body.Cag)
|
||||
}
|
||||
if body.StaticIp != "" {
|
||||
cmd += fmt.Sprintf(",static_ip=%s", body.StaticIp)
|
||||
}
|
||||
cmd := fmt.Sprintf("mod udmuser:imsi=%s,", body.IMSI)
|
||||
cmd += s.udmSubService.ParseCommandParams(body)
|
||||
data, err := telnet.ConvertToStr(telnetClient, cmd)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
@@ -317,7 +249,6 @@ func (s *UDMSubController) Edit(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
body.NeId = neId
|
||||
s.udmSubService.Insert(neId, body)
|
||||
}
|
||||
@@ -369,7 +300,6 @@ func (s *UDMSubController) Remove(c *gin.Context) {
|
||||
}
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
s.udmSubService.Delete(neId, imsi)
|
||||
}
|
||||
resultData[imsi] = data
|
||||
@@ -415,9 +345,7 @@ func (s *UDMSubController) Removes(c *gin.Context) {
|
||||
|
||||
// 命令ok时
|
||||
if strings.Contains(data, "ok") {
|
||||
neId = ""
|
||||
go s.udmSubService.LoadData(neId, imsi, num, "-(Deleted)-")
|
||||
|
||||
s.udmSubService.LoadData(neId, imsi, num, "-(Deleted)-")
|
||||
}
|
||||
c.JSON(200, result.OkData(data))
|
||||
}
|
||||
@@ -442,11 +370,6 @@ func (s *UDMSubController) Export(c *gin.Context) {
|
||||
|
||||
querys["pageNum"] = 1
|
||||
querys["pageSize"] = 10000
|
||||
|
||||
// for multi-tenancy
|
||||
querys["userName"] = ctx.LoginUserToUserName(c)
|
||||
querys["neId"] = ""
|
||||
|
||||
data := s.udmSubService.SelectPage(querys)
|
||||
if parse.Number(data["total"]) == 0 {
|
||||
// 导出数据记录为空
|
||||
@@ -469,14 +392,13 @@ func (s *UDMSubController) Export(c *gin.Context) {
|
||||
if fileType == "csv" {
|
||||
// 转换数据
|
||||
data := [][]string{}
|
||||
data = append(data, []string{"imsi", "msisdn", "ambr", "nssai", "arfb", "sar", "rat", "cn", "smf_sel", "sm_dat", "eps_dat", "tenant_name"})
|
||||
data = append(data, []string{"IMSI", "MSISDN", "UeAmbrTpl", "NssaiTpl", "AreaForbiddenTpl", "ServiceAreaRestrictionTpl", "RatRestrictions", "CnTypeRestrictions", "SmfSel", "SmData", "EPSDat"})
|
||||
for _, v := range rows {
|
||||
epsDat := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s", v.EpsFlag, v.EpsOdb, v.HplmnOdb, v.Ard, v.Epstpl, v.ContextId, v.ApnContext, v.StaticIp)
|
||||
data = append(data, []string{v.IMSI, v.MSISDN, v.Ambr, v.Nssai, v.Arfb, v.Sar, v.Rat, v.Cn, v.SmfSel, v.SmData, epsDat, v.TenantName})
|
||||
data = append(data, []string{v.IMSI, v.MSISDN, v.UeAmbrTpl, v.NssaiTpl, v.AreaForbiddenTpl, v.ServiceAreaRestrictionTpl, v.RatRestrictions, v.CnTypeRestrictions, v.SmfSel, v.SmData, epsDat})
|
||||
}
|
||||
// 输出到文件
|
||||
err := file.WriterFileCSV(data, filePath)
|
||||
if err != nil {
|
||||
if err := file.WriterFileCSV(data, filePath); err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -487,11 +409,10 @@ func (s *UDMSubController) Export(c *gin.Context) {
|
||||
data := [][]string{}
|
||||
for _, v := range rows {
|
||||
epsDat := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s", v.EpsFlag, v.EpsOdb, v.HplmnOdb, v.Ard, v.Epstpl, v.ContextId, v.ApnContext, v.StaticIp)
|
||||
data = append(data, []string{v.IMSI, v.MSISDN, v.Ambr, v.Nssai, v.Arfb, v.Sar, v.Rat, v.Cn, v.SmfSel, v.SmData, epsDat, v.TenantName})
|
||||
data = append(data, []string{v.IMSI, v.MSISDN, v.UeAmbrTpl, v.NssaiTpl, v.AreaForbiddenTpl, v.ServiceAreaRestrictionTpl, v.RatRestrictions, v.CnTypeRestrictions, v.SmfSel, v.SmData, epsDat})
|
||||
}
|
||||
// 输出到文件
|
||||
err := file.WriterFileTXT(data, ",", filePath)
|
||||
if err != nil {
|
||||
if err := file.WriterFileTXT(data, ",", filePath); err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -571,13 +492,11 @@ func (s *UDMSubController) Import(c *gin.Context) {
|
||||
if strings.Contains(data, "ok") {
|
||||
if strings.HasSuffix(body.UploadPath, ".csv") {
|
||||
data := file.ReadFileCSV(localFilePath)
|
||||
neId := ""
|
||||
go s.udmSubService.InsertData(neId, "csv", data)
|
||||
go s.udmSubService.InsertData(neInfo.NeId, "csv", data)
|
||||
}
|
||||
if strings.HasSuffix(body.UploadPath, ".txt") {
|
||||
data := file.ReadFileTXT(",", localFilePath)
|
||||
neId := ""
|
||||
go s.udmSubService.InsertData(neId, "txt", data)
|
||||
go s.udmSubService.InsertData(neInfo.NeId, "txt", data)
|
||||
}
|
||||
}
|
||||
c.JSON(200, result.OkMsg(data))
|
||||
|
||||
@@ -10,19 +10,17 @@ import (
|
||||
)
|
||||
|
||||
// 实例化控制层 UPFController 结构体
|
||||
var NewUPFController = &UPFController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
perfKPIService: neDataService.NewPerfKPIImpl,
|
||||
var NewUPF = &UPFController{
|
||||
neInfoService: neService.NewNeInfo,
|
||||
perfKPIService: neDataService.NewPerfKPI,
|
||||
}
|
||||
|
||||
// 网元UPF
|
||||
//
|
||||
// PATH /upf
|
||||
type UPFController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// 统计信息服务
|
||||
perfKPIService neDataService.IPerfKPI
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
perfKPIService *neDataService.PerfKPI // 统计信息服务
|
||||
}
|
||||
|
||||
// 总流量数 N3上行 N6下行
|
||||
|
||||
@@ -3,13 +3,13 @@ package model
|
||||
// UDMAuthUser UDM鉴权用户 u_auth_user
|
||||
type UDMAuthUser struct {
|
||||
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 默认ID
|
||||
IMSI string `json:"imsi" gorm:"imsi"` // SIM卡/USIM卡ID
|
||||
NeId string `json:"neId" gorm:"ne_id"` // UDM网元标识
|
||||
Amf string `json:"amf" gorm:"amf"` // AMF
|
||||
Status string `json:"status" gorm:"status"` // 状态
|
||||
Ki string `json:"ki" gorm:"ki"` // ki
|
||||
AlgoIndex string `json:"algoIndex" gorm:"algo_index"` // algoIndex
|
||||
Opc string `json:"opc" gorm:"opc"` // OPC
|
||||
IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID
|
||||
NeId string `json:"neId" gorm:"column:ne_id"` // UDM网元标识
|
||||
Amf string `json:"amf" gorm:"column:amf"` // AMF
|
||||
Status string `json:"status" gorm:"column:status"` // 状态
|
||||
Ki string `json:"ki" gorm:"column:ki"` // ki
|
||||
AlgoIndex string `json:"algoIndex" gorm:"column:algo_index"` // algoIndex
|
||||
Opc string `json:"opc" gorm:"column:opc"` // OPC
|
||||
}
|
||||
|
||||
// TableName 表名称
|
||||
|
||||
@@ -2,28 +2,40 @@ package model
|
||||
|
||||
// UDMSubUser UDM签约用户 u_sub_user
|
||||
type UDMSubUser struct {
|
||||
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 主键
|
||||
IMSI string `json:"imsi" gorm:"imsi"` // SIM卡/USIM卡ID
|
||||
MSISDN string `json:"msisdn" gorm:"msisdn"` // 用户电话号码
|
||||
NeId string `json:"neId" gorm:"ne_id"` // UDM网元标识
|
||||
Ambr string `json:"ambr" gorm:"ambr"` // SubUeAMBRTemp
|
||||
Nssai string `json:"nssai" gorm:"nssai"` // SubSNSSAITemp
|
||||
Rat string `json:"rat" gorm:"rat"` // rat VIRTUAL|WLAN|EUTRA|NR
|
||||
Arfb string `json:"arfb" gorm:"arfb"` // forbiddenAreasTemp
|
||||
Sar string `json:"sar" gorm:"sar"` // serviceAreaRestrictTemp
|
||||
Cn string `json:"cn" gorm:"cn"` // cnType EPC|5GC
|
||||
SmData string `json:"smData" gorm:"sm_data"` // smData
|
||||
SmfSel string `json:"smfSel" gorm:"smf_sel"` // smfSel
|
||||
EpsDat string `json:"epsDat" gorm:"eps_dat"` // Eps
|
||||
EpsFlag string `json:"epsFlag" gorm:"eps_flag"` // epsFlag
|
||||
EpsOdb string `json:"epsOdb" gorm:"eps_odb"` // epsOdb
|
||||
HplmnOdb string `json:"hplmnOdb" gorm:"hplmn_odb"` // hplmnOdb
|
||||
Ard string `json:"ard" gorm:"ard"` // Ard
|
||||
Epstpl string `json:"epstpl" gorm:"epstpl"` // Epstpl
|
||||
ContextId string `json:"contextId" gorm:"context_id"` // ContextId
|
||||
ApnContext string `json:"apnContext" gorm:"apn_context"` // apnContext
|
||||
StaticIp string `json:"staticIp" gorm:"static_ip"` // staticIpstatic_ip指给4G UE分配的静态IP,没有可不带此字段名
|
||||
Cag string `json:"cag" gorm:"cag"` // CAG
|
||||
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"` // 主键
|
||||
IMSI string `json:"imsi" gorm:"column:imsi"` // SIM卡/USIM卡ID
|
||||
MSISDN string `json:"msisdn" gorm:"column:msisdn"` // 用户电话号码
|
||||
NeId string `json:"neId" gorm:"column:ne_id"` // UDM网元标识
|
||||
|
||||
AmDat string `json:"amDat" gorm:"column:am_dat"` // AmData
|
||||
UeAmbrTpl string `json:"ambr" gorm:"column:ambr"` // AmData SubUeAMBRTemp
|
||||
NssaiTpl string `json:"nssai" gorm:"column:nssai"` // AmData SubSNSSAITemp
|
||||
RatRestrictions string `json:"rat" gorm:"column:rat"` // AmData RAT 0x00:VIRTUAL 0x01:WLAN 0x02:EUTRA 0x03:NR
|
||||
AreaForbiddenTpl string `json:"arfb" gorm:"column:arfb"` // AmData AreaForbidden
|
||||
ServiceAreaRestrictionTpl string `json:"sar" gorm:"column:sar"` // AmData serviceAreaRestrictTemp
|
||||
CnTypeRestrictions string `json:"cnType" gorm:"column:cn_type"` // AmData CNType 0x00:EPC和5GC 0x01:5GC 0x02:EPC 0x03:EPC+5GC
|
||||
RfspIndex string `json:"rfspIndex" gorm:"column:rfsp_index"` // AmData RfspIndex
|
||||
SubsRegTime string `json:"regTimer" gorm:"column:reg_timer"` // AmData RegTimer
|
||||
UeUsageType string `json:"ueUsageType" gorm:"column:ue_usage_type"` // AmData UEUsageType
|
||||
ActiveTime string `json:"activeTime" gorm:"column:active_time"` // AmData ActiveTime
|
||||
MicoAllowed string `json:"mico" gorm:"column:mico"` // AmData MICO
|
||||
OdbPs string `json:"odbPs" gorm:"column:odb_ps"` // AmData ODB_PS 0-all,1-hplmn,2-vplmn
|
||||
GroupId string `json:"groupId" gorm:"column:group_id"` // AmData GroupId
|
||||
|
||||
EpsDat string `json:"epsDat" gorm:"column:eps_dat"` // EpsDat
|
||||
EpsFlag string `json:"epsFlag" gorm:"column:eps_flag"` // EpsDat epsFlag
|
||||
EpsOdb string `json:"epsOdb" gorm:"column:eps_odb"` // EpsDat epsOdb
|
||||
HplmnOdb string `json:"hplmnOdb" gorm:"column:hplmn_odb"` // EpsDat hplmnOdb
|
||||
Ard string `json:"ard" gorm:"column:ard"` // EpsDat Ard
|
||||
Epstpl string `json:"epstpl" gorm:"column:epstpl"` // EpsDat Epstpl
|
||||
ContextId string `json:"contextId" gorm:"column:context_id"` // EpsDat ContextId
|
||||
ApnNum string `json:"apnNum" gorm:"column:apn_mum"` // EpsDat apnNum
|
||||
ApnContext string `json:"apnContext" gorm:"column:apn_context"` // EpsDat apnContext
|
||||
StaticIp string `json:"staticIp" gorm:"column:static_ip"` // EpsDat staticIp 指给4G UE分配的静态IP,没有可不带此字段名
|
||||
|
||||
SmData string `json:"smData" gorm:"column:sm_data"` // smData
|
||||
SmfSel string `json:"smfSel" gorm:"column:smf_sel"` // smfSel
|
||||
Cag string `json:"cag" gorm:"column:cag"` // CAG
|
||||
|
||||
TenantID string `json:"tenantID" gorm:"column:tenant_id"`
|
||||
TenantName string `json:"tenantName" gorm:"-"`
|
||||
|
||||
@@ -21,11 +21,11 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
kpiGroup.GET("/title",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewPerfKPIController.Title,
|
||||
controller.NewPerfKPI.Title,
|
||||
)
|
||||
kpiGroup.GET("/data",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewPerfKPIController.GoldKPI,
|
||||
controller.NewPerfKPI.GoldKPI,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -34,11 +34,11 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
alarmGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewAlarmController.List,
|
||||
controller.NewAlarm.List,
|
||||
)
|
||||
alarmGroup.DELETE("/:alarmIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewAlarmController.Remove,
|
||||
controller.NewAlarm.Remove,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -47,17 +47,17 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
imsGroup.GET("/cdr/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewIMSController.CDRList,
|
||||
controller.NewIMS.CDRList,
|
||||
)
|
||||
imsGroup.DELETE("/cdr/:cdrIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.imsCDR", collectlogs.BUSINESS_TYPE_DELETE)),
|
||||
controller.NewIMSController.CDRRemove,
|
||||
controller.NewIMS.CDRRemove,
|
||||
)
|
||||
imsGroup.POST("/cdr/export",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.imsCDR", collectlogs.BUSINESS_TYPE_EXPORT)),
|
||||
controller.NewIMSController.CDRExport,
|
||||
controller.NewIMS.CDRExport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -66,17 +66,17 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
smscGroup.GET("/cdr/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewSMSCController.CDRList,
|
||||
controller.NewSMSC.CDRList,
|
||||
)
|
||||
smscGroup.DELETE("/cdr/:cdrIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smscCDR", collectlogs.BUSINESS_TYPE_DELETE)),
|
||||
controller.NewSMSCController.CDRRemove,
|
||||
controller.NewSMSC.CDRRemove,
|
||||
)
|
||||
smscGroup.POST("/cdr/export",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smscCDR", collectlogs.BUSINESS_TYPE_EXPORT)),
|
||||
controller.NewSMSCController.CDRExport,
|
||||
controller.NewSMSC.CDRExport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -85,21 +85,21 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
smfGroup.GET("/cdr/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewSMFController.CDRList,
|
||||
controller.NewSMF.CDRList,
|
||||
)
|
||||
smfGroup.DELETE("/cdr/:cdrIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smfCDR", collectlogs.BUSINESS_TYPE_DELETE)),
|
||||
controller.NewSMFController.CDRRemove,
|
||||
controller.NewSMF.CDRRemove,
|
||||
)
|
||||
smfGroup.POST("/cdr/export",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.smfCDR", collectlogs.BUSINESS_TYPE_EXPORT)),
|
||||
controller.NewSMFController.CDRExport,
|
||||
controller.NewSMF.CDRExport,
|
||||
)
|
||||
smfGroup.GET("/subscribers",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewSMFController.SubUserList,
|
||||
controller.NewSMF.SubUserList,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -108,17 +108,17 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
amfGroup.GET("/ue/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewAMFController.UEList,
|
||||
controller.NewAMF.UEList,
|
||||
)
|
||||
amfGroup.DELETE("/ue/:ueIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.amfUE", collectlogs.BUSINESS_TYPE_DELETE)),
|
||||
controller.NewAMFController.UERemove,
|
||||
controller.NewAMF.UERemove,
|
||||
)
|
||||
amfGroup.POST("/ue/export",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.amfUE", collectlogs.BUSINESS_TYPE_EXPORT)),
|
||||
controller.NewAMFController.UEExport,
|
||||
controller.NewAMF.UEExport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
upfGroup.GET("/totalFlow",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewUPFController.TotalFlow,
|
||||
controller.NewUPF.TotalFlow,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -244,17 +244,17 @@ func Setup(router *gin.Engine) {
|
||||
{
|
||||
mmeGroup.GET("/ue/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewMMEController.UEList,
|
||||
controller.NewMME.UEList,
|
||||
)
|
||||
mmeGroup.DELETE("/ue/:ueIds",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.mmeUE", collectlogs.BUSINESS_TYPE_DELETE)),
|
||||
controller.NewMMEController.UERemove,
|
||||
controller.NewMME.UERemove,
|
||||
)
|
||||
mmeGroup.POST("/ue/export",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.mmeUE", collectlogs.BUSINESS_TYPE_EXPORT)),
|
||||
controller.NewMMEController.UEExport,
|
||||
controller.NewMME.UEExport,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,194 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// 告警 数据层接口
|
||||
type IAlarm interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.AlarmQuery) map[string]any
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ids []string) []model.Alarm
|
||||
// 实例化数据层 Alarm 结构体
|
||||
var NewAlarm = &Alarm{
|
||||
selectSql: `select
|
||||
id, alarm_seq, alarm_id, alarm_title, ne_type, ne_id, alarm_code, event_time,
|
||||
alarm_type, orig_severity, perceived_severity, pv_flag, ne_name, object_uid, object_name,
|
||||
object_type, location_info, province, alarm_status, specific_problem, specific_problem_id,
|
||||
add_info, counter, latest_event_time, ack_state, ack_time, ack_user, clear_type,
|
||||
clear_time, clear_user, timestamp
|
||||
from alarm`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ids []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"alarm_seq": "AlarmSeq",
|
||||
"alarm_id": "AlarmId",
|
||||
"alarm_title": "AlarmTitle",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"alarm_code": "AlarmCode",
|
||||
"event_time": "EventTime",
|
||||
"alarm_type": "AlarmType",
|
||||
"orig_severity": "OrigSeverity",
|
||||
"perceived_severity": "PerceivedSeverity",
|
||||
"pv_flag": "PvFlag",
|
||||
"ne_name": "NeName",
|
||||
"object_uid": "ObjectUid",
|
||||
"object_name": "ObjectName",
|
||||
"object_type": "ObjectType",
|
||||
"location_info": "LocationInfo",
|
||||
"province": "Province",
|
||||
"alarm_status": "AlarmStatus",
|
||||
"specific_problem": "SpecificProblem",
|
||||
"specific_problem_id": "SpecificProblemId",
|
||||
"add_info": "AddInfo",
|
||||
"counter": "Counter",
|
||||
"latest_event_time": "LatestEventTime",
|
||||
"ack_state": "AckState",
|
||||
"ack_time": "AckTime",
|
||||
"ack_user": "AckUser",
|
||||
"clear_type": "ClearType",
|
||||
"clear_time": "ClearTime",
|
||||
"clear_user": "ClearUser",
|
||||
"timestamp": "Timestamp",
|
||||
},
|
||||
}
|
||||
|
||||
// Alarm 告警 数据层处理
|
||||
type Alarm struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *Alarm) convertResultRows(rows []map[string]any) []model.Alarm {
|
||||
arr := make([]model.Alarm, 0)
|
||||
for _, row := range rows {
|
||||
item := model.Alarm{}
|
||||
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 *Alarm) SelectPage(querys model.AlarmQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "object_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.OrigSeverity != "" {
|
||||
eventTypes := strings.Split(querys.OrigSeverity, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("orig_severity in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.Alarm{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from alarm"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *Alarm) SelectByIds(ids []string) []model.Alarm {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.Alarm{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *Alarm) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from alarm where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 AlarmImpl 结构体
|
||||
var NewAlarmImpl = &AlarmImpl{
|
||||
selectSql: `select
|
||||
id, alarm_seq, alarm_id, alarm_title, ne_type, ne_id, alarm_code, event_time,
|
||||
alarm_type, orig_severity, perceived_severity, pv_flag, ne_name, object_uid, object_name,
|
||||
object_type, location_info, province, alarm_status, specific_problem, specific_problem_id,
|
||||
add_info, counter, latest_event_time, ack_state, ack_time, ack_user, clear_type,
|
||||
clear_time, clear_user, timestamp
|
||||
from alarm`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"alarm_seq": "AlarmSeq",
|
||||
"alarm_id": "AlarmId",
|
||||
"alarm_title": "AlarmTitle",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"alarm_code": "AlarmCode",
|
||||
"event_time": "EventTime",
|
||||
"alarm_type": "AlarmType",
|
||||
"orig_severity": "OrigSeverity",
|
||||
"perceived_severity": "PerceivedSeverity",
|
||||
"pv_flag": "PvFlag",
|
||||
"ne_name": "NeName",
|
||||
"object_uid": "ObjectUid",
|
||||
"object_name": "ObjectName",
|
||||
"object_type": "ObjectType",
|
||||
"location_info": "LocationInfo",
|
||||
"province": "Province",
|
||||
"alarm_status": "AlarmStatus",
|
||||
"specific_problem": "SpecificProblem",
|
||||
"specific_problem_id": "SpecificProblemId",
|
||||
"add_info": "AddInfo",
|
||||
"counter": "Counter",
|
||||
"latest_event_time": "LatestEventTime",
|
||||
"ack_state": "AckState",
|
||||
"ack_time": "AckTime",
|
||||
"ack_user": "AckUser",
|
||||
"clear_type": "ClearType",
|
||||
"clear_time": "ClearTime",
|
||||
"clear_user": "ClearUser",
|
||||
"timestamp": "Timestamp",
|
||||
},
|
||||
}
|
||||
|
||||
// AlarmImpl 告警 数据层处理
|
||||
type AlarmImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *AlarmImpl) convertResultRows(rows []map[string]any) []model.Alarm {
|
||||
arr := make([]model.Alarm, 0)
|
||||
for _, row := range rows {
|
||||
item := model.Alarm{}
|
||||
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 *AlarmImpl) SelectPage(querys model.AlarmQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "object_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.OrigSeverity != "" {
|
||||
eventTypes := strings.Split(querys.OrigSeverity, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("orig_severity in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.Alarm{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from alarm"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *AlarmImpl) SelectByIds(ids []string) []model.Alarm {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.Alarm{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *AlarmImpl) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from alarm where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,15 +1,222 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// CDR会话事件IMS 数据层接口
|
||||
type ICDREventIMS interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventIMSQuery) map[string]any
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(cdrIds []string) []model.CDREventIMS
|
||||
// 实例化数据层 CDREvent 结构体
|
||||
var NewCDREventIMS = &CDREventIMS{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_ims c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventIMS CDR会话事件IMS 数据层处理
|
||||
type CDREventIMS struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventIMS) convertResultRows(rows []map[string]any) []model.CDREventIMS {
|
||||
arr := make([]model.CDREventIMS, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventIMS{}
|
||||
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 *CDREventIMS) SelectPage(querys model.CDREventIMSQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.CallerParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.callerParty') = ?")
|
||||
params = append(params, querys.CallerParty)
|
||||
}
|
||||
if querys.CalledParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.calledParty') = ?")
|
||||
params = append(params, querys.CalledParty)
|
||||
}
|
||||
// MySQL8支持的
|
||||
// if querys.RecordType != "" {
|
||||
// recordTypes := strings.Split(querys.RecordType, ",")
|
||||
// placeholder := repo.KeyPlaceholderByQuery(len(recordTypes))
|
||||
// conditions = append(conditions, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') in (%s)", placeholder))
|
||||
// for _, recordType := range recordTypes {
|
||||
// params = append(params, recordType)
|
||||
// }
|
||||
// }
|
||||
// Mariadb不支持json in查询改or
|
||||
if querys.RecordType != "" {
|
||||
recordTypes := strings.Split(querys.RecordType, ",")
|
||||
var querys []string
|
||||
for _, recordType := range recordTypes {
|
||||
querys = append(querys, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType))
|
||||
}
|
||||
conditions = append(conditions, "("+strings.Join(querys, " OR ")+")")
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventIMS{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_ims c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventIMS) SelectByIds(cdrIds []string) []model.CDREventIMS {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventIMS{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventIMS) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_ims where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 CDREventImpl 结构体
|
||||
var NewCDREventIMSImpl = &CDREventIMSImpl{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_ims c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventIMSImpl CDR会话事件IMS 数据层处理
|
||||
type CDREventIMSImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventIMSImpl) convertResultRows(rows []map[string]any) []model.CDREventIMS {
|
||||
arr := make([]model.CDREventIMS, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventIMS{}
|
||||
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 *CDREventIMSImpl) SelectPage(querys model.CDREventIMSQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.CallerParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.callerParty') = ?")
|
||||
params = append(params, querys.CallerParty)
|
||||
}
|
||||
if querys.CalledParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.calledParty') = ?")
|
||||
params = append(params, querys.CalledParty)
|
||||
}
|
||||
// MySQL8支持的
|
||||
// if querys.RecordType != "" {
|
||||
// recordTypes := strings.Split(querys.RecordType, ",")
|
||||
// placeholder := repo.KeyPlaceholderByQuery(len(recordTypes))
|
||||
// conditions = append(conditions, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') in (%s)", placeholder))
|
||||
// for _, recordType := range recordTypes {
|
||||
// params = append(params, recordType)
|
||||
// }
|
||||
// }
|
||||
// Mariadb不支持json in查询改or
|
||||
if querys.RecordType != "" {
|
||||
recordTypes := strings.Split(querys.RecordType, ",")
|
||||
var querys []string
|
||||
for _, recordType := range recordTypes {
|
||||
querys = append(querys, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType))
|
||||
}
|
||||
conditions = append(conditions, "("+strings.Join(querys, " OR ")+")")
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventIMS{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_ims c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventIMSImpl) SelectByIds(cdrIds []string) []model.CDREventIMS {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventIMS{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventIMSImpl) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_ims where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,15 +1,204 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// CDR会话事件SMF 数据层接口
|
||||
type ICDREventSMF interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventSMFQuery) map[string]any
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(cdrIds []string) []model.CDREventSMF
|
||||
// 实例化数据层 CDREventSMF 结构体
|
||||
var NewCDREventSMF = &CDREventSMF{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_smf c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventSMF CDR会话事件 数据层处理
|
||||
type CDREventSMF struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventSMF) convertResultRows(rows []map[string]any) []model.CDREventSMF {
|
||||
arr := make([]model.CDREventSMF, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventSMF{}
|
||||
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 *CDREventSMF) SelectPage(querys model.CDREventSMFQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.RecordType != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.recordType') = ?")
|
||||
params = append(params, querys.RecordType)
|
||||
}
|
||||
if querys.SubscriberID != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?")
|
||||
params = append(params, querys.SubscriberID)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventSMF{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_smf c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventSMF) SelectByIds(cdrIds []string) []model.CDREventSMF {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventSMF{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMF) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_smf where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 CDREventSMFImpl 结构体
|
||||
var NewCDREventSMFImpl = &CDREventSMFImpl{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_smf c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventSMFImpl CDR会话事件 数据层处理
|
||||
type CDREventSMFImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventSMFImpl) convertResultRows(rows []map[string]any) []model.CDREventSMF {
|
||||
arr := make([]model.CDREventSMF, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventSMF{}
|
||||
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 *CDREventSMFImpl) SelectPage(querys model.CDREventSMFQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.RecordType != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.recordType') = ?")
|
||||
params = append(params, querys.RecordType)
|
||||
}
|
||||
if querys.SubscriberID != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?")
|
||||
params = append(params, querys.SubscriberID)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventSMF{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_smf c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventSMFImpl) SelectByIds(cdrIds []string) []model.CDREventSMF {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventSMF{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMFImpl) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_smf where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,15 +1,223 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// CDR会话事件SMSC 数据层接口
|
||||
type ICDREventSMSC interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventSMSCQuery) map[string]any
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(cdrIds []string) []model.CDREventSMSC
|
||||
// 实例化数据层 CDREventSMSC 结构体
|
||||
var NewCDREventSMSC = &CDREventSMSC{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_smsc c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventSMSC CDR会话事件 数据层处理
|
||||
type CDREventSMSC struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventSMSC) convertResultRows(rows []map[string]any) []model.CDREventSMSC {
|
||||
arr := make([]model.CDREventSMSC, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventSMSC{}
|
||||
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 *CDREventSMSC) SelectPage(querys model.CDREventSMSCQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.CallerParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.callerParty') = ?")
|
||||
params = append(params, querys.CallerParty)
|
||||
}
|
||||
if querys.CalledParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.calledParty') = ?")
|
||||
params = append(params, querys.CalledParty)
|
||||
}
|
||||
// MySQL8支持的
|
||||
// if querys.RecordType != "" {
|
||||
// recordTypes := strings.Split(querys.RecordType, ",")
|
||||
// placeholder := repo.KeyPlaceholderByQuery(len(recordTypes))
|
||||
// conditions = append(conditions, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') in (%s)", placeholder))
|
||||
// for _, recordType := range recordTypes {
|
||||
// params = append(params, recordType)
|
||||
// }
|
||||
// }
|
||||
// Mariadb不支持json in查询改or
|
||||
if querys.RecordType != "" {
|
||||
recordTypes := strings.Split(querys.RecordType, ",")
|
||||
var queryStrArr []string
|
||||
for _, recordType := range recordTypes {
|
||||
queryStrArr = append(queryStrArr, "JSON_EXTRACT(cdr_json, '$.recordType') = ?")
|
||||
params = append(params, recordType)
|
||||
}
|
||||
conditions = append(conditions, fmt.Sprintf("( %s )", strings.Join(queryStrArr, " OR ")))
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventSMSC{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_smsc c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventSMSC) SelectByIds(cdrIds []string) []model.CDREventSMSC {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventSMSC{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMSC) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_smsc where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 CDREventSMSCImpl 结构体
|
||||
var NewCDREventSMSCImpl = &CDREventSMSCImpl{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from cdr_event_smsc c
|
||||
left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"cdr_json": "CDRJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// CDREventSMSCImpl CDR会话事件 数据层处理
|
||||
type CDREventSMSCImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *CDREventSMSCImpl) convertResultRows(rows []map[string]any) []model.CDREventSMSC {
|
||||
arr := make([]model.CDREventSMSC, 0)
|
||||
for _, row := range rows {
|
||||
item := model.CDREventSMSC{}
|
||||
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 *CDREventSMSCImpl) SelectPage(querys model.CDREventSMSCQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.CallerParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.callerParty') = ?")
|
||||
params = append(params, querys.CallerParty)
|
||||
}
|
||||
if querys.CalledParty != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.calledParty') = ?")
|
||||
params = append(params, querys.CalledParty)
|
||||
}
|
||||
// MySQL8支持的
|
||||
// if querys.RecordType != "" {
|
||||
// recordTypes := strings.Split(querys.RecordType, ",")
|
||||
// placeholder := repo.KeyPlaceholderByQuery(len(recordTypes))
|
||||
// conditions = append(conditions, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') in (%s)", placeholder))
|
||||
// for _, recordType := range recordTypes {
|
||||
// params = append(params, recordType)
|
||||
// }
|
||||
// }
|
||||
// Mariadb不支持json in查询改or
|
||||
if querys.RecordType != "" {
|
||||
recordTypes := strings.Split(querys.RecordType, ",")
|
||||
var queryStrArr []string
|
||||
for _, recordType := range recordTypes {
|
||||
queryStrArr = append(queryStrArr, "JSON_EXTRACT(cdr_json, '$.recordType') = ?")
|
||||
params = append(params, recordType)
|
||||
}
|
||||
conditions = append(conditions, fmt.Sprintf("( %s )", strings.Join(queryStrArr, " OR ")))
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "c.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.CDREventSMSC{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from cdr_event_smsc c"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *CDREventSMSCImpl) SelectByIds(cdrIds []string) []model.CDREventSMSC {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.CDREventSMSC{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMSCImpl) DeleteByIds(cdrIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
|
||||
sql := "delete from cdr_event_smsc where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cdrIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,15 +1,141 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// 性能统计 数据层接口
|
||||
type IPerfKPI interface {
|
||||
// SelectGoldKPI 通过网元指标数据信息
|
||||
SelectGoldKPI(query model.GoldKPIQuery, kpiIds []string) []map[string]any
|
||||
"be.ems/lib/log"
|
||||
"be.ems/src/framework/datasource"
|
||||
"be.ems/src/framework/logger"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
)
|
||||
|
||||
// SelectGoldKPITitle 网元对应的指标名称
|
||||
SelectGoldKPITitle(neType string) []model.GoldKPITitle
|
||||
// 实例化数据层 PerfKPI 结构体
|
||||
var NewPerfKPI = &PerfKPI{}
|
||||
|
||||
// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
|
||||
SelectUPFTotalFlow(neType, rmUID, startDate, endDate string) map[string]any
|
||||
// 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 != "" {
|
||||
rmUIDs := strings.Split(query.RmUID, ",")
|
||||
var rmUIDconditions []string
|
||||
for _, rmUID := range rmUIDs {
|
||||
rmUIDconditions = append(rmUIDconditions, "gk.rm_uid = ?")
|
||||
params = append(params, rmUID)
|
||||
}
|
||||
conditions = append(conditions, "("+strings.Join(rmUIDconditions, " or ")+")")
|
||||
log.Debugf("conditions: %s params: %v", conditions, params)
|
||||
}
|
||||
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",
|
||||
"min(CASE WHEN gk.rm_uid != '' THEN gk.rm_uid ELSE 0 END) AS rmUID",
|
||||
}
|
||||
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)
|
||||
// for multi-tenancy group by timeGroup, rm_uid support multiple upf
|
||||
querySql := fmt.Sprintf("SELECT %s FROM %s gk %s GROUP BY timeGroup, gk.rm_uid %s", fieldsSql, tableName, whereSql, orderSql)
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
log.Debugf("querySql: %s params: %v results: %v", querySql, params, results)
|
||||
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]
|
||||
}
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"be.ems/lib/log"
|
||||
"be.ems/src/framework/datasource"
|
||||
"be.ems/src/framework/logger"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 PerfKPIImpl 结构体
|
||||
var NewPerfKPIImpl = &PerfKPIImpl{}
|
||||
|
||||
// PerfKPIImpl 性能统计 数据层处理
|
||||
type PerfKPIImpl struct{}
|
||||
|
||||
// SelectGoldKPI 通过网元指标数据信息
|
||||
func (r *PerfKPIImpl) SelectGoldKPI(query model.GoldKPIQuery, kpiIds []string) []map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
var tableName string = "kpi_report_"
|
||||
if query.RmUID != "" {
|
||||
rmUIDs := strings.Split(query.RmUID, ",")
|
||||
var rmUIDconditions []string
|
||||
for _, rmUID := range rmUIDs {
|
||||
rmUIDconditions = append(rmUIDconditions, "gk.rm_uid = ?")
|
||||
params = append(params, rmUID)
|
||||
}
|
||||
conditions = append(conditions, "("+strings.Join(rmUIDconditions, " or ")+")")
|
||||
log.Debugf("conditions: %s params: %v", conditions, params)
|
||||
}
|
||||
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",
|
||||
"min(CASE WHEN gk.rm_uid != '' THEN gk.rm_uid ELSE 0 END) AS rmUID",
|
||||
}
|
||||
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)
|
||||
// for multi-tenancy group by timeGroup, rm_uid support multiple upf
|
||||
querySql := fmt.Sprintf("SELECT %s FROM %s gk %s GROUP BY timeGroup, gk.rm_uid %s", fieldsSql, tableName, whereSql, orderSql)
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
log.Debugf("querySql: %s params: %v results: %v", querySql, params, results)
|
||||
return results
|
||||
}
|
||||
|
||||
// SelectGoldKPITitle 网元对应的指标名称
|
||||
func (r *PerfKPIImpl) 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 *PerfKPIImpl) 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]
|
||||
}
|
||||
@@ -53,7 +53,8 @@ func (r *UDMAuthUser) convertResultRows(rows []map[string]any) []model.UDMAuthUs
|
||||
// ClearAndInsert 清空ne_id后新增实体
|
||||
func (r *UDMAuthUser) ClearAndInsert(neId string, uArr []model.UDMAuthUser) int64 {
|
||||
// 不指定neID时,用 TRUNCATE 清空表快
|
||||
_, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil)
|
||||
// _, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil)
|
||||
_, err := datasource.ExecDB("", "DELETE FROM u_auth_user WHERE ne_id = ?", []any{neId})
|
||||
if err != nil {
|
||||
logger.Errorf("TRUNCATE err => %v", err)
|
||||
}
|
||||
|
||||
@@ -16,26 +16,35 @@ import (
|
||||
// 实例化数据层 UDMSubUser 结构体
|
||||
var NewUDMSub = &UDMSubUser{
|
||||
selectSql: `select
|
||||
s.id, s.msisdn, s.imsi, s.ambr, s.nssai, s.rat, s.arfb, s.sar, s.cn, s.sm_data, s.smf_sel, s.eps_dat,
|
||||
s.ne_id, s.eps_flag, s.eps_odb, s.hplmn_odb, s.ard, s.epstpl, s.context_id, s.apn_context, s.static_ip,
|
||||
s.cag,
|
||||
s.id, s.imsi, s.msisdn, s.ne_id,
|
||||
s.am_dat, s.ambr, s.nssai, s.rat, s.arfb, s.sar, s.cn_type, s.rfsp_index, s.reg_timer, s.ue_usage_type, s.active_time, s.mico, s.odb_ps, s.group_id,
|
||||
s.eps_dat, s.eps_flag, s.eps_odb, s.hplmn_odb, s.ard, s.epstpl, s.context_id, s.apn_mum, s.apn_context, s.static_ip,
|
||||
s.sm_data, s.smf_sel, s.cag,
|
||||
t.tenant_id, t.tenant_name
|
||||
from u_sub_user s
|
||||
from u_sub_user s
|
||||
left join sys_tenant t on t.tenant_id = s.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"imsi": "IMSI",
|
||||
"msisdn": "MSISDN",
|
||||
"ne_id": "NeId",
|
||||
"ambr": "Ambr",
|
||||
"nssai": "Nssai",
|
||||
"rat": "Rat",
|
||||
"arfb": "Arfb",
|
||||
"sar": "Sar",
|
||||
"cn": "Cn",
|
||||
"sm_data": "SmData",
|
||||
"smf_sel": "SmfSel",
|
||||
"id": "ID",
|
||||
"imsi": "IMSI",
|
||||
"msisdn": "MSISDN",
|
||||
"ne_id": "NeId",
|
||||
|
||||
"am_dat": "AmDat",
|
||||
"ambr": "UeAmbrTpl",
|
||||
"nssai": "NssaiTpl",
|
||||
"rat": "RatRestrictions",
|
||||
"arfb": "AreaForbiddenTpl",
|
||||
"sar": "ServiceAreaRestrictionTpl",
|
||||
"cn_type": "CnTypeRestrictions",
|
||||
"rfsp_index": "RfspIndex",
|
||||
"reg_timer": "SubsRegTime",
|
||||
"ue_usage_type": "UeUsageType",
|
||||
"active_time": "ActiveTime",
|
||||
"mico": "MicoAllowed",
|
||||
"odb_ps": "OdbPs",
|
||||
"group_id": "GroupId",
|
||||
|
||||
"eps_dat": "EpsDat",
|
||||
"eps_flag": "EpsFlag",
|
||||
"eps_odb": "EpsOdb",
|
||||
@@ -43,9 +52,13 @@ var NewUDMSub = &UDMSubUser{
|
||||
"ard": "Ard",
|
||||
"epstpl": "Epstpl",
|
||||
"context_id": "ContextId",
|
||||
"apn_mum": "ApnNum",
|
||||
"apn_context": "ApnContext",
|
||||
"static_ip": "StaticIp",
|
||||
"cag": "Cag",
|
||||
|
||||
"sm_data": "SmData",
|
||||
"smf_sel": "SmfSel",
|
||||
"cag": "Cag",
|
||||
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName", // Tenant name for multi-tenancy
|
||||
@@ -76,9 +89,10 @@ func (r *UDMSubUser) convertResultRows(rows []map[string]any) []model.UDMSubUser
|
||||
}
|
||||
|
||||
// ClearAndInsert 清空ne_id后新增实体
|
||||
func (r *UDMSubUser) ClearAndInsert(neID string, u []model.UDMSubUser) int64 {
|
||||
func (r *UDMSubUser) ClearAndInsert(neId string, u []model.UDMSubUser) int64 {
|
||||
// 不指定neID时,用 TRUNCATE 清空表快
|
||||
_, err := datasource.ExecDB("", "TRUNCATE TABLE u_sub_user", nil)
|
||||
// _, err := datasource.ExecDB("", "TRUNCATE TABLE u_sub_user", nil)
|
||||
_, err := datasource.ExecDB("", "DELETE FROM u_sub_user WHERE ne_id = ?", []any{neId})
|
||||
if err != nil {
|
||||
logger.Errorf("TRUNCATE err => %v", err)
|
||||
}
|
||||
@@ -91,20 +105,15 @@ func (r *UDMSubUser) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["imsi"]; ok && v != "" {
|
||||
conditions = append(conditions, "imsi like concat(concat('%', ?), '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["msisdn"]; ok && v != "" {
|
||||
conditions = append(conditions, "msisdn like concat(concat('%', ?), '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["imsi"]; ok && v != "" {
|
||||
//conditions = append(conditions, "imsi like concat(concat('%', ?), '%')")
|
||||
//params = append(params, strings.Trim(v.(string), " "))
|
||||
conditions = append(conditions, "imsi like ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if v, ok := query["tenantName"]; ok && v != "" {
|
||||
var tenantID []string
|
||||
@@ -129,13 +138,13 @@ func (r *UDMSubUser) SelectPage(query map[string]any) map[string]any {
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "s.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
query["neId"] = ""
|
||||
}
|
||||
// if len(tenantID) > 0 {
|
||||
// conditions = append(conditions, "s.tenant_id = ?")
|
||||
// params = append(params, tenantID[0])
|
||||
// }
|
||||
}
|
||||
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
|
||||
@@ -1,15 +1,209 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// UE会话事件AMF 数据层接口
|
||||
type IUEEventAMF interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.UEEventAMFQuery) map[string]any
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ueIds []string) []model.UEEventAMF
|
||||
// 实例化数据层 UEEventAMF 结构体
|
||||
var NewUEEventAMF = &UEEventAMF{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, event_type, event_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from ue_event_amf e
|
||||
left join sys_tenant t on t.tenant_id = e.tenant_id and t.status = 1`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ueIds []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"event_type": "EventType",
|
||||
"event_json": "EventJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// UEEventAMF UE会话事件 数据层处理
|
||||
type UEEventAMF struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *UEEventAMF) convertResultRows(rows []map[string]any) []model.UEEventAMF {
|
||||
arr := make([]model.UEEventAMF, 0)
|
||||
for _, row := range rows {
|
||||
item := model.UEEventAMF{}
|
||||
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 *UEEventAMF) SelectPage(querys model.UEEventAMFQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.EventType != "" {
|
||||
eventTypes := strings.Split(querys.EventType, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("event_type in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
if querys.IMSI != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(event_json, '$.imsi') = ?")
|
||||
params = append(params, querys.IMSI)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.UEEventAMF{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ue_event_amf e"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *UEEventAMF) SelectByIds(ueIds []string) []model.UEEventAMF {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.UEEventAMF{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventAMF) DeleteByIds(ueIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
sql := "delete from ue_event_amf where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 UEEventAMFImpl 结构体
|
||||
var NewUEEventAMFImpl = &UEEventAMFImpl{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, event_type, event_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from ue_event_amf e
|
||||
left join sys_tenant t on t.tenant_id = e.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"event_type": "EventType",
|
||||
"event_json": "EventJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// UEEventAMFImpl UE会话事件 数据层处理
|
||||
type UEEventAMFImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *UEEventAMFImpl) convertResultRows(rows []map[string]any) []model.UEEventAMF {
|
||||
arr := make([]model.UEEventAMF, 0)
|
||||
for _, row := range rows {
|
||||
item := model.UEEventAMF{}
|
||||
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 *UEEventAMFImpl) SelectPage(querys model.UEEventAMFQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.EventType != "" {
|
||||
eventTypes := strings.Split(querys.EventType, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("event_type in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
if querys.IMSI != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(event_json, '$.imsi') = ?")
|
||||
params = append(params, querys.IMSI)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.UEEventAMF{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ue_event_amf e"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *UEEventAMFImpl) SelectByIds(ueIds []string) []model.UEEventAMF {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.UEEventAMF{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventAMFImpl) DeleteByIds(ueIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
sql := "delete from ue_event_amf where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,15 +1,209 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
// UE会话事件MME 数据层接口
|
||||
type IUEEventMME interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.UEEventMMEQuery) map[string]any
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ueIds []string) []model.UEEventMME
|
||||
// 实例化数据层 UEEventMME 结构体
|
||||
var NewUEEventMME = &UEEventMME{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, event_type, event_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from ue_event_mme e
|
||||
left join sys_tenant t on t.tenant_id = e.tenant_id and t.status = 1`,
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ueIds []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"event_type": "EventType",
|
||||
"event_json": "EventJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// UEEventMME UE会话事件 数据层处理
|
||||
type UEEventMME struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *UEEventMME) convertResultRows(rows []map[string]any) []model.UEEventMME {
|
||||
arr := make([]model.UEEventMME, 0)
|
||||
for _, row := range rows {
|
||||
item := model.UEEventMME{}
|
||||
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 *UEEventMME) SelectPage(querys model.UEEventMMEQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.EventType != "" {
|
||||
eventTypes := strings.Split(querys.EventType, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("event_type in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
if querys.IMSI != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(event_json, '$.imsi') = ?")
|
||||
params = append(params, querys.IMSI)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.UEEventMME{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ue_event_mme e"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *UEEventMME) SelectByIds(ueIds []string) []model.UEEventMME {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.UEEventMME{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventMME) DeleteByIds(ueIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
sql := "delete from ue_event_mme where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
dborm "be.ems/lib/core/datasource"
|
||||
"be.ems/lib/log"
|
||||
"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/network_data/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 UEEventMMEImpl 结构体
|
||||
var NewUEEventMMEImpl = &UEEventMMEImpl{
|
||||
selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, event_type, event_json, created_at,
|
||||
t.tenant_id, t.tenant_name
|
||||
from ue_event_mme e
|
||||
left join sys_tenant t on t.tenant_id = e.tenant_id and t.status = 1`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_name": "NeName",
|
||||
"rm_uid": "RmUID",
|
||||
"timestamp": "Timestamp",
|
||||
"event_type": "EventType",
|
||||
"event_json": "EventJSONStr",
|
||||
"created_at": "CreatedAt",
|
||||
"tenant_id": "TenantID",
|
||||
"tenant_name": "TenantName",
|
||||
},
|
||||
}
|
||||
|
||||
// UEEventMMEImpl UE会话事件 数据层处理
|
||||
type UEEventMMEImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *UEEventMMEImpl) convertResultRows(rows []map[string]any) []model.UEEventMME {
|
||||
arr := make([]model.UEEventMME, 0)
|
||||
for _, row := range rows {
|
||||
item := model.UEEventMME{}
|
||||
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 *UEEventMMEImpl) SelectPage(querys model.UEEventMMEQuery) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if querys.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, querys.NeType)
|
||||
}
|
||||
if querys.RmUID != "" {
|
||||
conditions = append(conditions, "rm_uid = ?")
|
||||
params = append(params, querys.RmUID)
|
||||
}
|
||||
if querys.StartTime != "" {
|
||||
conditions = append(conditions, "timestamp >= ?")
|
||||
if len(querys.StartTime) == 13 {
|
||||
querys.StartTime = querys.StartTime[:10]
|
||||
}
|
||||
params = append(params, querys.StartTime)
|
||||
}
|
||||
if querys.EndTime != "" {
|
||||
conditions = append(conditions, "timestamp <= ?")
|
||||
if len(querys.EndTime) == 13 {
|
||||
querys.EndTime = querys.EndTime[:10]
|
||||
}
|
||||
params = append(params, querys.EndTime)
|
||||
}
|
||||
if querys.EventType != "" {
|
||||
eventTypes := strings.Split(querys.EventType, ",")
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
|
||||
conditions = append(conditions, fmt.Sprintf("event_type in (%s)", placeholder))
|
||||
for _, eventType := range eventTypes {
|
||||
params = append(params, eventType)
|
||||
}
|
||||
}
|
||||
if querys.IMSI != "" {
|
||||
conditions = append(conditions, "JSON_EXTRACT(event_json, '$.imsi') = ?")
|
||||
params = append(params, querys.IMSI)
|
||||
}
|
||||
|
||||
// for multi-tenancy solution
|
||||
if querys.TenantName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_tenant").
|
||||
Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.TenantName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
} else if querys.UserName != "" {
|
||||
var tenantID string
|
||||
_, err := dborm.DefaultDB().Table("sys_user").
|
||||
Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
|
||||
if err != nil {
|
||||
log.Errorf("Get tenant_id from sys_user err => %v", err)
|
||||
}
|
||||
log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
|
||||
if tenantID != "" {
|
||||
conditions = append(conditions, "e.tenant_id = ?")
|
||||
params = append(params, tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.UEEventMME{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ue_event_mme e"
|
||||
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(querys.PageNum, querys.PageSize)
|
||||
pageSql := " limit ?,? "
|
||||
params = append(params, pageNum*pageSize)
|
||||
params = append(params, pageSize)
|
||||
|
||||
// 排序
|
||||
orderSql := ""
|
||||
if querys.SortField != "" {
|
||||
sortSql := querys.SortField
|
||||
if querys.SortOrder != "" {
|
||||
if querys.SortOrder == "desc" {
|
||||
sortSql += " desc "
|
||||
} else {
|
||||
sortSql += " asc "
|
||||
}
|
||||
}
|
||||
orderSql = fmt.Sprintf(" order by id desc, %s ", sortSql)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + orderSql + pageSql
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
result["rows"] = r.convertResultRows(results)
|
||||
return result
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *UEEventMMEImpl) SelectByIds(ueIds []string) []model.UEEventMME {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.UEEventMME{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventMMEImpl) DeleteByIds(ueIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ueIds))
|
||||
sql := "delete from ue_event_mme where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ueIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,12 +1,39 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// 告警 服务层接口
|
||||
type IAlarm interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.AlarmQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ids []string) (int64, error)
|
||||
// 实例化数据层 Alarm 结构体
|
||||
var NewAlarm = &Alarm{
|
||||
alarmRepository: repository.NewAlarm,
|
||||
}
|
||||
|
||||
// Alarm 告警 服务层处理
|
||||
type Alarm struct {
|
||||
alarmRepository *repository.Alarm // 告警数据信息
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *Alarm) SelectPage(querys model.AlarmQuery) map[string]any {
|
||||
return r.alarmRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *Alarm) DeleteByIds(ids []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
data := r.alarmRepository.SelectByIds(ids)
|
||||
if len(data) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(data) == len(ids) {
|
||||
rows := r.alarmRepository.DeleteByIds(ids)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// 实例化数据层 AlarmImpl 结构体
|
||||
var NewAlarmImpl = &AlarmImpl{
|
||||
alarmRepository: repository.NewAlarmImpl,
|
||||
}
|
||||
|
||||
// AlarmImpl 告警 服务层处理
|
||||
type AlarmImpl struct {
|
||||
// 告警数据信息
|
||||
alarmRepository repository.IAlarm
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *AlarmImpl) SelectPage(querys model.AlarmQuery) map[string]any {
|
||||
return r.alarmRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *AlarmImpl) DeleteByIds(ids []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
data := r.alarmRepository.SelectByIds(ids)
|
||||
if len(data) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(data) == len(ids) {
|
||||
rows := r.alarmRepository.DeleteByIds(ids)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -1,12 +1,39 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// CDR会话事件IMS 服务层接口
|
||||
type ICDREventIMS interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventIMSQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) (int64, error)
|
||||
// 实例化数据层 CDREventIMS 结构体
|
||||
var NewCDREventIMS = &CDREventIMS{
|
||||
cdrEventIMSRepository: repository.NewCDREventIMS,
|
||||
}
|
||||
|
||||
// CDREventImpl CDR会话事件IMS 服务层处理
|
||||
type CDREventIMS struct {
|
||||
cdrEventIMSRepository *repository.CDREventIMS // CDR会话事件数据信息
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *CDREventIMS) SelectPage(querys model.CDREventIMSQuery) map[string]any {
|
||||
return r.cdrEventIMSRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventIMS) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventIMSRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventIMSRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewCDREventIMSImpl 结构体
|
||||
var NewCDREventIMSImpl = &CDREventIMSImpl{
|
||||
cdrEventIMSRepository: repository.NewCDREventIMSImpl,
|
||||
}
|
||||
|
||||
// CDREventImpl CDR会话事件IMS 服务层处理
|
||||
type CDREventIMSImpl struct {
|
||||
// CDR会话事件数据信息
|
||||
cdrEventIMSRepository repository.ICDREventIMS
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *CDREventIMSImpl) SelectPage(querys model.CDREventIMSQuery) map[string]any {
|
||||
return r.cdrEventIMSRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventIMSImpl) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventIMSRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventIMSRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -1,12 +1,39 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// CDR会话事件SMF 服务层接口
|
||||
type ICDREventSMF interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventSMFQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) (int64, error)
|
||||
// 实例化数据层 CDREventSMF 结构体
|
||||
var NewCDREventSMF = &CDREventSMF{
|
||||
cdrEventRepository: repository.NewCDREventSMF,
|
||||
}
|
||||
|
||||
// CDREventSMF CDR会话事件SMF 服务层处理
|
||||
type CDREventSMF struct {
|
||||
cdrEventRepository *repository.CDREventSMF // CDR会话事件数据信息
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *CDREventSMF) SelectPage(querys model.CDREventSMFQuery) map[string]any {
|
||||
return r.cdrEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMF) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
var NewCDREventSMFImpl = &CDREventSMFImpl{
|
||||
cdrEventRepository: repository.NewCDREventSMFImpl,
|
||||
}
|
||||
|
||||
type CDREventSMFImpl struct {
|
||||
// CDR会话事件数据信息
|
||||
cdrEventRepository repository.ICDREventSMF
|
||||
}
|
||||
|
||||
func (r *CDREventSMFImpl) SelectPage(querys model.CDREventSMFQuery) map[string]any {
|
||||
return r.cdrEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMFImpl) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -1,12 +1,39 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// CDR会话事件SMSC 服务层接口
|
||||
type ICDREventSMSC interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.CDREventSMSCQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cdrIds []string) (int64, error)
|
||||
// 实例化数据层 CDREventSMSC 结构体
|
||||
var NewCDREventSMSC = &CDREventSMSC{
|
||||
cdrEventRepository: repository.NewCDREventSMSC,
|
||||
}
|
||||
|
||||
// CDREventSMSC CDR会话事件SMSC 服务层处理
|
||||
type CDREventSMSC struct {
|
||||
cdrEventRepository *repository.CDREventSMSC // CDR会话事件数据信息
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *CDREventSMSC) SelectPage(querys model.CDREventSMSCQuery) map[string]any {
|
||||
return r.cdrEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMSC) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
var NewCDREventSMSCImpl = &CDREventSMSCImpl{
|
||||
cdrEventRepository: repository.NewCDREventSMSCImpl,
|
||||
}
|
||||
|
||||
type CDREventSMSCImpl struct {
|
||||
// CDR会话事件数据信息
|
||||
cdrEventRepository repository.ICDREventSMSC
|
||||
}
|
||||
|
||||
func (r *CDREventSMSCImpl) SelectPage(querys model.CDREventSMSCQuery) map[string]any {
|
||||
return r.cdrEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *CDREventSMSCImpl) DeleteByIds(cdrIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.cdrEventRepository.SelectByIds(cdrIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("not data")
|
||||
}
|
||||
|
||||
if len(ids) == len(cdrIds) {
|
||||
rows := r.cdrEventRepository.DeleteByIds(cdrIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -1,15 +1,79 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
// 性能统计 服务层接口
|
||||
type IPerfKPI interface {
|
||||
// SelectGoldKPI 通过网元指标数据信息
|
||||
SelectGoldKPI(query model.GoldKPIQuery) []map[string]any
|
||||
"be.ems/src/framework/constants/cachekey"
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// SelectGoldKPITitle 网元对应的指标名称
|
||||
SelectGoldKPITitle(neType string) []model.GoldKPITitle
|
||||
|
||||
// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
|
||||
SelectUPFTotalFlow(neType, rmUID string, day int) map[string]any
|
||||
// 实例化数据层 PerfKPI 结构体
|
||||
var NewPerfKPI = &PerfKPI{
|
||||
perfKPIRepository: repository.NewPerfKPI,
|
||||
}
|
||||
|
||||
// PerfKPI 性能统计 服务层处理
|
||||
type PerfKPI struct {
|
||||
perfKPIRepository *repository.PerfKPI // 性能统计数据信息
|
||||
}
|
||||
|
||||
// SelectGoldKPI 通过网元指标数据信息
|
||||
func (r *PerfKPI) SelectGoldKPI(query model.GoldKPIQuery) []map[string]any {
|
||||
// 获取数据指标id
|
||||
var kpiIds []string
|
||||
kpiTitles := r.perfKPIRepository.SelectGoldKPITitle(query.NeType)
|
||||
for _, kpiId := range kpiTitles {
|
||||
kpiIds = append(kpiIds, kpiId.KPIID)
|
||||
}
|
||||
|
||||
data := r.perfKPIRepository.SelectGoldKPI(query, kpiIds)
|
||||
if data == nil {
|
||||
return []map[string]any{}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// SelectGoldKPITitle 网元对应的指标名称
|
||||
func (r *PerfKPI) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
|
||||
return r.perfKPIRepository.SelectGoldKPITitle(neType)
|
||||
}
|
||||
|
||||
// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
|
||||
func (r *PerfKPI) SelectUPFTotalFlow(neType, rmUID string, day int) map[string]any {
|
||||
now := time.Now()
|
||||
// 获取当前日期
|
||||
endDate := fmt.Sprint(now.UnixMilli())
|
||||
// 将当前日期前几天数
|
||||
startDate := fmt.Sprint(now.AddDate(0, 0, -day).Truncate(24 * time.Hour).UnixMilli())
|
||||
|
||||
var info map[string]any
|
||||
|
||||
// 读取缓存数据 小于2分钟重新缓存
|
||||
key := fmt.Sprintf("%sUPF:totalFlow:%s_%d", cachekey.NE_DATA_KEY, rmUID, day)
|
||||
infoStr, _ := redis.Get("", key)
|
||||
if infoStr != "" {
|
||||
json.Unmarshal([]byte(infoStr), &info)
|
||||
expireSecond, _ := redis.GetExpire("", key)
|
||||
if expireSecond > 120 {
|
||||
return info
|
||||
}
|
||||
}
|
||||
// down * 8 / 1000 / 1000 单位M
|
||||
info = r.perfKPIRepository.SelectUPFTotalFlow(neType, rmUID, startDate, endDate)
|
||||
if v, ok := info["up"]; ok && v == nil {
|
||||
info["up"] = 0
|
||||
}
|
||||
if v, ok := info["down"]; ok && v == nil {
|
||||
info["down"] = 0
|
||||
}
|
||||
|
||||
// 保存到缓存
|
||||
infoJSON, _ := json.Marshal(info)
|
||||
redis.SetByExpire("", key, string(infoJSON), time.Duration(10)*time.Minute)
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/constants/cachekey"
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// 实例化数据层 PerfKPIImpl 结构体
|
||||
var NewPerfKPIImpl = &PerfKPIImpl{
|
||||
perfKPIRepository: repository.NewPerfKPIImpl,
|
||||
}
|
||||
|
||||
// PerfKPIImpl 性能统计 服务层处理
|
||||
type PerfKPIImpl struct {
|
||||
// 性能统计数据信息
|
||||
perfKPIRepository repository.IPerfKPI
|
||||
}
|
||||
|
||||
// SelectGoldKPI 通过网元指标数据信息
|
||||
func (r *PerfKPIImpl) SelectGoldKPI(query model.GoldKPIQuery) []map[string]any {
|
||||
// 获取数据指标id
|
||||
var kpiIds []string
|
||||
kpiTitles := r.perfKPIRepository.SelectGoldKPITitle(query.NeType)
|
||||
for _, kpiId := range kpiTitles {
|
||||
kpiIds = append(kpiIds, kpiId.KPIID)
|
||||
}
|
||||
|
||||
data := r.perfKPIRepository.SelectGoldKPI(query, kpiIds)
|
||||
if data == nil {
|
||||
return []map[string]any{}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// SelectGoldKPITitle 网元对应的指标名称
|
||||
func (r *PerfKPIImpl) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
|
||||
return r.perfKPIRepository.SelectGoldKPITitle(neType)
|
||||
}
|
||||
|
||||
// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
|
||||
func (r *PerfKPIImpl) SelectUPFTotalFlow(neType, rmUID string, day int) map[string]any {
|
||||
now := time.Now()
|
||||
// 获取当前日期
|
||||
endDate := fmt.Sprint(now.UnixMilli())
|
||||
// 将当前日期前几天数
|
||||
startDate := fmt.Sprint(now.AddDate(0, 0, -day).Truncate(24 * time.Hour).UnixMilli())
|
||||
|
||||
var info map[string]any
|
||||
|
||||
// 读取缓存数据 小于2分钟重新缓存
|
||||
key := fmt.Sprintf("%sUPF:totalFlow:%s_%d", cachekey.NE_DATA_KEY, rmUID, day)
|
||||
infoStr, _ := redis.Get("", key)
|
||||
if infoStr != "" {
|
||||
json.Unmarshal([]byte(infoStr), &info)
|
||||
expireSecond, _ := redis.GetExpire("", key)
|
||||
if expireSecond > 120 {
|
||||
return info
|
||||
}
|
||||
}
|
||||
|
||||
info = r.perfKPIRepository.SelectUPFTotalFlow(neType, rmUID, startDate, endDate)
|
||||
if v, ok := info["up"]; ok && v == nil {
|
||||
info["up"] = 0
|
||||
}
|
||||
if v, ok := info["down"]; ok && v == nil {
|
||||
info["down"] = 0
|
||||
}
|
||||
|
||||
// 保存到缓存
|
||||
infoJSON, _ := json.Marshal(info)
|
||||
redis.SetByExpire("", key, string(infoJSON), time.Duration(10)*time.Minute)
|
||||
|
||||
return info
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
neService "be.ems/src/modules/network_element/service"
|
||||
)
|
||||
|
||||
// 实例化服务层 UDMAuthUser 结构体
|
||||
@@ -25,12 +26,25 @@ type UDMAuthUser struct {
|
||||
func (r *UDMAuthUser) dataByRedis(imsi, neId string) []model.UDMAuthUser {
|
||||
arr := []model.UDMAuthUser{}
|
||||
key := fmt.Sprintf("ausf:%s", imsi)
|
||||
ausfArr, err := redis.GetKeys("udmuser", key)
|
||||
source := fmt.Sprintf("UDM_%s", neId)
|
||||
|
||||
// 网元主机的Redis客户端
|
||||
redisClient, err := neService.NewNeInfo.NeRunRedisClient("UDM", neId)
|
||||
if err != nil {
|
||||
return arr
|
||||
}
|
||||
defer func() {
|
||||
redisClient.Close()
|
||||
redis.ConnectPush(source, nil)
|
||||
}()
|
||||
redis.ConnectPush(source, redisClient.Client)
|
||||
|
||||
ausfArr, err := redis.GetKeys(source, key)
|
||||
if err != nil {
|
||||
return arr
|
||||
}
|
||||
for _, key := range ausfArr {
|
||||
m, err := redis.GetHash("udmuser", key)
|
||||
m, err := redis.GetHash(source, key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -69,21 +83,16 @@ func (r *UDMAuthUser) ResetData(neId string) int64 {
|
||||
|
||||
// ParseInfo 解析单个用户imsi鉴权信息 data从命令MML得到的结果
|
||||
func (r *UDMAuthUser) ParseInfo(imsi, neId string, data map[string]string) model.UDMAuthUser {
|
||||
u := model.UDMAuthUser{
|
||||
IMSI: imsi,
|
||||
NeId: neId,
|
||||
Amf: data["amf"],
|
||||
Status: "1",
|
||||
Ki: data["ki"],
|
||||
AlgoIndex: data["algo"],
|
||||
Opc: data["opc"],
|
||||
}
|
||||
u := r.udmAuthRepository.SelectByIMSIAndNeID(imsi, neId)
|
||||
|
||||
// 补充用户ID用于更新
|
||||
auth := r.udmAuthRepository.SelectByIMSIAndNeID(imsi, neId)
|
||||
if auth.IMSI == imsi {
|
||||
u.ID = auth.ID
|
||||
}
|
||||
// 用于更新
|
||||
u.IMSI = imsi
|
||||
u.NeId = neId
|
||||
u.Amf = data["amf"]
|
||||
u.Ki = data["ki"]
|
||||
u.AlgoIndex = data["algo"]
|
||||
u.Opc = data["opc"]
|
||||
u.Status = "1"
|
||||
return u
|
||||
}
|
||||
|
||||
@@ -170,3 +179,22 @@ func (r *UDMAuthUser) LoadData(neId, imsi, num string) {
|
||||
r.udmAuthRepository.Inserts(arr)
|
||||
}
|
||||
}
|
||||
|
||||
// ParseCommandParams 解析数据组成命令参数 ki=xx,xx=xx,...
|
||||
func (r *UDMAuthUser) ParseCommandParams(item model.UDMAuthUser) string {
|
||||
var conditions []string
|
||||
if item.Ki != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("ki=%s", item.Ki))
|
||||
}
|
||||
|
||||
if item.Amf != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("amf=%s", item.Amf))
|
||||
}
|
||||
if item.AlgoIndex != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("algo=%s", item.AlgoIndex))
|
||||
}
|
||||
if item.Opc != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("opc=%s", item.Opc))
|
||||
}
|
||||
return strings.Join(conditions, ",")
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
neService "be.ems/src/modules/network_element/service"
|
||||
)
|
||||
|
||||
// 实例化服务层 UDMSubUser 结构体
|
||||
@@ -18,22 +19,33 @@ var NewUDMSub = &UDMSubUser{
|
||||
|
||||
// UDM签约信息 服务层处理
|
||||
type UDMSubUser struct {
|
||||
// UDM签约信息数据信息
|
||||
udmSubRepository *repository.UDMSubUser
|
||||
// UDM用户IMSI信息数据信息
|
||||
udmUserInfoRepository *repository.UDMUserInfo
|
||||
udmSubRepository *repository.UDMSubUser // UDM签约信息数据信息
|
||||
udmUserInfoRepository *repository.UDMUserInfo // UDM用户IMSI信息数据信息
|
||||
}
|
||||
|
||||
// dataByRedis UDM签约用户 db:0 中 udm-sd:*
|
||||
func (r *UDMSubUser) dataByRedis(imsi, neId string) []model.UDMSubUser {
|
||||
arr := []model.UDMSubUser{}
|
||||
key := fmt.Sprintf("udm-sd:%s", imsi)
|
||||
udmsdArr, err := redis.GetKeys("udmuser", key)
|
||||
source := fmt.Sprintf("UDM_%s", neId)
|
||||
|
||||
// 网元主机的Redis客户端
|
||||
redisClient, err := neService.NewNeInfo.NeRunRedisClient("UDM", neId)
|
||||
if err != nil {
|
||||
return arr
|
||||
}
|
||||
defer func() {
|
||||
redisClient.Close()
|
||||
redis.ConnectPush(source, nil)
|
||||
}()
|
||||
redis.ConnectPush(source, redisClient.Client)
|
||||
|
||||
udmsdArr, err := redis.GetKeys(source, key)
|
||||
if err != nil {
|
||||
return arr
|
||||
}
|
||||
for _, key := range udmsdArr {
|
||||
m, err := redis.GetHash("udmuser", key)
|
||||
m, err := redis.GetHash(source, key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -50,12 +62,29 @@ func (r *UDMSubUser) dataByRedis(imsi, neId string) []model.UDMSubUser {
|
||||
// def_ambr,def_nssai,0,def_arfb,def_sar,3,1,12000,1,1000,0,1,-
|
||||
if v, ok := m["am-dat"]; ok {
|
||||
arr := strings.Split(v, ",")
|
||||
a.Ambr = arr[0]
|
||||
a.Nssai = arr[1]
|
||||
a.Rat = arr[2]
|
||||
a.Arfb = arr[3]
|
||||
a.Sar = arr[4]
|
||||
a.Cn = arr[5]
|
||||
a.AmDat = v
|
||||
a.UeAmbrTpl = arr[0]
|
||||
a.NssaiTpl = arr[1]
|
||||
a.RatRestrictions = arr[2]
|
||||
a.AreaForbiddenTpl = arr[3]
|
||||
a.ServiceAreaRestrictionTpl = arr[4]
|
||||
a.CnTypeRestrictions = arr[5]
|
||||
a.RfspIndex = arr[6]
|
||||
a.SubsRegTime = arr[7]
|
||||
a.UeUsageType = arr[8]
|
||||
a.ActiveTime = arr[9]
|
||||
a.MicoAllowed = "0" // arr[10]
|
||||
a.OdbPs = "1" // arr[11]
|
||||
a.GroupId = "-" // arr[12]
|
||||
if len(arr) > 10 {
|
||||
a.MicoAllowed = arr[10]
|
||||
}
|
||||
if len(arr) > 11 {
|
||||
a.OdbPs = arr[11]
|
||||
}
|
||||
if len(arr) > 12 && arr[12] != "-" {
|
||||
a.GroupId = arr[12]
|
||||
}
|
||||
}
|
||||
// 1,64,24,65,def_eps,1,2,010200000000,-
|
||||
if v, ok := m["eps-dat"]; ok {
|
||||
@@ -71,9 +100,11 @@ func (r *UDMSubUser) dataByRedis(imsi, neId string) []model.UDMSubUser {
|
||||
a.Ard = arr[3]
|
||||
a.Epstpl = arr[4]
|
||||
a.ContextId = arr[5]
|
||||
a.ApnNum = arr[6] // 导入和导出不用
|
||||
a.ApnContext = arr[7]
|
||||
// [6] 是不要的,导入和导出不用
|
||||
a.StaticIp = arr[8]
|
||||
if len(arr) >= 9 {
|
||||
a.StaticIp = arr[8]
|
||||
}
|
||||
}
|
||||
|
||||
arr = append(arr, a)
|
||||
@@ -91,27 +122,30 @@ func (r *UDMSubUser) ResetData(neId string) int64 {
|
||||
|
||||
// ParseInfo 解析单个用户imsi签约信息 data从命令MML得到的结果
|
||||
func (r *UDMSubUser) ParseInfo(imsi, neId string, data map[string]string) model.UDMSubUser {
|
||||
cnType, _ := strconv.ParseInt(data["CNType"][:4], 0, 64)
|
||||
rat, _ := strconv.ParseInt(data["RAT"][:4], 0, 64)
|
||||
u := r.udmSubRepository.SelectByIMSIAndNeID(imsi, neId)
|
||||
|
||||
cnType, _ := strconv.ParseInt(data["CNType"][:4], 0, 64) // 0x03(EPC|5GC)
|
||||
rat, _ := strconv.ParseInt(data["RAT"][:4], 0, 64) // 0x00(VIRTUAL|WLAN|EUTRA|NR)
|
||||
msisdn := data["MSISDN"]
|
||||
if imsMsisdnLen := strings.Index(msisdn, ","); imsMsisdnLen != -1 {
|
||||
msisdn = msisdn[:imsMsisdnLen]
|
||||
}
|
||||
|
||||
u := model.UDMSubUser{
|
||||
IMSI: imsi,
|
||||
MSISDN: msisdn,
|
||||
NeId: neId,
|
||||
Ambr: data["AMBR"],
|
||||
Arfb: data["AreaForbidden"],
|
||||
Cn: fmt.Sprint(cnType),
|
||||
SmData: data["SM-Data(snssai+dnn[1..n])"],
|
||||
Sar: data["ServiceAreaRestriction"],
|
||||
Nssai: data["NSSAI"],
|
||||
SmfSel: data["Smf-Selection"],
|
||||
Cag: data["cag"],
|
||||
Rat: fmt.Sprint(rat),
|
||||
}
|
||||
// 用于更新
|
||||
u.IMSI = imsi
|
||||
u.MSISDN = msisdn
|
||||
u.NeId = neId
|
||||
u.UeAmbrTpl = data["AMBR"]
|
||||
u.NssaiTpl = data["NSSAI"]
|
||||
u.AreaForbiddenTpl = data["AreaForbidden"]
|
||||
u.ServiceAreaRestrictionTpl = data["ServiceAreaRestriction"]
|
||||
u.CnTypeRestrictions = fmt.Sprint(cnType)
|
||||
u.RatRestrictions = fmt.Sprint(rat)
|
||||
u.MicoAllowed = data["MICO"]
|
||||
u.SmData = data["SM-Data(snssai+dnn[1..n])"]
|
||||
u.SmfSel = data["Smf-Selection"]
|
||||
u.Cag = data["cag"]
|
||||
|
||||
// 1,64,24,65,def_eps,1,2,010200000000,-
|
||||
if v, ok := data["EPS-Data"]; ok {
|
||||
u.EpsDat = v
|
||||
@@ -122,16 +156,11 @@ func (r *UDMSubUser) ParseInfo(imsi, neId string, data map[string]string) model.
|
||||
u.Ard = arr[3]
|
||||
u.Epstpl = arr[4]
|
||||
u.ContextId = arr[5]
|
||||
u.ApnNum = arr[6] // 导入和导出不用
|
||||
u.ApnContext = arr[7]
|
||||
// [6] 是不要的,导入和导出不用
|
||||
u.StaticIp = arr[8]
|
||||
}
|
||||
|
||||
// 补充用户ID用于更新
|
||||
sub := r.udmSubRepository.SelectByIMSIAndNeID(imsi, neId)
|
||||
if sub.IMSI == imsi {
|
||||
u.ID = sub.ID
|
||||
}
|
||||
// 补充用户拓展信息
|
||||
info := r.udmUserInfoRepository.SelectByIMSIAndNeID(imsi, neId)
|
||||
if info.IMSI == imsi {
|
||||
@@ -252,3 +281,75 @@ func (r *UDMSubUser) LoadData(neId, imsi, num, remark string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ParseCommandParams 解析数据组成命令参数 msisdn=xx,xx=xx,...
|
||||
func (r *UDMSubUser) ParseCommandParams(item model.UDMSubUser) string {
|
||||
var conditions []string
|
||||
if item.MSISDN != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("msisdn=%s", item.MSISDN))
|
||||
}
|
||||
|
||||
// AmData
|
||||
if item.UeAmbrTpl != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("ambr=%s", item.UeAmbrTpl))
|
||||
}
|
||||
if item.NssaiTpl != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("nssai=%s", item.NssaiTpl))
|
||||
}
|
||||
if item.AreaForbiddenTpl != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("arfb=%s", item.AreaForbiddenTpl))
|
||||
}
|
||||
if item.ServiceAreaRestrictionTpl != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("sar=%s", item.ServiceAreaRestrictionTpl))
|
||||
}
|
||||
if item.RatRestrictions != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("rat=%s", item.RatRestrictions))
|
||||
}
|
||||
if item.CnTypeRestrictions != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("cn=%s", item.CnTypeRestrictions))
|
||||
}
|
||||
if item.MicoAllowed != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("mico=%s", item.MicoAllowed))
|
||||
}
|
||||
|
||||
// EpsDat
|
||||
// if item.EpsDat != "" {
|
||||
// conditions = append(conditions, fmt.Sprintf("eps_dat=%s", item.EpsDat))
|
||||
// }
|
||||
if item.EpsFlag != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("eps_flag=%s", item.EpsFlag))
|
||||
}
|
||||
if item.EpsOdb != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("eps_odb=%s", item.EpsOdb))
|
||||
}
|
||||
if item.HplmnOdb != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("hplmn_odb=%s", item.HplmnOdb))
|
||||
}
|
||||
if item.Epstpl != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("epstpl=%s", item.Epstpl))
|
||||
}
|
||||
if item.Ard != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("ard=%s", item.Ard))
|
||||
}
|
||||
if item.ContextId != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("context_id=%s", item.ContextId))
|
||||
}
|
||||
if item.ApnContext != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("apn_context=%s", item.ApnContext))
|
||||
}
|
||||
if item.StaticIp != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("static_ip=%s", item.StaticIp))
|
||||
}
|
||||
|
||||
// 其他
|
||||
if item.SmfSel != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("smf_sel=%s", item.SmfSel))
|
||||
}
|
||||
if item.SmData != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("sm_data=%s", item.SmData))
|
||||
}
|
||||
if item.Cag != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("cag=%s", item.Cag))
|
||||
}
|
||||
return strings.Join(conditions, ",")
|
||||
}
|
||||
|
||||
@@ -1,12 +1,40 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// UE会话事件AMF 服务层接口
|
||||
type IUEEventAMF interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.UEEventAMFQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ueIds []string) (int64, error)
|
||||
// 实例化数据层 UEEventAMF 结构体
|
||||
var NewUEEventAMF = &UEEventAMF{
|
||||
ueEventRepository: repository.NewUEEventAMF,
|
||||
}
|
||||
|
||||
// UEEventAMF UE会话事件AMF 服务层处理
|
||||
type UEEventAMF struct {
|
||||
// UE会话事件数据信息
|
||||
ueEventRepository *repository.UEEventAMF
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *UEEventAMF) SelectPage(querys model.UEEventAMFQuery) map[string]any {
|
||||
return r.ueEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventAMF) DeleteByIds(ueIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.ueEventRepository.SelectByIds(ueIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(ids) == len(ueIds) {
|
||||
rows := r.ueEventRepository.DeleteByIds(ueIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// 实例化数据层 UEEventMMEImpl 结构体
|
||||
var NewUEEventMMEImpl = &UEEventMMEImpl{
|
||||
ueEventRepository: repository.NewUEEventMMEImpl,
|
||||
}
|
||||
|
||||
// UEEventMMEImpl UE会话事件MME 服务层处理
|
||||
type UEEventMMEImpl struct {
|
||||
// UE会话事件数据信息
|
||||
ueEventRepository repository.IUEEventMME
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *UEEventMMEImpl) SelectPage(querys model.UEEventMMEQuery) map[string]any {
|
||||
return r.ueEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventMMEImpl) DeleteByIds(ueIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.ueEventRepository.SelectByIds(ueIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(ids) == len(ueIds) {
|
||||
rows := r.ueEventRepository.DeleteByIds(ueIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -1,12 +1,39 @@
|
||||
package service
|
||||
|
||||
import "be.ems/src/modules/network_data/model"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
// UE会话事件MME 服务层接口
|
||||
type IUEEventMME interface {
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(querys model.UEEventMMEQuery) map[string]any
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ueIds []string) (int64, error)
|
||||
// 实例化数据层 UEEventMME 结构体
|
||||
var NewUEEventMME = &UEEventMME{
|
||||
ueEventRepository: repository.NewUEEventMME,
|
||||
}
|
||||
|
||||
// UEEventMME UE会话事件MME 服务层处理
|
||||
type UEEventMME struct {
|
||||
ueEventRepository *repository.UEEventMME // UE会话事件数据信息
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *UEEventMME) SelectPage(querys model.UEEventMMEQuery) map[string]any {
|
||||
return r.ueEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventMME) DeleteByIds(ueIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.ueEventRepository.SelectByIds(ueIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(ids) == len(ueIds) {
|
||||
rows := r.ueEventRepository.DeleteByIds(ueIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/modules/network_data/model"
|
||||
"be.ems/src/modules/network_data/repository"
|
||||
)
|
||||
|
||||
// 实例化数据层 UEEventAMFImpl 结构体
|
||||
var NewUEEventAMFImpl = &UEEventAMFImpl{
|
||||
ueEventRepository: repository.NewUEEventAMFImpl,
|
||||
}
|
||||
|
||||
// UEEventAMFImpl UE会话事件AMF 服务层处理
|
||||
type UEEventAMFImpl struct {
|
||||
// UE会话事件数据信息
|
||||
ueEventRepository repository.IUEEventAMF
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *UEEventAMFImpl) SelectPage(querys model.UEEventAMFQuery) map[string]any {
|
||||
return r.ueEventRepository.SelectPage(querys)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *UEEventAMFImpl) DeleteByIds(ueIds []string) (int64, error) {
|
||||
// 检查是否存在
|
||||
ids := r.ueEventRepository.SelectByIds(ueIds)
|
||||
if len(ids) <= 0 {
|
||||
return 0, fmt.Errorf("no data")
|
||||
}
|
||||
|
||||
if len(ids) == len(ueIds) {
|
||||
rows := r.ueEventRepository.DeleteByIds(ueIds)
|
||||
return rows, nil
|
||||
}
|
||||
// 删除信息失败!
|
||||
return 0, fmt.Errorf("delete fail")
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
|
||||
// 实例化控制层 NeActionController 结构体
|
||||
var NewNeAction = &NeActionController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// 网元处理请求
|
||||
@@ -28,10 +28,10 @@ var NewNeAction = &NeActionController{
|
||||
// PATH /action
|
||||
type NeActionController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
neInfoService *neService.NeInfo
|
||||
}
|
||||
|
||||
// 发送文件从本地到网元
|
||||
// 从本地到网元发送文件
|
||||
//
|
||||
// POST /pushFile
|
||||
func (s *NeActionController) PushFile(c *gin.Context) {
|
||||
@@ -88,7 +88,7 @@ func (s *NeActionController) PushFile(c *gin.Context) {
|
||||
c.JSON(200, result.OkData(filepath.ToSlash(neFilePath)))
|
||||
}
|
||||
|
||||
// 获取文件从网元到本地
|
||||
// 从网元到本地获取文件
|
||||
//
|
||||
// GET /pullFile
|
||||
func (s *NeActionController) PullFile(c *gin.Context) {
|
||||
@@ -147,6 +147,116 @@ func (s *NeActionController) PullFile(c *gin.Context) {
|
||||
c.FileAttachment(localFilePath, fileName)
|
||||
}
|
||||
|
||||
// 从网元到本地获取目录压缩为ZIP
|
||||
//
|
||||
// GET /pullDirZip
|
||||
func (s *NeActionController) PullDirZip(c *gin.Context) {
|
||||
language := ctx.AcceptLanguage(c)
|
||||
var querys struct {
|
||||
NeType string `form:"neType" binding:"required"`
|
||||
NeID string `form:"neId" binding:"required"`
|
||||
Path string `form:"path" binding:"required"`
|
||||
DelTemp bool `form:"delTemp"` // 删除本地临时文件
|
||||
}
|
||||
if err := c.ShouldBindQuery(&querys); err != nil {
|
||||
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
|
||||
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
|
||||
}
|
||||
|
||||
// 网元主机的SSH客户端
|
||||
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
defer sshClient.Close()
|
||||
// 网元主机的SSH客户端进行文件传输
|
||||
sftpClient, err := sshClient.NewClientSFTP()
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
defer sftpClient.Close()
|
||||
|
||||
nePath := querys.Path
|
||||
dirName := generate.Code(6)
|
||||
localFilePath := filepath.Join("/tmp/omc/pull/", dirName)
|
||||
if runtime.GOOS == "windows" {
|
||||
localFilePath = fmt.Sprintf("C:%s", localFilePath)
|
||||
}
|
||||
// 复制到本地
|
||||
localDirFilePath := filepath.Join(localFilePath, "zip")
|
||||
if err = sftpClient.CopyDirRemoteToLocal(nePath, localDirFilePath); err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 压缩zip文件名
|
||||
zipFileName := fmt.Sprintf("%s-%s-%s.zip", neInfo.NeType, neInfo.NeId, dirName)
|
||||
zipFilePath := filepath.Join(localFilePath, zipFileName)
|
||||
if err := file.CompressZipByDir(zipFilePath, localDirFilePath); err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if querys.DelTemp {
|
||||
_ = os.RemoveAll(localFilePath)
|
||||
}
|
||||
}()
|
||||
c.FileAttachment(zipFilePath, zipFileName)
|
||||
}
|
||||
|
||||
// 查看网元端文件内容
|
||||
//
|
||||
// GET /viewFile
|
||||
func (s *NeActionController) ViewFile(c *gin.Context) {
|
||||
language := ctx.AcceptLanguage(c)
|
||||
var querys struct {
|
||||
NeType string `form:"neType" binding:"required"`
|
||||
NeID string `form:"neId" binding:"required"`
|
||||
Path string `form:"path" binding:"required"`
|
||||
FileName string `form:"fileName" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindQuery(&querys); err != nil {
|
||||
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
|
||||
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
|
||||
}
|
||||
|
||||
// 网元主机的SSH客户端
|
||||
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
|
||||
if err != nil {
|
||||
c.JSON(200, result.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
defer sshClient.Close()
|
||||
|
||||
// 网元端文件
|
||||
nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName))
|
||||
// 网元端临时目录
|
||||
output, err := sshClient.RunCMD(fmt.Sprintf("cat %s", nePath))
|
||||
output = strings.TrimSpace(output)
|
||||
if err != nil || strings.HasPrefix(output, "ls: ") {
|
||||
c.JSON(200, result.ErrMsg(i18n.TKey(language, "file view cat error")))
|
||||
return
|
||||
}
|
||||
c.JSON(200, result.OkData(output))
|
||||
}
|
||||
|
||||
// 网元端文件列表
|
||||
//
|
||||
// GET /files
|
||||
@@ -181,13 +291,12 @@ func (s *NeActionController) Files(c *gin.Context) {
|
||||
defer sshClient.Close()
|
||||
|
||||
// 获取文件列表
|
||||
totalSize, rows, err := ssh.FileList(sshClient, querys.Path, querys.Search)
|
||||
rows, err := ssh.FileList(sshClient, querys.Path, querys.Search)
|
||||
if err != nil {
|
||||
c.JSON(200, result.Ok(map[string]any{
|
||||
"path": querys.Path,
|
||||
"totalSize": totalSize,
|
||||
"total": len(rows),
|
||||
"rows": []ssh.FileListRow{},
|
||||
"path": querys.Path,
|
||||
"total": len(rows),
|
||||
"rows": []ssh.FileListRow{},
|
||||
}))
|
||||
return
|
||||
}
|
||||
@@ -206,10 +315,9 @@ func (s *NeActionController) Files(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(200, result.Ok(map[string]any{
|
||||
"path": querys.Path,
|
||||
"totalSize": totalSize,
|
||||
"total": lenNum,
|
||||
"rows": splitRows,
|
||||
"path": querys.Path,
|
||||
"total": lenNum,
|
||||
"rows": splitRows,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -18,18 +18,16 @@ import (
|
||||
|
||||
// NewNeConfig 网元参数配置 实例化控制层
|
||||
var NewNeConfig = &NeConfigController{
|
||||
neConfigService: neService.NewNeConfigImpl,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neConfigService: neService.NewNeConfig,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// 网元参数配置
|
||||
//
|
||||
// PATH /config
|
||||
type NeConfigController struct {
|
||||
// 网元参数配置可用属性值服务
|
||||
neConfigService neService.INeConfig
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
neConfigService *neService.NeConfig // 网元参数配置可用属性值服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
}
|
||||
|
||||
// 网元参数配置可用属性值列表
|
||||
|
||||
@@ -18,18 +18,16 @@ import (
|
||||
|
||||
// NewNeConfigBackup 实例化控制层 NeConfigBackupController 结构体
|
||||
var NewNeConfigBackup = &NeConfigBackupController{
|
||||
neConfigBackupService: neService.NewNeConfigBackupImpl,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neConfigBackupService: neService.NewNeConfigBackup,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// 网元配置文件备份记录
|
||||
//
|
||||
// PATH /config/backup
|
||||
type NeConfigBackupController struct {
|
||||
// 网元配置文件备份记录服务
|
||||
neConfigBackupService neService.INeConfigBackup
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
neConfigBackupService *neService.NeConfigBackup // 网元配置文件备份记录服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
}
|
||||
|
||||
// 网元配置文件备份记录列表
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/redis"
|
||||
"be.ems/src/framework/telnet"
|
||||
"be.ems/src/framework/utils/ctx"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
@@ -17,15 +18,14 @@ import (
|
||||
|
||||
// 实例化控制层 NeHostController 结构体
|
||||
var NewNeHost = &NeHostController{
|
||||
neHostService: neService.NewNeHostImpl,
|
||||
neHostService: neService.NewNeHost,
|
||||
}
|
||||
|
||||
// 网元主机连接请求
|
||||
//
|
||||
// PATH /host
|
||||
type NeHostController struct {
|
||||
// 网元主机连接服务
|
||||
neHostService neService.INeHost
|
||||
neHostService *neService.NeHost // 网元主机连接服务
|
||||
}
|
||||
|
||||
// 网元主机列表
|
||||
@@ -212,6 +212,21 @@ func (s *NeHostController) Test(c *gin.Context) {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if body.HostType == "redis" {
|
||||
var connRedis redis.ConnRedis
|
||||
body.CopyTo(&connRedis)
|
||||
|
||||
client, err := connRedis.NewClient()
|
||||
if err != nil {
|
||||
// 连接主机失败,请检查连接参数后重试
|
||||
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
c.JSON(200, result.Ok(nil))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 网元主机发送命令
|
||||
|
||||
@@ -15,15 +15,14 @@ import (
|
||||
|
||||
// 实例化控制层 NeHostCmdController 结构体
|
||||
var NewNeHostCmd = &NeHostCmdController{
|
||||
neHostCmdService: neService.NewNeHostCmdImpl,
|
||||
neHostCmdService: neService.NewNeHostCmd,
|
||||
}
|
||||
|
||||
// 网元主机命令请求
|
||||
//
|
||||
// PATH /hostCmd
|
||||
type NeHostCmdController struct {
|
||||
// 网元主机命令服务
|
||||
neHostCmdService neService.INeHostCmd
|
||||
neHostCmdService *neService.NeHostCmd // 网元主机命令服务
|
||||
}
|
||||
|
||||
// 网元主机命令列表
|
||||
|
||||
@@ -18,8 +18,8 @@ import (
|
||||
|
||||
// 实例化控制层 NeInfoController 结构体
|
||||
var NewNeInfo = &NeInfoController{
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neLicenseService: neService.NewNeLicenseImpl,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
neLicenseService: neService.NewNeLicense,
|
||||
neVersionService: neService.NewNeVersion,
|
||||
}
|
||||
|
||||
@@ -27,12 +27,9 @@ var NewNeInfo = &NeInfoController{
|
||||
//
|
||||
// PATH /info
|
||||
type NeInfoController struct {
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
// 网元授权激活信息服务
|
||||
neLicenseService neService.INeLicense
|
||||
// 网元版本信息服务
|
||||
neVersionService *neService.NeVersion
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
neLicenseService *neService.NeLicense // 网元授权激活信息服务
|
||||
neVersionService *neService.NeVersion // 网元版本信息服务
|
||||
}
|
||||
|
||||
// neStateCacheMap 网元状态缓存最后一次成功的信息
|
||||
|
||||
@@ -15,18 +15,16 @@ import (
|
||||
|
||||
// 实例化控制层 NeLicenseController 结构体
|
||||
var NewNeLicense = &NeLicenseController{
|
||||
neLicenseService: neService.NewNeLicenseImpl,
|
||||
neInfoService: neService.NewNeInfoImpl,
|
||||
neLicenseService: neService.NewNeLicense,
|
||||
neInfoService: neService.NewNeInfo,
|
||||
}
|
||||
|
||||
// 网元授权激活请求
|
||||
//
|
||||
// PATH /license
|
||||
type NeLicenseController struct {
|
||||
// 网元授权激活服务
|
||||
neLicenseService neService.INeLicense
|
||||
// 网元信息服务
|
||||
neInfoService neService.INeInfo
|
||||
neLicenseService *neService.NeLicense // 网元授权激活服务
|
||||
neInfoService *neService.NeInfo // 网元信息服务
|
||||
}
|
||||
|
||||
// 网元授权激活列表
|
||||
|
||||
@@ -15,15 +15,14 @@ import (
|
||||
|
||||
// 实例化控制层 NeSoftwareController 结构体
|
||||
var NewNeSoftware = &NeSoftwareController{
|
||||
neSoftwareService: neService.NewNeSoftwareImpl,
|
||||
neSoftwareService: neService.NewNeSoftware,
|
||||
}
|
||||
|
||||
// 网元软件包请求
|
||||
//
|
||||
// PATH /software
|
||||
type NeSoftwareController struct {
|
||||
// 网元软件包服务
|
||||
neSoftwareService neService.INeSoftware
|
||||
neSoftwareService *neService.NeSoftware // 网元软件包服务
|
||||
}
|
||||
|
||||
// 网元软件包列表
|
||||
|
||||
@@ -18,8 +18,7 @@ var NewNeVersion = &NeVersionController{
|
||||
//
|
||||
// PATH /version
|
||||
type NeVersionController struct {
|
||||
// 网元版本服务
|
||||
neVersionService *neService.NeVersion
|
||||
neVersionService *neService.NeVersion // 网元版本服务
|
||||
}
|
||||
|
||||
// 网元版本列表
|
||||
|
||||
@@ -49,6 +49,8 @@ func NeState(neInfo model.NeInfo) (map[string]any, error) {
|
||||
"capability": resData["capability"],
|
||||
"sn": resData["serialNum"],
|
||||
"expire": resData["expiryDate"],
|
||||
"hostname": resData["hostName"],
|
||||
"os": resData["osInfo"],
|
||||
"cpu": resData["cpuUsage"],
|
||||
"mem": resData["memUsage"],
|
||||
"disk": resData["diskSpace"],
|
||||
|
||||
@@ -5,16 +5,17 @@ import "encoding/json"
|
||||
// NeHost 网元主机表 ne_host
|
||||
type NeHost struct {
|
||||
HostID string `json:"hostId" gorm:"column:host_id"` // 主机主键
|
||||
HostType string `json:"hostType" gorm:"column:host_type" binding:"oneof=ssh telnet"` // 主机类型 ssh telnet
|
||||
HostType string `json:"hostType" gorm:"column:host_type" binding:"oneof=ssh telnet redis"` // 连接类型 ssh telnet redis
|
||||
GroupID string `json:"groupId" gorm:"column:group_id"` // 分组(0默认 1网元 2系统)
|
||||
Title string `json:"title" gorm:"column:title"` // 标题名称
|
||||
Addr string `json:"addr" gorm:"column:addr" binding:"required"` // 主机地址
|
||||
Port int64 `json:"port" gorm:"column:port" binding:"required,number,max=65535,min=1"` // SSH端口
|
||||
User string `json:"user" gorm:"column:user" binding:"required"` // 主机用户名
|
||||
Port int64 `json:"port" gorm:"column:port" binding:"required,number,max=65535,min=1"` // 端口 22 4100 6379
|
||||
User string `json:"user" gorm:"column:user" binding:"required"` // 认证用户名
|
||||
AuthMode string `json:"authMode" gorm:"column:auth_mode" binding:"oneof=0 1 2"` // 认证模式(0密码 1主机私钥 2已免密)
|
||||
Password string `json:"password" gorm:"column:password"` // 认证密码
|
||||
PrivateKey string `json:"privateKey" gorm:"column:private_key"` // 认证私钥
|
||||
PassPhrase string `json:"passPhrase" gorm:"column:pass_phrase"` // 认证私钥密码
|
||||
DBName string `json:"dbName" gorm:"column:db_name"` // 数据库名称
|
||||
Remark string `json:"remark" gorm:"column:remark"` // 备注
|
||||
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
|
||||
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
|
||||
@@ -23,7 +24,7 @@ type NeHost struct {
|
||||
}
|
||||
|
||||
// TableName 表名称
|
||||
func (NeHost) TableName() string {
|
||||
func (*NeHost) TableName() string {
|
||||
return "ne_host"
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ type NeInfo struct {
|
||||
VendorName string `json:"vendorName" gorm:"vendor_name"`
|
||||
Dn string `json:"dn" gorm:"dn"`
|
||||
NeAddress string `json:"neAddress" gorm:"ne_address"` // MAC地址
|
||||
HostIDs string `json:"hostIds" gorm:"host_ids"` // 网元主机ID组 数据格式(ssh,telnet,telnet)
|
||||
HostIDs string `json:"hostIds" gorm:"host_ids"` // 网元主机ID组 数据格式(ssh,telnet) UDM(ssh,telnet,redis) UPF(ssh,telnet,telnet)
|
||||
Status string `json:"status" gorm:"status"` // 0离线 1在线 2配置待下发
|
||||
Remark string `json:"remark" gorm:"remark"` // 备注
|
||||
CreateBy string `json:"createBy" gorm:"create_by"` // 创建者
|
||||
|
||||
@@ -17,10 +17,8 @@ func Setup(router *gin.Engine) {
|
||||
// 启动时需要的初始参数
|
||||
InitLoad()
|
||||
|
||||
neGroup := router.Group("/ne")
|
||||
|
||||
// 网元操作处理
|
||||
neActionGroup := neGroup.Group("/action")
|
||||
neActionGroup := router.Group("/ne/action")
|
||||
{
|
||||
neActionGroup.GET("/files",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -35,6 +33,14 @@ func Setup(router *gin.Engine) {
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neAction", collectlogs.BUSINESS_TYPE_IMPORT)),
|
||||
controller.NewNeAction.PushFile,
|
||||
)
|
||||
neActionGroup.GET("/pullDirZip",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewNeAction.PullDirZip,
|
||||
)
|
||||
neActionGroup.GET("/viewFile",
|
||||
middleware.PreAuthorize(nil),
|
||||
controller.NewNeAction.ViewFile,
|
||||
)
|
||||
neActionGroup.PUT("/service",
|
||||
middleware.PreAuthorize(nil),
|
||||
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neAction", collectlogs.BUSINESS_TYPE_OTHER)),
|
||||
@@ -43,7 +49,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元信息
|
||||
neInfoGroup := neGroup.Group("/info")
|
||||
neInfoGroup := router.Group("/ne/info")
|
||||
{
|
||||
neInfoGroup.GET("/state",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -104,7 +110,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元主机
|
||||
neHostGroup := neGroup.Group("/host")
|
||||
neHostGroup := router.Group("/ne/host")
|
||||
{
|
||||
neHostGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -153,7 +159,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元主机命令
|
||||
neHostCmdGroup := neGroup.Group("/hostCmd")
|
||||
neHostCmdGroup := router.Group("/ne/hostCmd")
|
||||
{
|
||||
neHostCmdGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -181,7 +187,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元版本信息
|
||||
neVersionGroup := neGroup.Group("/version")
|
||||
neVersionGroup := router.Group("/ne/version")
|
||||
{
|
||||
neVersionGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -199,7 +205,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元软件包信息
|
||||
neSoftwareGroup := neGroup.Group("/software")
|
||||
neSoftwareGroup := router.Group("/ne/software")
|
||||
{
|
||||
neSoftwareGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -232,7 +238,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元授权激活信息
|
||||
neLicenseGroup := neGroup.Group("/license")
|
||||
neLicenseGroup := router.Group("/ne/license")
|
||||
{
|
||||
neLicenseGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -262,7 +268,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元参数配置
|
||||
neConfigGroup := neGroup.Group("/config")
|
||||
neConfigGroup := router.Group("/ne/config")
|
||||
{
|
||||
// 网元参数配置可用属性值
|
||||
neConfigGroup.GET("/list",
|
||||
@@ -315,7 +321,7 @@ func Setup(router *gin.Engine) {
|
||||
}
|
||||
|
||||
// 网元配置文件备份记录
|
||||
neConfigBackupGroup := neGroup.Group("/config/backup")
|
||||
neConfigBackupGroup := router.Group("/ne/config/backup")
|
||||
{
|
||||
neConfigBackupGroup.GET("/list",
|
||||
middleware.PreAuthorize(nil),
|
||||
@@ -351,13 +357,13 @@ func Setup(router *gin.Engine) {
|
||||
// InitLoad 初始参数
|
||||
func InitLoad() {
|
||||
// 启动时,清除缓存-网元类型
|
||||
service.NewNeInfoImpl.ClearNeCacheByNeType("*")
|
||||
service.NewNeInfoImpl.SelectNeInfoByRmuid("")
|
||||
service.NewNeInfo.ClearNeCacheByNeType("*")
|
||||
service.NewNeInfo.SelectNeInfoByRmuid("")
|
||||
// 启动时,网元公共参数数据记录到全局变量
|
||||
if para5GMap, err := service.NewNeInfoImpl.NeConfPara5GRead(); para5GMap != nil && err == nil {
|
||||
service.NewNeInfoImpl.NeConfPara5GWirte(para5GMap, nil)
|
||||
if para5GMap, err := service.NewNeInfo.NeConfPara5GRead(); para5GMap != nil && err == nil {
|
||||
service.NewNeInfo.NeConfPara5GWirte(para5GMap, nil)
|
||||
}
|
||||
// 启动时,清除缓存-网元参数配置可用属性值
|
||||
service.NewNeConfigImpl.ClearNeCacheByNeType("*")
|
||||
service.NewNeConfigImpl.RefreshByNeTypeAndNeID("*")
|
||||
service.NewNeConfig.ClearNeCacheByNeType("*")
|
||||
service.NewNeConfig.RefreshByNeTypeAndNeID("*")
|
||||
}
|
||||
|
||||
@@ -1,24 +1,259 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_element/model"
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// INeConfig 网元参数配置可用属性值 数据层接口
|
||||
type INeConfig interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/network_element/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(param model.NeConfig) []model.NeConfig
|
||||
// 实例化数据层 NeConfig 结构体
|
||||
var NewNeConfig = &NeConfig{
|
||||
selectSql: `select id, ne_type, param_name, param_display, param_type, param_json, param_sort, param_perms, update_time from ne_config`,
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ids []string) []model.NeConfig
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(param model.NeConfig) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(param model.NeConfig) int64
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ids []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"param_name": "ParamName",
|
||||
"param_display": "ParamDisplay",
|
||||
"param_type": "ParamType",
|
||||
"param_json": "ParamJson",
|
||||
"param_sort": "ParamSort",
|
||||
"param_perms": "ParamPerms",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeConfig 网元参数配置可用属性值 数据层处理
|
||||
type NeConfig struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeConfig) convertResultRows(rows []map[string]any) []model.NeConfig {
|
||||
arr := make([]model.NeConfig, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeConfig{}
|
||||
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 *NeConfig) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
if v, ok := query["paramName"]; ok && v != "" {
|
||||
conditions = append(conditions, "param_name = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(id) as 'total' from ne_config"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeConfig) SelectList(param model.NeConfig) []model.NeConfig {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if param.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, param.NeType)
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
conditions = append(conditions, "param_name = ?")
|
||||
params = append(params, param.ParamName)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by param_sort asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeConfig) SelectByIds(ids []string) []model.NeConfig {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeConfig{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeConfig) Insert(param model.NeConfig) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if param.NeType != "" {
|
||||
params["ne_type"] = param.NeType
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
params["param_name"] = param.ParamName
|
||||
}
|
||||
if param.ParamDisplay != "" {
|
||||
params["param_display"] = param.ParamDisplay
|
||||
}
|
||||
if param.ParamType != "" {
|
||||
params["param_type"] = param.ParamType
|
||||
}
|
||||
if param.ParamJson != "" {
|
||||
params["param_json"] = param.ParamJson
|
||||
}
|
||||
params["param_sort"] = param.ParamSort
|
||||
if param.ParamPerms != "" {
|
||||
params["param_perms"] = param.ParamPerms
|
||||
}
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_config (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeConfig) Update(param model.NeConfig) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if param.NeType != "" {
|
||||
params["ne_type"] = param.NeType
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
params["param_name"] = param.ParamName
|
||||
}
|
||||
if param.ParamDisplay != "" {
|
||||
params["param_display"] = param.ParamDisplay
|
||||
}
|
||||
if param.ParamType != "" {
|
||||
params["param_type"] = param.ParamType
|
||||
}
|
||||
if param.ParamJson != "" {
|
||||
params["param_json"] = param.ParamJson
|
||||
}
|
||||
params["param_sort"] = param.ParamSort
|
||||
if param.ParamPerms != "" {
|
||||
params["param_perms"] = param.ParamPerms
|
||||
}
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_config set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, param.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeConfig) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from ne_config where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,259 +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/network_element/model"
|
||||
)
|
||||
|
||||
// NewNeConfigImpl 网元参数配置可用属性值 实例化数据层
|
||||
var NewNeConfigImpl = &NeConfigImpl{
|
||||
selectSql: `select id, ne_type, param_name, param_display, param_type, param_json, param_sort, param_perms, update_time from ne_config`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"param_name": "ParamName",
|
||||
"param_display": "ParamDisplay",
|
||||
"param_type": "ParamType",
|
||||
"param_json": "ParamJson",
|
||||
"param_sort": "ParamSort",
|
||||
"param_perms": "ParamPerms",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeConfigImpl 网元参数配置可用属性值 数据层处理
|
||||
type NeConfigImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeConfigImpl) convertResultRows(rows []map[string]any) []model.NeConfig {
|
||||
arr := make([]model.NeConfig, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeConfig{}
|
||||
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 *NeConfigImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
if v, ok := query["paramName"]; ok && v != "" {
|
||||
conditions = append(conditions, "param_name = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(id) as 'total' from ne_config"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeConfigImpl) SelectList(param model.NeConfig) []model.NeConfig {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if param.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, param.NeType)
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
conditions = append(conditions, "param_name = ?")
|
||||
params = append(params, param.ParamName)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by param_sort asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeConfigImpl) SelectByIds(ids []string) []model.NeConfig {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeConfig{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeConfigImpl) Insert(param model.NeConfig) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if param.NeType != "" {
|
||||
params["ne_type"] = param.NeType
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
params["param_name"] = param.ParamName
|
||||
}
|
||||
if param.ParamDisplay != "" {
|
||||
params["param_display"] = param.ParamDisplay
|
||||
}
|
||||
if param.ParamType != "" {
|
||||
params["param_type"] = param.ParamType
|
||||
}
|
||||
if param.ParamJson != "" {
|
||||
params["param_json"] = param.ParamJson
|
||||
}
|
||||
params["param_sort"] = param.ParamSort
|
||||
if param.ParamPerms != "" {
|
||||
params["param_perms"] = param.ParamPerms
|
||||
}
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_config (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeConfigImpl) Update(param model.NeConfig) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if param.NeType != "" {
|
||||
params["ne_type"] = param.NeType
|
||||
}
|
||||
if param.ParamName != "" {
|
||||
params["param_name"] = param.ParamName
|
||||
}
|
||||
if param.ParamDisplay != "" {
|
||||
params["param_display"] = param.ParamDisplay
|
||||
}
|
||||
if param.ParamType != "" {
|
||||
params["param_type"] = param.ParamType
|
||||
}
|
||||
if param.ParamJson != "" {
|
||||
params["param_json"] = param.ParamJson
|
||||
}
|
||||
params["param_sort"] = param.ParamSort
|
||||
if param.ParamPerms != "" {
|
||||
params["param_perms"] = param.ParamPerms
|
||||
}
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_config set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, param.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeConfigImpl) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from ne_config where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,24 +1,262 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_element/model"
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// INeConfigBackup 网元配置文件备份记录 数据层接口
|
||||
type INeConfigBackup interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/network_element/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(item model.NeConfigBackup) []model.NeConfigBackup
|
||||
// 实例化数据层 NeConfigBackup 结构体
|
||||
var NewNeConfigBackup = &NeConfigBackup{
|
||||
selectSql: `select
|
||||
id, ne_type, ne_id, name, path, remark, create_by, create_time, update_by, update_time
|
||||
from ne_config_backup`,
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ids []string) []model.NeConfigBackup
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(item model.NeConfigBackup) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(item model.NeConfigBackup) int64
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ids []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"name": "Name",
|
||||
"path": "Path",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeConfigBackup 网元配置文件备份记录 数据层处理
|
||||
type NeConfigBackup struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeConfigBackup) convertResultRows(rows []map[string]any) []model.NeConfigBackup {
|
||||
arr := make([]model.NeConfigBackup, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeConfigBackup{}
|
||||
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 *NeConfigBackup) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["name"]; ok && v != "" {
|
||||
conditions = append(conditions, "name like concat(concat('%', ?), '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_config_backup"
|
||||
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 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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeConfigBackup) SelectList(item model.NeConfigBackup) []model.NeConfigBackup {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if item.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, item.NeType)
|
||||
}
|
||||
if item.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, item.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by id desc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeConfigBackup) SelectByIds(cmdIds []string) []model.NeConfigBackup {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeConfigBackup{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeConfigBackup) Insert(item model.NeConfigBackup) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if item.NeType != "" {
|
||||
params["ne_type"] = item.NeType
|
||||
}
|
||||
if item.NeId != "" {
|
||||
params["ne_id"] = item.NeId
|
||||
}
|
||||
if item.Name != "" {
|
||||
params["name"] = item.Name
|
||||
}
|
||||
if item.Path != "" {
|
||||
params["path"] = item.Path
|
||||
}
|
||||
if item.Remark != "" {
|
||||
params["remark"] = item.Remark
|
||||
}
|
||||
if item.CreateBy != "" {
|
||||
params["create_by"] = item.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_config_backup (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeConfigBackup) Update(item model.NeConfigBackup) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if item.NeType != "" {
|
||||
params["ne_type"] = item.NeType
|
||||
}
|
||||
if item.NeId != "" {
|
||||
params["ne_id"] = item.NeId
|
||||
}
|
||||
if item.Name != "" {
|
||||
params["name"] = item.Name
|
||||
}
|
||||
if item.Path != "" {
|
||||
params["path"] = item.Path
|
||||
}
|
||||
params["remark"] = item.Remark
|
||||
if item.UpdateBy != "" {
|
||||
params["update_by"] = item.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_config_backup set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, item.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeConfigBackup) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from ne_config_backup where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,262 +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/network_element/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewNeConfigBackupImpl 结构体
|
||||
var NewNeConfigBackupImpl = &NeConfigBackupImpl{
|
||||
selectSql: `select
|
||||
id, ne_type, ne_id, name, path, remark, create_by, create_time, update_by, update_time
|
||||
from ne_config_backup`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"name": "Name",
|
||||
"path": "Path",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeConfigBackupImpl 网元配置文件备份记录 数据层处理
|
||||
type NeConfigBackupImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeConfigBackupImpl) convertResultRows(rows []map[string]any) []model.NeConfigBackup {
|
||||
arr := make([]model.NeConfigBackup, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeConfigBackup{}
|
||||
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 *NeConfigBackupImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["name"]; ok && v != "" {
|
||||
conditions = append(conditions, "name like concat(concat('%', ?), '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_config_backup"
|
||||
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 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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeConfigBackupImpl) SelectList(item model.NeConfigBackup) []model.NeConfigBackup {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if item.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, item.NeType)
|
||||
}
|
||||
if item.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, item.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by id desc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeConfigBackupImpl) SelectByIds(cmdIds []string) []model.NeConfigBackup {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeConfigBackup{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeConfigBackupImpl) Insert(item model.NeConfigBackup) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if item.NeType != "" {
|
||||
params["ne_type"] = item.NeType
|
||||
}
|
||||
if item.NeId != "" {
|
||||
params["ne_id"] = item.NeId
|
||||
}
|
||||
if item.Name != "" {
|
||||
params["name"] = item.Name
|
||||
}
|
||||
if item.Path != "" {
|
||||
params["path"] = item.Path
|
||||
}
|
||||
if item.Remark != "" {
|
||||
params["remark"] = item.Remark
|
||||
}
|
||||
if item.CreateBy != "" {
|
||||
params["create_by"] = item.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_config_backup (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeConfigBackupImpl) Update(item model.NeConfigBackup) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if item.NeType != "" {
|
||||
params["ne_type"] = item.NeType
|
||||
}
|
||||
if item.NeId != "" {
|
||||
params["ne_id"] = item.NeId
|
||||
}
|
||||
if item.Name != "" {
|
||||
params["name"] = item.Name
|
||||
}
|
||||
if item.Path != "" {
|
||||
params["path"] = item.Path
|
||||
}
|
||||
params["remark"] = item.Remark
|
||||
if item.UpdateBy != "" {
|
||||
params["update_by"] = item.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_config_backup set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, item.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeConfigBackupImpl) DeleteByIds(ids []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(ids))
|
||||
sql := "delete from ne_config_backup where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(ids)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,27 +1,383 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_element/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// INeHost 网元主机连接 数据层接口
|
||||
type INeHost interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/network_element/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(neHost model.NeHost) []model.NeHost
|
||||
// 实例化数据层 NeHost 结构体
|
||||
var NewNeHost = &NeHost{
|
||||
selectSql: `select
|
||||
host_id, host_type, group_id, title, addr, port, user, auth_mode, password, private_key, pass_phrase, db_name, remark, create_by, create_time, update_by, update_time
|
||||
from ne_host`,
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(hostIds []string) []model.NeHost
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(neHost model.NeHost) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(neHost model.NeHost) int64
|
||||
|
||||
// DeleteByIds 批量删除网元主机连接信息
|
||||
DeleteByIds(hostIds []string) int64
|
||||
|
||||
// CheckUniqueNeHost 校验主机是否唯一
|
||||
CheckUniqueNeHost(neHost model.NeHost) string
|
||||
resultMap: map[string]string{
|
||||
"host_id": "HostID",
|
||||
"host_type": "HostType",
|
||||
"group_id": "GroupID",
|
||||
"title": "Title",
|
||||
"addr": "Addr",
|
||||
"port": "Port",
|
||||
"user": "User",
|
||||
"auth_mode": "AuthMode",
|
||||
"password": "Password",
|
||||
"private_key": "PrivateKey",
|
||||
"private_password": "PassPhrase",
|
||||
"db_name": "DBName",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeHost 网元主机连接 数据层处理
|
||||
type NeHost struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeHost) convertResultRows(rows []map[string]any) []model.NeHost {
|
||||
arr := make([]model.NeHost, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeHost{}
|
||||
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 *NeHost) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["hostType"]; ok && v != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["groupId"]; ok && v != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["title"]; ok && v != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_host"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeHost) SelectList(neHost model.NeHost) []model.NeHost {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHost.HostType != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, neHost.HostType)
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHost.GroupID)
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, neHost.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by update_time asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeHost) SelectByIds(hostIds []string) []model.NeHost {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
|
||||
querySql := r.selectSql + " where host_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(hostIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeHost{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueNeHost 校验主机是否唯一
|
||||
func (r *NeHost) CheckUniqueNeHost(neHost model.NeHost) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHost.HostType != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, neHost.HostType)
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHost.GroupID)
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
conditions = append(conditions, "title = ?")
|
||||
params = append(params, neHost.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select host_id as 'str' from ne_host " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeHost) Insert(neHost model.NeHost) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHost.HostType != "" {
|
||||
params["host_type"] = neHost.HostType
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
params["group_id"] = neHost.GroupID
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
params["title"] = neHost.Title
|
||||
}
|
||||
if neHost.Addr != "" {
|
||||
params["addr"] = neHost.Addr
|
||||
}
|
||||
if neHost.Port > 0 {
|
||||
params["port"] = neHost.Port
|
||||
}
|
||||
if neHost.User != "" {
|
||||
params["user"] = neHost.User
|
||||
}
|
||||
if neHost.AuthMode != "" {
|
||||
params["auth_mode"] = neHost.AuthMode
|
||||
}
|
||||
if neHost.Password != "" {
|
||||
params["password"] = neHost.Password
|
||||
}
|
||||
if neHost.PrivateKey != "" {
|
||||
params["private_key"] = neHost.PrivateKey
|
||||
}
|
||||
if neHost.PassPhrase != "" {
|
||||
params["pass_phrase"] = neHost.PassPhrase
|
||||
}
|
||||
if neHost.DBName != "" {
|
||||
params["db_name"] = neHost.DBName
|
||||
}
|
||||
if neHost.Remark != "" {
|
||||
params["remark"] = neHost.Remark
|
||||
}
|
||||
if neHost.CreateBy != "" {
|
||||
params["create_by"] = neHost.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 根据认证模式清除不必要的信息
|
||||
if neHost.AuthMode == "0" {
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "1" {
|
||||
params["password"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "2" {
|
||||
params["password"] = ""
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_host (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeHost) Update(neHost model.NeHost) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHost.HostType != "" {
|
||||
params["host_type"] = neHost.HostType
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
params["group_id"] = neHost.GroupID
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
params["title"] = neHost.Title
|
||||
}
|
||||
if neHost.Addr != "" {
|
||||
params["addr"] = neHost.Addr
|
||||
}
|
||||
if neHost.Port > 0 {
|
||||
params["port"] = neHost.Port
|
||||
}
|
||||
if neHost.User != "" {
|
||||
params["user"] = neHost.User
|
||||
}
|
||||
if neHost.AuthMode != "" {
|
||||
params["auth_mode"] = neHost.AuthMode
|
||||
}
|
||||
if neHost.Password != "" {
|
||||
params["password"] = neHost.Password
|
||||
}
|
||||
if neHost.PrivateKey != "" {
|
||||
params["private_key"] = neHost.PrivateKey
|
||||
}
|
||||
if neHost.PassPhrase != "" {
|
||||
params["pass_phrase"] = neHost.PassPhrase
|
||||
}
|
||||
if neHost.DBName != "" {
|
||||
params["db_name"] = neHost.DBName
|
||||
}
|
||||
params["remark"] = neHost.Remark
|
||||
if neHost.UpdateBy != "" {
|
||||
params["update_by"] = neHost.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 根据认证模式清除不必要的信息
|
||||
if neHost.AuthMode == "0" {
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "1" {
|
||||
params["password"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "2" {
|
||||
params["password"] = ""
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_host set " + strings.Join(keys, ",") + " where host_id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neHost.HostID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除网元主机连接信息
|
||||
func (r *NeHost) DeleteByIds(hostIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
|
||||
sql := "delete from ne_host where host_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(hostIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,376 +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/network_element/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewNeHostImpl 结构体
|
||||
var NewNeHostImpl = &NeHostImpl{
|
||||
selectSql: `select
|
||||
host_id, host_type, group_id, title, addr, port, user, auth_mode, password, private_key, pass_phrase, remark, create_by, create_time, update_by, update_time
|
||||
from ne_host`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"host_id": "HostID",
|
||||
"host_type": "HostType",
|
||||
"group_id": "GroupID",
|
||||
"title": "Title",
|
||||
"addr": "Addr",
|
||||
"port": "Port",
|
||||
"user": "User",
|
||||
"auth_mode": "AuthMode",
|
||||
"password": "Password",
|
||||
"private_key": "PrivateKey",
|
||||
"private_password": "PassPhrase",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeHostImpl 网元主机连接 数据层处理
|
||||
type NeHostImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeHostImpl) convertResultRows(rows []map[string]any) []model.NeHost {
|
||||
arr := make([]model.NeHost, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeHost{}
|
||||
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 *NeHostImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["hostType"]; ok && v != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["groupId"]; ok && v != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["title"]; ok && v != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_host"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeHostImpl) SelectList(neHost model.NeHost) []model.NeHost {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHost.HostType != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, neHost.HostType)
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHost.GroupID)
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, neHost.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by update_time asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeHostImpl) SelectByIds(hostIds []string) []model.NeHost {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
|
||||
querySql := r.selectSql + " where host_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(hostIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeHost{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueNeHost 校验主机是否唯一
|
||||
func (r *NeHostImpl) CheckUniqueNeHost(neHost model.NeHost) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHost.HostType != "" {
|
||||
conditions = append(conditions, "host_type = ?")
|
||||
params = append(params, neHost.HostType)
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHost.GroupID)
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
conditions = append(conditions, "title = ?")
|
||||
params = append(params, neHost.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select host_id as 'str' from ne_host " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeHostImpl) Insert(neHost model.NeHost) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHost.HostType != "" {
|
||||
params["host_type"] = neHost.HostType
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
params["group_id"] = neHost.GroupID
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
params["title"] = neHost.Title
|
||||
}
|
||||
if neHost.Addr != "" {
|
||||
params["addr"] = neHost.Addr
|
||||
}
|
||||
if neHost.Port > 0 {
|
||||
params["port"] = neHost.Port
|
||||
}
|
||||
if neHost.User != "" {
|
||||
params["user"] = neHost.User
|
||||
}
|
||||
if neHost.AuthMode != "" {
|
||||
params["auth_mode"] = neHost.AuthMode
|
||||
}
|
||||
if neHost.Password != "" {
|
||||
params["password"] = neHost.Password
|
||||
}
|
||||
if neHost.PrivateKey != "" {
|
||||
params["private_key"] = neHost.PrivateKey
|
||||
}
|
||||
if neHost.PassPhrase != "" {
|
||||
params["pass_phrase"] = neHost.PassPhrase
|
||||
}
|
||||
if neHost.Remark != "" {
|
||||
params["remark"] = neHost.Remark
|
||||
}
|
||||
if neHost.CreateBy != "" {
|
||||
params["create_by"] = neHost.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 根据认证模式清除不必要的信息
|
||||
if neHost.AuthMode == "0" {
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "1" {
|
||||
params["password"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "2" {
|
||||
params["password"] = ""
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_host (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeHostImpl) Update(neHost model.NeHost) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHost.HostType != "" {
|
||||
params["host_type"] = neHost.HostType
|
||||
}
|
||||
if neHost.GroupID != "" {
|
||||
params["group_id"] = neHost.GroupID
|
||||
}
|
||||
if neHost.Title != "" {
|
||||
params["title"] = neHost.Title
|
||||
}
|
||||
if neHost.Addr != "" {
|
||||
params["addr"] = neHost.Addr
|
||||
}
|
||||
if neHost.Port > 0 {
|
||||
params["port"] = neHost.Port
|
||||
}
|
||||
if neHost.User != "" {
|
||||
params["user"] = neHost.User
|
||||
}
|
||||
if neHost.AuthMode != "" {
|
||||
params["auth_mode"] = neHost.AuthMode
|
||||
}
|
||||
if neHost.Password != "" {
|
||||
params["password"] = neHost.Password
|
||||
}
|
||||
if neHost.PrivateKey != "" {
|
||||
params["private_key"] = neHost.PrivateKey
|
||||
}
|
||||
if neHost.PassPhrase != "" {
|
||||
params["pass_phrase"] = neHost.PassPhrase
|
||||
}
|
||||
params["remark"] = neHost.Remark
|
||||
if neHost.UpdateBy != "" {
|
||||
params["update_by"] = neHost.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 根据认证模式清除不必要的信息
|
||||
if neHost.AuthMode == "0" {
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "1" {
|
||||
params["password"] = ""
|
||||
}
|
||||
if neHost.AuthMode == "2" {
|
||||
params["password"] = ""
|
||||
params["private_key"] = ""
|
||||
params["pass_phrase"] = ""
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_host set " + strings.Join(keys, ",") + " where host_id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neHost.HostID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除网元主机连接信息
|
||||
func (r *NeHostImpl) DeleteByIds(hostIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
|
||||
sql := "delete from ne_host where host_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(hostIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,27 +1,306 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_element/model"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// INeHostCmd 网元主机命令 数据层接口
|
||||
type INeHostCmd interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/network_element/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(neHostCmd model.NeHostCmd) []model.NeHostCmd
|
||||
// 实例化数据层 NeHostCmd 结构体
|
||||
var NewNeHostCmd = &NeHostCmd{
|
||||
selectSql: `select
|
||||
cmd_id, cmd_type, group_id, title, command, remark, create_by, create_time, update_by, update_time
|
||||
from ne_host_cmd`,
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(cmdIds []string) []model.NeHostCmd
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(neHostCmd model.NeHostCmd) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(neHostCmd model.NeHostCmd) int64
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(cmdIds []string) int64
|
||||
|
||||
// CheckUniqueGroupTitle 校验同类型组内是否唯一
|
||||
CheckUniqueGroupTitle(neHostCmd model.NeHostCmd) string
|
||||
resultMap: map[string]string{
|
||||
"cmd_id": "CmdID",
|
||||
"cmd_type": "CmdType",
|
||||
"group_id": "GroupID",
|
||||
"title": "Title",
|
||||
"command": "Command",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeHostCmd 网元主机连接 数据层处理
|
||||
type NeHostCmd struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeHostCmd) convertResultRows(rows []map[string]any) []model.NeHostCmd {
|
||||
arr := make([]model.NeHostCmd, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeHostCmd{}
|
||||
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 *NeHostCmd) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["cmdType"]; ok && v != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["groupId"]; ok && v != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["title"]; ok && v != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_host_cmd"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeHostCmd) SelectList(neHostCmd model.NeHostCmd) []model.NeHostCmd {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHostCmd.CmdType != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, neHostCmd.CmdType)
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHostCmd.GroupID)
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, neHostCmd.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by update_time asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeHostCmd) SelectByIds(cmdIds []string) []model.NeHostCmd {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where cmd_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeHostCmd{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueGroupTitle 校验同类型组内是否唯一
|
||||
func (r *NeHostCmd) CheckUniqueGroupTitle(neHostCmd model.NeHostCmd) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHostCmd.CmdType != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, neHostCmd.CmdType)
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHostCmd.GroupID)
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
conditions = append(conditions, "title = ?")
|
||||
params = append(params, neHostCmd.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select host_id as 'str' from ne_host " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeHostCmd) Insert(neHostCmd model.NeHostCmd) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHostCmd.CmdType != "" {
|
||||
params["cmd_type"] = neHostCmd.CmdType
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
params["group_id"] = neHostCmd.GroupID
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
params["title"] = neHostCmd.Title
|
||||
}
|
||||
if neHostCmd.Command != "" {
|
||||
params["command"] = neHostCmd.Command
|
||||
}
|
||||
if neHostCmd.Remark != "" {
|
||||
params["remark"] = neHostCmd.Remark
|
||||
}
|
||||
if neHostCmd.CreateBy != "" {
|
||||
params["create_by"] = neHostCmd.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_host_cmd (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeHostCmd) Update(neHostCmd model.NeHostCmd) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHostCmd.CmdType != "" {
|
||||
params["cmd_type"] = neHostCmd.CmdType
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
params["group_id"] = neHostCmd.GroupID
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
params["title"] = neHostCmd.Title
|
||||
}
|
||||
if neHostCmd.Command != "" {
|
||||
params["command"] = neHostCmd.Command
|
||||
}
|
||||
params["remark"] = neHostCmd.Remark
|
||||
if neHostCmd.UpdateBy != "" {
|
||||
params["update_by"] = neHostCmd.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_host_cmd set " + strings.Join(keys, ",") + " where cmd_id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neHostCmd.CmdID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeHostCmd) DeleteByIds(cmdIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
sql := "delete from ne_host_cmd where cmd_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,306 +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/network_element/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewNeHostCmdImpl 结构体
|
||||
var NewNeHostCmdImpl = &NeHostCmdImpl{
|
||||
selectSql: `select
|
||||
cmd_id, cmd_type, group_id, title, command, remark, create_by, create_time, update_by, update_time
|
||||
from ne_host_cmd`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"cmd_id": "CmdID",
|
||||
"cmd_type": "CmdType",
|
||||
"group_id": "GroupID",
|
||||
"title": "Title",
|
||||
"command": "Command",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeHostCmdImpl 网元主机连接 数据层处理
|
||||
type NeHostCmdImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeHostCmdImpl) convertResultRows(rows []map[string]any) []model.NeHostCmd {
|
||||
arr := make([]model.NeHostCmd, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeHostCmd{}
|
||||
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 *NeHostCmdImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["cmdType"]; ok && v != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["groupId"]; ok && v != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["title"]; ok && v != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_host_cmd"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeHostCmdImpl) SelectList(neHostCmd model.NeHostCmd) []model.NeHostCmd {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHostCmd.CmdType != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, neHostCmd.CmdType)
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHostCmd.GroupID)
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
conditions = append(conditions, "title like concat(?, '%')")
|
||||
params = append(params, neHostCmd.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by update_time asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeHostCmdImpl) SelectByIds(cmdIds []string) []model.NeHostCmd {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where cmd_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeHostCmd{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueGroupTitle 校验同类型组内是否唯一
|
||||
func (r *NeHostCmdImpl) CheckUniqueGroupTitle(neHostCmd model.NeHostCmd) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neHostCmd.CmdType != "" {
|
||||
conditions = append(conditions, "cmd_type = ?")
|
||||
params = append(params, neHostCmd.CmdType)
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
conditions = append(conditions, "group_id = ?")
|
||||
params = append(params, neHostCmd.GroupID)
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
conditions = append(conditions, "title = ?")
|
||||
params = append(params, neHostCmd.Title)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select host_id as 'str' from ne_host " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeHostCmdImpl) Insert(neHostCmd model.NeHostCmd) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHostCmd.CmdType != "" {
|
||||
params["cmd_type"] = neHostCmd.CmdType
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
params["group_id"] = neHostCmd.GroupID
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
params["title"] = neHostCmd.Title
|
||||
}
|
||||
if neHostCmd.Command != "" {
|
||||
params["command"] = neHostCmd.Command
|
||||
}
|
||||
if neHostCmd.Remark != "" {
|
||||
params["remark"] = neHostCmd.Remark
|
||||
}
|
||||
if neHostCmd.CreateBy != "" {
|
||||
params["create_by"] = neHostCmd.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_host_cmd (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeHostCmdImpl) Update(neHostCmd model.NeHostCmd) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neHostCmd.CmdType != "" {
|
||||
params["cmd_type"] = neHostCmd.CmdType
|
||||
}
|
||||
if neHostCmd.GroupID != "" {
|
||||
params["group_id"] = neHostCmd.GroupID
|
||||
}
|
||||
if neHostCmd.Title != "" {
|
||||
params["title"] = neHostCmd.Title
|
||||
}
|
||||
if neHostCmd.Command != "" {
|
||||
params["command"] = neHostCmd.Command
|
||||
}
|
||||
params["remark"] = neHostCmd.Remark
|
||||
if neHostCmd.UpdateBy != "" {
|
||||
params["update_by"] = neHostCmd.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_host_cmd set " + strings.Join(keys, ",") + " where cmd_id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neHostCmd.CmdID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeHostCmdImpl) DeleteByIds(cmdIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
sql := "delete from ne_host_cmd where cmd_id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,35 +1,407 @@
|
||||
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/network_element/model"
|
||||
)
|
||||
|
||||
// 网元信息 数据层接口
|
||||
type INeInfo interface {
|
||||
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
|
||||
SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo
|
||||
|
||||
// SelectNeInfoByNeType 通过ne_type和ne_id查询网元信息
|
||||
SelectNeInfoByNeType(neType string) []model.NeInfo
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
|
||||
// SelectList 查询列表
|
||||
SelectList(neInfo model.NeInfo) []model.NeInfo
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(infoIds []string) []model.NeInfo
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(neInfo model.NeInfo) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(neInfo model.NeInfo) int64
|
||||
|
||||
// DeleteByIds 批量删除网元信息
|
||||
DeleteByIds(infoIds []string) int64
|
||||
|
||||
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
|
||||
CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string
|
||||
// neListSort 网元列表预设排序
|
||||
var neListSort = []string{
|
||||
"OMC",
|
||||
"IMS",
|
||||
"AMF",
|
||||
"AUSF",
|
||||
"UDM",
|
||||
"SMF",
|
||||
"PCF",
|
||||
"NSSF",
|
||||
"NRF",
|
||||
"UPF",
|
||||
"LMF",
|
||||
"NEF",
|
||||
"MME",
|
||||
"N3IWF",
|
||||
"MOCNGW",
|
||||
"SMSC",
|
||||
"SMSF",
|
||||
"CBC",
|
||||
"CHF",
|
||||
}
|
||||
|
||||
// 实例化数据层 NeInfo 结构体
|
||||
var NewNeInfo = &NeInfo{
|
||||
selectSql: `select id, ne_type, ne_id, rm_uid, ne_name, ip, port, pv_flag, province, vendor_name, dn, ne_address, host_ids, status, remark, create_by, create_time, update_by, update_time from ne_info`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"rm_uid": "RmUID",
|
||||
"ne_name": "NeName",
|
||||
"ip": "IP",
|
||||
"port": "Port",
|
||||
"pv_flag": "PvFlag",
|
||||
"province": "Province",
|
||||
"vendor_name": "VendorName",
|
||||
"dn": "Dn",
|
||||
"ne_address": "NeAddress",
|
||||
"host_ids": "HostIDs",
|
||||
"status": "Status",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeInfo 网元信息表 数据层处理
|
||||
type NeInfo struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeInfo) convertResultRows(rows []map[string]any) []model.NeInfo {
|
||||
arr := make([]model.NeInfo, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeInfo{}
|
||||
for key, value := range row {
|
||||
if keyMapper, ok := r.resultMap[key]; ok {
|
||||
repo.SetFieldValue(&item, keyMapper, value)
|
||||
}
|
||||
}
|
||||
arr = append(arr, item)
|
||||
}
|
||||
|
||||
// 创建优先级映射
|
||||
priority := make(map[string]int)
|
||||
for i, v := range neListSort {
|
||||
priority[v] = i
|
||||
}
|
||||
// 冒泡排序
|
||||
n := len(arr)
|
||||
for i := 0; i < n-1; i++ {
|
||||
for j := 0; j < n-i-1; j++ {
|
||||
if priority[arr[j].NeType] > priority[arr[j+1].NeType] {
|
||||
// 交换元素
|
||||
arr[j], arr[j+1] = arr[j+1], arr[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return arr
|
||||
}
|
||||
|
||||
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
|
||||
func (r *NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
|
||||
querySql := r.selectSql + " where ne_type = ? and ne_id = ?"
|
||||
results, err := datasource.RawDB("", querySql, []any{neType, neID})
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return model.NeInfo{}
|
||||
}
|
||||
// 转换实体
|
||||
rows := r.convertResultRows(results)
|
||||
if len(rows) > 0 {
|
||||
return rows[0]
|
||||
}
|
||||
return model.NeInfo{}
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *NeInfo) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["rmUid"]; ok && v != "" {
|
||||
conditions = append(conditions, "rmUid like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeInfo{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_info"
|
||||
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 + " order by ne_type asc, ne_id asc " + 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 查询列表
|
||||
func (r *NeInfo) SelectList(neInfo model.NeInfo) []model.NeInfo {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neInfo.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neInfo.NeType)
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neInfo.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by ne_type asc, ne_id asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeInfo) SelectByIds(infoIds []string) []model.NeInfo {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(infoIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeInfo{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
|
||||
func (r *NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neInfo.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neInfo.NeType)
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neInfo.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select id as 'str' from ne_info " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeInfo) Insert(neInfo model.NeInfo) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neInfo.NeType != "" {
|
||||
params["ne_type"] = neInfo.NeType
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
params["ne_id"] = neInfo.NeId
|
||||
}
|
||||
if neInfo.RmUID != "" {
|
||||
params["rm_uid"] = neInfo.RmUID
|
||||
}
|
||||
if neInfo.NeName != "" {
|
||||
params["ne_name"] = neInfo.NeName
|
||||
}
|
||||
if neInfo.IP != "" {
|
||||
params["ip"] = neInfo.IP
|
||||
}
|
||||
if neInfo.Port > 0 {
|
||||
params["port"] = neInfo.Port
|
||||
}
|
||||
if neInfo.PvFlag != "" {
|
||||
params["pv_flag"] = neInfo.PvFlag
|
||||
}
|
||||
if neInfo.Province != "" {
|
||||
params["province"] = neInfo.Province
|
||||
}
|
||||
if neInfo.VendorName != "" {
|
||||
params["vendor_name"] = neInfo.VendorName
|
||||
}
|
||||
if neInfo.Dn != "" {
|
||||
params["dn"] = neInfo.Dn
|
||||
}
|
||||
if neInfo.NeAddress != "" {
|
||||
params["ne_address"] = neInfo.NeAddress
|
||||
}
|
||||
if neInfo.HostIDs != "" {
|
||||
params["host_ids"] = neInfo.HostIDs
|
||||
}
|
||||
if neInfo.Status != "" {
|
||||
params["status"] = neInfo.Status
|
||||
}
|
||||
if neInfo.Remark != "" {
|
||||
params["remark"] = neInfo.Remark
|
||||
}
|
||||
if neInfo.CreateBy != "" {
|
||||
params["create_by"] = neInfo.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_info (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeInfo) Update(neInfo model.NeInfo) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neInfo.NeType != "" {
|
||||
params["ne_type"] = neInfo.NeType
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
params["ne_id"] = neInfo.NeId
|
||||
}
|
||||
if neInfo.RmUID != "" {
|
||||
params["rm_uid"] = neInfo.RmUID
|
||||
}
|
||||
if neInfo.NeName != "" {
|
||||
params["ne_name"] = neInfo.NeName
|
||||
}
|
||||
if neInfo.IP != "" {
|
||||
params["ip"] = neInfo.IP
|
||||
}
|
||||
if neInfo.Port > 0 {
|
||||
params["port"] = neInfo.Port
|
||||
}
|
||||
if neInfo.PvFlag != "" {
|
||||
params["pv_flag"] = neInfo.PvFlag
|
||||
}
|
||||
params["province"] = neInfo.Province
|
||||
params["vendor_name"] = neInfo.VendorName
|
||||
params["dn"] = neInfo.Dn
|
||||
params["ne_address"] = neInfo.NeAddress
|
||||
if neInfo.HostIDs != "" {
|
||||
params["host_ids"] = neInfo.HostIDs
|
||||
}
|
||||
params["remark"] = neInfo.Remark
|
||||
if neInfo.Status != "" {
|
||||
params["status"] = neInfo.Status
|
||||
}
|
||||
if neInfo.UpdateBy != "" {
|
||||
params["update_by"] = neInfo.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_info set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neInfo.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除网元信息
|
||||
func (r *NeInfo) DeleteByIds(infoIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
|
||||
sql := "delete from ne_info where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(infoIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,418 +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/network_element/model"
|
||||
)
|
||||
|
||||
// neListSort 网元列表预设排序
|
||||
var neListSort = []string{
|
||||
"OMC",
|
||||
"IMS",
|
||||
"AMF",
|
||||
"AUSF",
|
||||
"UDM",
|
||||
"SMF",
|
||||
"PCF",
|
||||
"NSSF",
|
||||
"NRF",
|
||||
"UPF",
|
||||
"LMF",
|
||||
"NEF",
|
||||
"MME",
|
||||
"N3IWF",
|
||||
"MOCNGW",
|
||||
"SMSC",
|
||||
"CBC",
|
||||
}
|
||||
|
||||
// 实例化数据层 NeInfoImpl 结构体
|
||||
var NewNeInfoImpl = &NeInfoImpl{
|
||||
selectSql: `select id, ne_type, ne_id, rm_uid, ne_name, ip, port, pv_flag, province, vendor_name, dn, ne_address, host_ids, status, remark, create_by, create_time, update_by, update_time from ne_info`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"rm_uid": "RmUID",
|
||||
"ne_name": "NeName",
|
||||
"ip": "IP",
|
||||
"port": "Port",
|
||||
"pv_flag": "PvFlag",
|
||||
"province": "Province",
|
||||
"vendor_name": "VendorName",
|
||||
"dn": "Dn",
|
||||
"ne_address": "NeAddress",
|
||||
"host_ids": "HostIDs",
|
||||
"status": "Status",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeInfoImpl 网元信息表 数据层处理
|
||||
type NeInfoImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeInfoImpl) convertResultRows(rows []map[string]any) []model.NeInfo {
|
||||
arr := make([]model.NeInfo, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeInfo{}
|
||||
for key, value := range row {
|
||||
if keyMapper, ok := r.resultMap[key]; ok {
|
||||
repo.SetFieldValue(&item, keyMapper, value)
|
||||
}
|
||||
}
|
||||
arr = append(arr, item)
|
||||
}
|
||||
|
||||
// 创建优先级映射
|
||||
priority := make(map[string]int)
|
||||
for i, v := range neListSort {
|
||||
priority[v] = i
|
||||
}
|
||||
// 冒泡排序
|
||||
n := len(arr)
|
||||
for i := 0; i < n-1; i++ {
|
||||
for j := 0; j < n-i-1; j++ {
|
||||
if priority[arr[j].NeType] > priority[arr[j+1].NeType] {
|
||||
// 交换元素
|
||||
arr[j], arr[j+1] = arr[j+1], arr[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return arr
|
||||
}
|
||||
|
||||
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
|
||||
func (r *NeInfoImpl) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
|
||||
querySql := r.selectSql + " where ne_type = ? and ne_id = ?"
|
||||
results, err := datasource.RawDB("", querySql, []any{neType, neID})
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return model.NeInfo{}
|
||||
}
|
||||
// 转换实体
|
||||
rows := r.convertResultRows(results)
|
||||
if len(rows) > 0 {
|
||||
return rows[0]
|
||||
}
|
||||
return model.NeInfo{}
|
||||
}
|
||||
|
||||
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
|
||||
func (r *NeInfoImpl) SelectNeInfoByNeType(neType string) []model.NeInfo {
|
||||
querySql := r.selectSql + " where ne_type = ?"
|
||||
results, err := datasource.RawDB("", querySql, []any{neType})
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeInfo{}
|
||||
}
|
||||
// 转换实体
|
||||
rows := r.convertResultRows(results)
|
||||
return rows
|
||||
}
|
||||
|
||||
// SelectPage 根据条件分页查询
|
||||
func (r *NeInfoImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["rmUid"]; ok && v != "" {
|
||||
conditions = append(conditions, "rmUid like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeInfo{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_info"
|
||||
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 + " order by ne_type asc, ne_id asc " + 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 查询列表
|
||||
func (r *NeInfoImpl) SelectList(neInfo model.NeInfo) []model.NeInfo {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neInfo.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neInfo.NeType)
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neInfo.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by ne_type asc, ne_id asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeInfoImpl) SelectByIds(infoIds []string) []model.NeInfo {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(infoIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeInfo{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
|
||||
func (r *NeInfoImpl) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neInfo.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neInfo.NeType)
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neInfo.NeId)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := "select id as 'str' from ne_info " + 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 ""
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeInfoImpl) Insert(neInfo model.NeInfo) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neInfo.NeType != "" {
|
||||
params["ne_type"] = neInfo.NeType
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
params["ne_id"] = neInfo.NeId
|
||||
}
|
||||
if neInfo.RmUID != "" {
|
||||
params["rm_uid"] = neInfo.RmUID
|
||||
}
|
||||
if neInfo.NeName != "" {
|
||||
params["ne_name"] = neInfo.NeName
|
||||
}
|
||||
if neInfo.IP != "" {
|
||||
params["ip"] = neInfo.IP
|
||||
}
|
||||
if neInfo.Port > 0 {
|
||||
params["port"] = neInfo.Port
|
||||
}
|
||||
if neInfo.PvFlag != "" {
|
||||
params["pv_flag"] = neInfo.PvFlag
|
||||
}
|
||||
if neInfo.Province != "" {
|
||||
params["province"] = neInfo.Province
|
||||
}
|
||||
if neInfo.VendorName != "" {
|
||||
params["vendor_name"] = neInfo.VendorName
|
||||
}
|
||||
if neInfo.Dn != "" {
|
||||
params["dn"] = neInfo.Dn
|
||||
}
|
||||
if neInfo.NeAddress != "" {
|
||||
params["ne_address"] = neInfo.NeAddress
|
||||
}
|
||||
if neInfo.HostIDs != "" {
|
||||
params["host_ids"] = neInfo.HostIDs
|
||||
}
|
||||
if neInfo.Status != "" {
|
||||
params["status"] = neInfo.Status
|
||||
}
|
||||
if neInfo.Remark != "" {
|
||||
params["remark"] = neInfo.Remark
|
||||
}
|
||||
if neInfo.CreateBy != "" {
|
||||
params["create_by"] = neInfo.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_info (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeInfoImpl) Update(neInfo model.NeInfo) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neInfo.NeType != "" {
|
||||
params["ne_type"] = neInfo.NeType
|
||||
}
|
||||
if neInfo.NeId != "" {
|
||||
params["ne_id"] = neInfo.NeId
|
||||
}
|
||||
if neInfo.RmUID != "" {
|
||||
params["rm_uid"] = neInfo.RmUID
|
||||
}
|
||||
if neInfo.NeName != "" {
|
||||
params["ne_name"] = neInfo.NeName
|
||||
}
|
||||
if neInfo.IP != "" {
|
||||
params["ip"] = neInfo.IP
|
||||
}
|
||||
if neInfo.Port > 0 {
|
||||
params["port"] = neInfo.Port
|
||||
}
|
||||
if neInfo.PvFlag != "" {
|
||||
params["pv_flag"] = neInfo.PvFlag
|
||||
}
|
||||
params["province"] = neInfo.Province
|
||||
params["vendor_name"] = neInfo.VendorName
|
||||
params["dn"] = neInfo.Dn
|
||||
params["ne_address"] = neInfo.NeAddress
|
||||
if neInfo.HostIDs != "" {
|
||||
params["host_ids"] = neInfo.HostIDs
|
||||
}
|
||||
params["remark"] = neInfo.Remark
|
||||
if neInfo.Status != "" {
|
||||
params["status"] = neInfo.Status
|
||||
}
|
||||
if neInfo.UpdateBy != "" {
|
||||
params["update_by"] = neInfo.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_info set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neInfo.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除网元信息
|
||||
func (r *NeInfoImpl) DeleteByIds(infoIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
|
||||
sql := "delete from ne_info where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(infoIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -1,24 +1,297 @@
|
||||
package repository
|
||||
|
||||
import "be.ems/src/modules/network_element/model"
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// INeLicense 网元授权激活信息 数据层接口
|
||||
type INeLicense interface {
|
||||
// SelectPage 根据条件分页查询字典类型
|
||||
SelectPage(query map[string]any) map[string]any
|
||||
"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/network_element/model"
|
||||
)
|
||||
|
||||
// SelectList 根据实体查询
|
||||
SelectList(neLicense model.NeLicense) []model.NeLicense
|
||||
// 实例化数据层 NeLicense 结构体
|
||||
var NewNeLicense = &NeLicense{
|
||||
selectSql: `select
|
||||
id, ne_type, ne_id, activation_request_code, license_path, serial_num, expiry_date, status, remark, create_by, create_time, update_by, update_time
|
||||
from ne_license`,
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
SelectByIds(ids []string) []model.NeLicense
|
||||
|
||||
// Insert 新增信息
|
||||
Insert(neLicense model.NeLicense) string
|
||||
|
||||
// Update 修改信息
|
||||
Update(neLicense model.NeLicense) int64
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
DeleteByIds(ids []string) int64
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"activation_request_code": "ActivationRequestCode",
|
||||
"license_path": "LicensePath",
|
||||
"serial_num": "SerialNum",
|
||||
"expiry_date": "ExpiryDate",
|
||||
"status": "Status",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeLicense 网元授权激活信息 数据层处理
|
||||
type NeLicense struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeLicense) convertResultRows(rows []map[string]any) []model.NeLicense {
|
||||
arr := make([]model.NeLicense, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeLicense{}
|
||||
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 *NeLicense) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["expiryDate"]; ok && v != "" {
|
||||
conditions = append(conditions, "expiry_date = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["createBy"]; ok && v != "" {
|
||||
conditions = append(conditions, "create_by like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_license"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeLicense) SelectList(neLicense model.NeLicense) []model.NeLicense {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neLicense.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neLicense.NeType)
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neLicense.NeId)
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
conditions = append(conditions, "expiry_date = ?")
|
||||
params = append(params, neLicense.ExpiryDate)
|
||||
}
|
||||
if neLicense.CreateBy != "" {
|
||||
conditions = append(conditions, "create_by like concat(?, '%')")
|
||||
params = append(params, neLicense.CreateBy)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by id asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeLicense) SelectByIds(cmdIds []string) []model.NeLicense {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeLicense{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeLicense) Insert(neLicense model.NeLicense) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neLicense.NeType != "" {
|
||||
params["ne_type"] = neLicense.NeType
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
params["ne_id"] = neLicense.NeId
|
||||
}
|
||||
if neLicense.ActivationRequestCode != "" {
|
||||
params["activation_request_code"] = neLicense.ActivationRequestCode
|
||||
}
|
||||
if neLicense.LicensePath != "" {
|
||||
params["license_path"] = neLicense.LicensePath
|
||||
}
|
||||
if neLicense.SerialNum != "" {
|
||||
params["serial_num"] = neLicense.SerialNum
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
params["expiry_date"] = neLicense.ExpiryDate
|
||||
}
|
||||
if neLicense.Status != "" {
|
||||
params["status"] = neLicense.Status
|
||||
}
|
||||
if neLicense.Remark != "" {
|
||||
params["remark"] = neLicense.Remark
|
||||
}
|
||||
if neLicense.CreateBy != "" {
|
||||
params["create_by"] = neLicense.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_license (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeLicense) Update(neLicense model.NeLicense) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neLicense.NeType != "" {
|
||||
params["ne_type"] = neLicense.NeType
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
params["ne_id"] = neLicense.NeId
|
||||
}
|
||||
if neLicense.ActivationRequestCode != "" {
|
||||
params["activation_request_code"] = neLicense.ActivationRequestCode
|
||||
}
|
||||
if neLicense.LicensePath != "" {
|
||||
params["license_path"] = neLicense.LicensePath
|
||||
}
|
||||
if neLicense.SerialNum != "" {
|
||||
params["serial_num"] = neLicense.SerialNum
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
params["expiry_date"] = neLicense.ExpiryDate
|
||||
}
|
||||
if neLicense.Status != "" {
|
||||
params["status"] = neLicense.Status
|
||||
}
|
||||
if neLicense.Remark != "" {
|
||||
params["remark"] = neLicense.Remark
|
||||
}
|
||||
if neLicense.UpdateBy != "" {
|
||||
params["update_by"] = neLicense.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_license set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neLicense.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeLicense) DeleteByIds(cmdIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
sql := "delete from ne_license where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -1,297 +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/network_element/model"
|
||||
)
|
||||
|
||||
// 实例化数据层 NewNeLicense 结构体
|
||||
var NewNeLicenseImpl = &NeLicenseImpl{
|
||||
selectSql: `select
|
||||
id, ne_type, ne_id, activation_request_code, license_path, serial_num, expiry_date, status, remark, create_by, create_time, update_by, update_time
|
||||
from ne_license`,
|
||||
|
||||
resultMap: map[string]string{
|
||||
"id": "ID",
|
||||
"ne_type": "NeType",
|
||||
"ne_id": "NeId",
|
||||
"activation_request_code": "ActivationRequestCode",
|
||||
"license_path": "LicensePath",
|
||||
"serial_num": "SerialNum",
|
||||
"expiry_date": "ExpiryDate",
|
||||
"status": "Status",
|
||||
"remark": "Remark",
|
||||
"create_by": "CreateBy",
|
||||
"create_time": "CreateTime",
|
||||
"update_by": "UpdateBy",
|
||||
"update_time": "UpdateTime",
|
||||
},
|
||||
}
|
||||
|
||||
// NeLicenseImpl 网元授权激活信息 数据层处理
|
||||
type NeLicenseImpl struct {
|
||||
// 查询视图对象SQL
|
||||
selectSql string
|
||||
// 结果字段与实体映射
|
||||
resultMap map[string]string
|
||||
}
|
||||
|
||||
// convertResultRows 将结果记录转实体结果组
|
||||
func (r *NeLicenseImpl) convertResultRows(rows []map[string]any) []model.NeLicense {
|
||||
arr := make([]model.NeLicense, 0)
|
||||
for _, row := range rows {
|
||||
item := model.NeLicense{}
|
||||
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 *NeLicenseImpl) SelectPage(query map[string]any) map[string]any {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if v, ok := query["neType"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["neId"]; ok && v != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["expiryDate"]; ok && v != "" {
|
||||
conditions = append(conditions, "expiry_date = ?")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
if v, ok := query["createBy"]; ok && v != "" {
|
||||
conditions = append(conditions, "create_by like concat(?, '%')")
|
||||
params = append(params, strings.Trim(v.(string), " "))
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
result := map[string]any{
|
||||
"total": 0,
|
||||
"rows": []model.NeHost{},
|
||||
}
|
||||
|
||||
// 查询数量 长度为0直接返回
|
||||
totalSql := "select count(1) as 'total' from ne_license"
|
||||
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
|
||||
}
|
||||
|
||||
// SelectList 根据实体查询
|
||||
func (r *NeLicenseImpl) SelectList(neLicense model.NeLicense) []model.NeLicense {
|
||||
// 查询条件拼接
|
||||
var conditions []string
|
||||
var params []any
|
||||
if neLicense.NeType != "" {
|
||||
conditions = append(conditions, "ne_type = ?")
|
||||
params = append(params, neLicense.NeType)
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
conditions = append(conditions, "ne_id = ?")
|
||||
params = append(params, neLicense.NeId)
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
conditions = append(conditions, "expiry_date = ?")
|
||||
params = append(params, neLicense.ExpiryDate)
|
||||
}
|
||||
if neLicense.CreateBy != "" {
|
||||
conditions = append(conditions, "create_by like concat(?, '%')")
|
||||
params = append(params, neLicense.CreateBy)
|
||||
}
|
||||
|
||||
// 构建查询条件语句
|
||||
whereSql := ""
|
||||
if len(conditions) > 0 {
|
||||
whereSql += " where " + strings.Join(conditions, " and ")
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
querySql := r.selectSql + whereSql + " order by id asc "
|
||||
results, err := datasource.RawDB("", querySql, params)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
}
|
||||
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询
|
||||
func (r *NeLicenseImpl) SelectByIds(cmdIds []string) []model.NeLicense {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
querySql := r.selectSql + " where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.RawDB("", querySql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("query err => %v", err)
|
||||
return []model.NeLicense{}
|
||||
}
|
||||
// 转换实体
|
||||
return r.convertResultRows(results)
|
||||
}
|
||||
|
||||
// Insert 新增信息
|
||||
func (r *NeLicenseImpl) Insert(neLicense model.NeLicense) string {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neLicense.NeType != "" {
|
||||
params["ne_type"] = neLicense.NeType
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
params["ne_id"] = neLicense.NeId
|
||||
}
|
||||
if neLicense.ActivationRequestCode != "" {
|
||||
params["activation_request_code"] = neLicense.ActivationRequestCode
|
||||
}
|
||||
if neLicense.LicensePath != "" {
|
||||
params["license_path"] = neLicense.LicensePath
|
||||
}
|
||||
if neLicense.SerialNum != "" {
|
||||
params["serial_num"] = neLicense.SerialNum
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
params["expiry_date"] = neLicense.ExpiryDate
|
||||
}
|
||||
if neLicense.Status != "" {
|
||||
params["status"] = neLicense.Status
|
||||
}
|
||||
if neLicense.Remark != "" {
|
||||
params["remark"] = neLicense.Remark
|
||||
}
|
||||
if neLicense.CreateBy != "" {
|
||||
params["create_by"] = neLicense.CreateBy
|
||||
params["create_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
|
||||
sql := "insert into ne_license (" + 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
|
||||
}
|
||||
|
||||
// Update 修改信息
|
||||
func (r *NeLicenseImpl) Update(neLicense model.NeLicense) int64 {
|
||||
// 参数拼接
|
||||
params := make(map[string]any)
|
||||
if neLicense.NeType != "" {
|
||||
params["ne_type"] = neLicense.NeType
|
||||
}
|
||||
if neLicense.NeId != "" {
|
||||
params["ne_id"] = neLicense.NeId
|
||||
}
|
||||
if neLicense.ActivationRequestCode != "" {
|
||||
params["activation_request_code"] = neLicense.ActivationRequestCode
|
||||
}
|
||||
if neLicense.LicensePath != "" {
|
||||
params["license_path"] = neLicense.LicensePath
|
||||
}
|
||||
if neLicense.SerialNum != "" {
|
||||
params["serial_num"] = neLicense.SerialNum
|
||||
}
|
||||
if neLicense.ExpiryDate != "" {
|
||||
params["expiry_date"] = neLicense.ExpiryDate
|
||||
}
|
||||
if neLicense.Status != "" {
|
||||
params["status"] = neLicense.Status
|
||||
}
|
||||
if neLicense.Remark != "" {
|
||||
params["remark"] = neLicense.Remark
|
||||
}
|
||||
if neLicense.UpdateBy != "" {
|
||||
params["update_by"] = neLicense.UpdateBy
|
||||
params["update_time"] = time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// 构建执行语句
|
||||
keys, values := repo.KeyValueByUpdate(params)
|
||||
sql := "update ne_license set " + strings.Join(keys, ",") + " where id = ?"
|
||||
|
||||
// 执行更新
|
||||
values = append(values, neLicense.ID)
|
||||
rows, err := datasource.ExecDB("", sql, values)
|
||||
if err != nil {
|
||||
logger.Errorf("update row : %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息
|
||||
func (r *NeLicenseImpl) DeleteByIds(cmdIds []string) int64 {
|
||||
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
|
||||
sql := "delete from ne_license where id in (" + placeholder + ")"
|
||||
parameters := repo.ConvertIdsSlice(cmdIds)
|
||||
results, err := datasource.ExecDB("", sql, parameters)
|
||||
if err != nil {
|
||||
logger.Errorf("delete err => %v", err)
|
||||
return 0
|
||||
}
|
||||
return results
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user