Browse Source

fix:bi看报加入知识资源库引用

zqbao 3 months ago
parent
commit
71e482b384

+ 32 - 0
controllers/bi_dashboard.go

@@ -100,6 +100,7 @@ func (this *BIDaShboardController) AddDashboard() {
 		return
 	}
 	detailList := make([]*bi_dashboard.BiDashboardDetail, 0)
+	var isAddResource bool
 	for i, v := range req.List {
 		item := &bi_dashboard.BiDashboardDetail{
 			BiDashboardId: int(id),
@@ -111,6 +112,9 @@ func (this *BIDaShboardController) AddDashboard() {
 			ModifyTime:    time.Now(),
 		}
 		detailList = append(detailList, item)
+		if v.Type == 3 {
+			isAddResource = true
+		}
 	}
 	err = bi_dashboard.AddBiDashboardDetailMulti(detailList)
 	if err != nil {
@@ -118,6 +122,18 @@ func (this *BIDaShboardController) AddDashboard() {
 		br.ErrMsg = "新增详情失败,Err:" + err.Error()
 		return
 	}
+	if isAddResource {
+		msg, err := services.SaveBiDashboardKnowledgeResource(item.BiDashboardId, this.SysUser.AdminId)
+		if err != nil {
+			if msg == "" {
+				msg = "新增知识资源失败"
+			}
+			br.Msg = msg
+			br.ErrMsg = "新增知识资源失败,Err:" + err.Error()
+			return
+		}
+
+	}
 
 	br.Ret = 200
 	br.Success = true
@@ -179,6 +195,7 @@ func (this *BIDaShboardController) EditDashboard() {
 	}
 
 	detailList := make([]*bi_dashboard.BiDashboardDetail, 0)
+	isEditResource := false
 	for _, v := range req.List {
 		item := &bi_dashboard.BiDashboardDetail{
 			BiDashboardId: req.BiDashboardId,
@@ -189,6 +206,9 @@ func (this *BIDaShboardController) EditDashboard() {
 			CreateTime:    time.Now(),
 			ModifyTime:    time.Now(),
 		}
+		if v.Type == 3 {
+			isEditResource = true
+		}
 		detailList = append(detailList, item)
 	}
 	err = bi_dashboard.AddBiDashboardDetailMulti(detailList)
@@ -197,6 +217,18 @@ func (this *BIDaShboardController) EditDashboard() {
 		br.ErrMsg = "新增详情失败,Err:" + err.Error()
 		return
 	}
+	if isEditResource {
+		// 添加知识资源引用
+		msg, err := services.SaveBiDashboardKnowledgeResource(item.BiDashboardId, this.SysUser.AdminId)
+		if err != nil {
+			if msg == "" {
+				msg = "编辑知识资源失败"
+			}
+			br.Msg = msg
+			br.ErrMsg = "编辑知识资源失败,Err:" + err.Error()
+			return
+		}
+	}
 
 	br.Ret = 200
 	br.Success = true

+ 146 - 13
controllers/knowledge/resource.go

@@ -36,14 +36,13 @@ type ResourceController struct {
 // @Param   StartDate   query   string  true       "开始时间"
 // @Param   EndDate   query   string  true       "结束时间"
 // @Param   Frequency   query   string  true       "频度"
-// @Param   ClassifyIdFirst   query   int  true       "一级分类id"
-// @Param   ClassifyIdSecond   query   int  true       "二级分类id"
-// @Param   ClassifyIdThird   query   int  true       "三级分类id"
+// @Param   ClassifyIds   query   int  true       "分类id, 多选, 英文逗号分隔"
 // @Param   State   query   int  true       "状态"
 // @Param   KeyWord   query   string  true       "搜索关键词"
 // @Param   PublishSort   query   string  true       "desc:降序,asc 升序(预留)"
 // @Param   FilterReportType   query   string  true       "筛选事件类型,1:公共研报,2:共享研报,3:我的研报"
 // @Param   IncludeFile   query   string  true       "是否包含文件, no:不包含"
+// @Param   SourceFrom   query   string  true       "来源, 用英文逗号分隔"
 // @Param   IsShowMe   query   string  true       "只看我, false:全部, true:只看我"
 // @Success 200 {object} knowledge.KnowledgeResourceListResp
 // @router /resource/list [get]
@@ -279,6 +278,137 @@ func (this *ResourceController) List() {
 	br.Data = resp
 }
 
+// Search
+// @Title 获取事件列表接口
+// @Description 获取事件列表
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   TimeType     query string true  "筛选的时间类别:publish_time(发布时间),modify_time(更新时间);approve_time(审批时间)"
+// @Param   StartDate   query   string  true       "开始时间"
+// @Param   EndDate   query   string  true       "结束时间"
+// @Param   Frequency   query   string  true       "频度"
+// @Param   ClassifyIds   query   int  true       "分类id, 多选, 英文逗号分隔"
+// @Param   SysUserIds   query   int  true       "用户id, 多选, 英文逗号分隔"
+// @Param   State   query   int  true       "状态"
+// @Param   KeyWord   query   string  true       "搜索关键词"
+// @Param   PublishSort   query   string  true       "desc:降序,asc 升序(预留)"
+// @Param   FilterReportType   query   string  true       "筛选事件类型,1:公共研报,2:共享研报,3:我的研报"
+// @Param   IncludeFile   query   string  true       "是否包含文件, no:不包含"
+// @Param   SourceFrom   query   string  true       "来源, 用英文逗号分隔"
+// @Param   IsShowMe   query   string  true       "只看我, false:全部, true:只看我"
+// @Success 200 {object} knowledge.KnowledgeResourceListResp
+// @router /resource/search_by_es [get]
+func (this *ResourceController) Search() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+
+	classifyIds := this.GetString("ClassifyIds")
+	// 添加人
+	addUserIds := this.GetString("SysUserIds")
+	// 标签
+	tagIds := this.GetString("TagIds")
+
+	keyWord := this.GetString("Keyword")
+	resourceType, _ := this.GetInt("ResourceType")
+
+	sourceFrom := this.GetString("SourceFrom")
+
+	includeFile := this.GetString("IncludeFile")
+
+	IsShowMe, _ := this.GetBool("IsShowMe")
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+
+	startSize = utils.StartIndex(currentIndex, pageSize)
+
+	isIncludeFile := true
+	if includeFile == "no" {
+		isIncludeFile = false
+	}
+	var searchUserIds []int
+	if IsShowMe {
+		searchUserIds = append(searchUserIds, this.SysUser.AdminId)
+	}
+	if addUserIds != "" {
+		// 转成数组,并把类型转成int
+		addUserIdsArr := strings.Split(addUserIds, ",")
+		for _, v := range addUserIdsArr {
+			addUserId, _ := strconv.Atoi(v)
+			searchUserIds = append(searchUserIds, addUserId)
+		}
+	}
+
+	var sourceFromArr []string
+	if sourceFrom != "" {
+		sourceFromArr = strings.Split(sourceFrom, ",")
+	}
+	var classifyIdsInt []int
+	if classifyIds != "" {
+		//转成数组,并把类型转成int
+		classifyIdsArr := strings.Split(classifyIds, ",")
+		for _, v := range classifyIdsArr {
+			classifyId, _ := strconv.Atoi(v)
+			classifyIdsInt = append(classifyIdsInt, classifyId)
+		}
+	}
+	var tagIdsInt []int
+	if tagIds != "" {
+		//转成数组,并把类型转成int
+		tagIdsArr := strings.Split(tagIds, ",")
+		for _, v := range tagIdsArr {
+			tagId, _ := strconv.Atoi(v)
+			tagIdsInt = append(tagIdsInt, tagId)
+		}
+	}
+	knowledges, total, err := knowledgeServ.SearchKnowledgeResourceByEs(resourceType, keyWord, searchUserIds, classifyIdsInt, sourceFromArr, tagIdsInt, isIncludeFile, startSize, pageSize)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+
+	list := make([]*knowledge.KnowledgeResourceList, 0, len(knowledges))
+	for _, v := range knowledges {
+		item := new(knowledge.KnowledgeResourceList)
+		item.KnowledgeResourceId = v.KnowledgeResourceId
+		item.ResourceType = v.ResourceType
+		item.ClassifyId = v.ClassifyId
+		item.Title = v.Title
+		item.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
+		item.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
+		item.State = v.State
+		item.ResourceCode = v.ResourceCode
+		item.AdminId = v.AdminId
+		item.AdminRealName = v.AdminRealName
+		item.SourceFrom = v.SourceFrom
+		item.TagId = v.TagId
+		item.StartTime = v.StartTime.Format(utils.FormatDateTime)
+		item.EndTime = v.EndTime.Format(utils.FormatDateTime)
+		list = append(list, item)
+	}
+
+	page := paging.GetPaging(currentIndex, pageSize, int(total))
+	resp := new(knowledge.KnowledgeResourceListResp)
+	resp.Paging = page
+	resp.List = list
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
 // Add
 // @Title 新增事件接口
 // @Description 新增事件(区分事件类型)
@@ -816,6 +946,13 @@ func (this *ResourceController) Delete() {
 		br.ErrMsg = "删除事件失败, Err: " + err.Error()
 		return
 	}
+	go func() {
+		item.IsDelete = 1
+		er := knowledgeServ.EsAddOrEditKnowledgeResource(item)
+		if er != nil {
+			utils.FileLog.Info("知识资源id:" + strconv.Itoa(req.KnowledgeResourceId) + ",删除事件同步es失败, Err: " + er.Error())
+		}
+	}()
 
 	br.Ret = 200
 	br.Success = true
@@ -1206,10 +1343,7 @@ func (this *ResourceController) TemplateDownload() {
 // @Title 获取bi看报中的知识资源列表
 // @Description 获取bi看报中的知识资源列表
 // @Success 200 {object} models.EdbdataClassifyResp
-// @Param   ResourceType   query   int  true       "资源库类型:0:事件库 1:政策库 2:观点库;3:知识库"
 // @Param   BiDashboardDetailId   query   int  true       "bi看板详情ID"
-// @Param   CurrentIndex   query   int  true       "当前页码,从1开始"
-// @Param   PageSize   query   int  true       "每页显示数量"
 // @router /resource/bi_dashboard/list [get]
 func (this *ResourceController) BiDashboardResourceList() {
 	br := new(models.BaseResponse).Init()
@@ -1219,11 +1353,11 @@ func (this *ResourceController) BiDashboardResourceList() {
 	}()
 
 	biDashboardDetailId, _ := this.GetInt("BiDashboardDetailId")
-	resourceType, _ := this.GetInt("ResourceType")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	pageSize, _ := this.GetInt("PageSize")
+	// resourceType, _ := this.GetInt("ResourceType")
+	// currentIndex, _ := this.GetInt("CurrentIndex")
+	// pageSize, _ := this.GetInt("PageSize")
 
-	resp, msg, err := knowledgeServ.GetKnowledgeResourceList(biDashboardDetailId, resourceType, currentIndex, pageSize)
+	resp, msg, err := knowledgeServ.GetKnowledgeResourceList(biDashboardDetailId)
 	if err != nil {
 		if msg == "" {
 			msg = "获取数据失败"
@@ -1243,7 +1377,7 @@ func (this *ResourceController) BiDashboardResourceList() {
 // @Title 获取bi看报中的知识资源列表
 // @Description 获取bi看报中的知识资源列表
 // @Success 200 {object} models.EdbdataClassifyResp
-// @Param   ResourceType   query   int  true       "资源库类型:0:事件库 1:政策库 2:观点库;3:知识库"
+// @Param   biDashboardDetailId   query   int  true       "看板详情ID"
 // @router /resource/bi_dashboard/cache/list [get]
 func (this *ResourceController) BiDashboardCacheResourceList() {
 	br := new(models.BaseResponse).Init()
@@ -1253,9 +1387,8 @@ func (this *ResourceController) BiDashboardCacheResourceList() {
 	}()
 
 	biDashboardDetailId, _ := this.GetInt("BiDashboardDetailId")
-	resourceType, _ := this.GetInt("ResourceType")
 
-	resp, msg, err := knowledgeServ.GetKnowledgeResourceTmpList(biDashboardDetailId, resourceType, this.SysUser.AdminId)
+	resp, msg, err := knowledgeServ.GetKnowledgeResourceTmpList(biDashboardDetailId, this.SysUser.AdminId)
 	if err != nil {
 		if msg == "" {
 			msg = "获取数据失败"

+ 7 - 0
models/bi_dashboard/bi_dashboard_detail.go

@@ -31,6 +31,13 @@ func GetBiDashboardDetailById(id int) (list []*BiDashboardDetail, err error) {
 	return
 }
 
+// GetBiDashboardDetailIdByBidashboardIdAndType 获取看板详情id
+func GetBiDashboardDetailIdByBidashboardIdAndType(bid int, t int) (ids []int, err error) {
+	sql := "SELECT bi_dashboard_detail_id FROM bi_dashboard_detail WHERE bi_dashboard_id = ? AND type = ?"
+	err = global.DEFAULT_DmSQL.Raw(sql, bid, t).Scan(&ids).Error
+	return
+}
+
 // multiAdd
 func AddBiDashboardDetailMulti(items []*BiDashboardDetail) (err error) {
 	return global.DEFAULT_DmSQL.CreateInBatches(items, 100).Error

+ 20 - 2
models/knowledge/knowledge_resource_bi_dashboard_detail.go

@@ -10,7 +10,7 @@ type KnowledgeResourceBiDashboardDetail struct {
 	Id                    int       `gorm:"column:id;primary_key"`
 	BiDashboardDetailId   int       `gorm:"column:bi_dashboard_detail_id;comment:关联的BI仪表盘详情ID"`
 	KnowledgeResourceId   int       `gorm:"column:knowledge_resource_id;comment:关联的知识库资源ID"`
-	KnowledgeResourceType string    `gorm:"column:knowledge_resource_type;comment:知识库资源类型:0事件库,1政策库,2观点库,3知识库"`
+	KnowledgeResourceType int       `gorm:"column:knowledge_resource_type;comment:知识库资源类型:0事件库,1政策库,2观点库,3知识库"`
 	CreateTime            time.Time `gorm:"column:create_time;comment:创建时间"`
 }
 
@@ -19,7 +19,25 @@ func (KnowledgeResourceBiDashboardDetail) TableName() string {
 }
 
 func (k *KnowledgeResourceBiDashboardDetail) BatchAdd(items []*KnowledgeResourceBiDashboardDetail) (err error) {
-	return global.DmSQL["rddp"].CreateInBatches(items, utils.MultiAddNum).Error
+	if len(items) == 0 {
+		return
+	}
+	tx := global.DmSQL["rddp"].Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+
+	sql := `DELETE FROM knowledge_resource_bi_dashboard_detail WHERE bi_dashboard_detail_id =? `
+	err = tx.Exec(sql, items[0].BiDashboardDetailId).Error
+	if err != nil {
+		return
+	}
+	err = global.DmSQL["rddp"].CreateInBatches(items, utils.MultiAddNum).Error
+	return
 }
 
 func GetKnowledgeResourceIdsByCondition(condition string, pars []interface{}) (resourceIds []int, err error) {

+ 9 - 0
routers/commentsRouter.go

@@ -5119,6 +5119,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta_gn/eta_api/controllers/knowledge:ResourceController"] = append(beego.GlobalControllerRouter["eta_gn/eta_api/controllers/knowledge:ResourceController"],
+        beego.ControllerComments{
+            Method: "Search",
+            Router: `/resource/search_by_es`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta_gn/eta_api/controllers/knowledge:ResourceController"] = append(beego.GlobalControllerRouter["eta_gn/eta_api/controllers/knowledge:ResourceController"],
         beego.ControllerComments{
             Method: "GetSourceFrom",

+ 47 - 1
services/bi_dashboard.go

@@ -3,13 +3,59 @@ package services
 import (
 	"encoding/json"
 	"eta_gn/eta_api/models/bi_dashboard"
+	"eta_gn/eta_api/models/knowledge"
 	"eta_gn/eta_api/utils"
 	"fmt"
+	"strconv"
 	"time"
-)
 
+	"github.com/go-redis/redis/v8"
+)
 
+func SaveBiDashboardKnowledgeResource(dashboardId, adminId int) (msg string, err error) {
+	ids, err := bi_dashboard.GetBiDashboardDetailIdByBidashboardIdAndType(dashboardId, 3)
+	if err != nil {
+		return
+	}
+	if len(ids) == 0 {
+		return
+	}
 
+	data, er := utils.Rc.RedisBytes(utils.CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE + strconv.Itoa(adminId))
+	req := new(knowledge.BiDashboardResourceAddReq)
+	if er != nil {
+		if er == redis.Nil {
+			msg = "暂无知识库"
+			err = nil
+			return
+		}
+		msg = "知识资源库添加失败"
+		return
+	}
+	if err = json.Unmarshal(data, &req); err != nil {
+		msg = "知识资源库添加失败"
+	}
+	defer func() {
+		if err == nil {
+			utils.Rc.Delete(utils.CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE + strconv.Itoa(adminId))
+		}
+	}()
+	insertMapping := make([]*knowledge.KnowledgeResourceBiDashboardDetail, 0, len(req.KnowledgeResourceList))
+	for _, v := range req.KnowledgeResourceList {
+		tmp := new(knowledge.KnowledgeResourceBiDashboardDetail)
+		tmp.BiDashboardDetailId = ids[0]
+		tmp.KnowledgeResourceId = v.KnowledgeResourceId
+		tmp.KnowledgeResourceType = 3
+		tmp.CreateTime = time.Now()
+		insertMapping = append(insertMapping, tmp)
+	}
+	obj := new(knowledge.KnowledgeResourceBiDashboardDetail)
+	err = obj.BatchAdd(insertMapping)
+	if err != nil {
+		msg = "知识资源库添加失败"
+	}
+	return
+}
 
 // UpdateBiDashboardEditing 更新看板编辑状态
 func UpdateBiDashboardEditing(boardId, status, userId int, userName string) (ret bi_dashboard.BiDashboardEditingCache, err error) {

+ 24 - 1
services/elastic/elastic.go

@@ -8,9 +8,10 @@ import (
 	"eta_gn/eta_api/models/data_manage"
 	"eta_gn/eta_api/utils"
 	"fmt"
-	"github.com/olivere/elastic/v7"
 	"strconv"
 	"strings"
+
+	"github.com/olivere/elastic/v7"
 )
 
 // indexName:索引名称
@@ -37,6 +38,28 @@ func EsCreateIndex(indexName, mappingJson string) (err error) {
 	return
 }
 
+// EsDeleteIndex 删除索引
+func EsDeleteIndex(indexName string) (err error) {
+	client := utils.EsClient
+
+	//定义表结构
+	exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
+	if err != nil {
+		return
+	}
+	if exists {
+		resp, err := client.DeleteIndex(indexName).Do(context.Background())
+		if err != nil {
+			fmt.Println("DeleteIndex Err:" + err.Error())
+			return err
+		}
+		fmt.Println(resp.Acknowledged)
+	} else {
+		fmt.Println(indexName + " 不存在")
+	}
+	return
+}
+
 // 删除数据
 func EsDeleteData(indexName, docId string) (err error) {
 	client := utils.EsClient

+ 186 - 0
services/knowledge/es.go

@@ -0,0 +1,186 @@
+package knowledge
+
+import (
+	"context"
+	"encoding/json"
+	"eta_gn/eta_api/models/knowledge"
+	"eta_gn/eta_api/utils"
+	"fmt"
+	"strconv"
+)
+
+// SearchChartInfoData 查询es中的图表数据
+func SearchKnowledgeResourceByEs(resourceType int, keywordStr string, showSysIds, classifyIds []int, sourceList []string, tagIds []int, isIncludeFile bool, from, size int) (list []*knowledge.KnowledgeResource, total int64, err error) {
+	indexName := utils.EsKnowledgeResourceIndexName
+	list = make([]*knowledge.KnowledgeResource, 0)
+	defer func() {
+		if err != nil {
+			fmt.Println("SearchKnowledgeResource Err:", err.Error())
+			utils.FileLog.Info("SearchKnowledgeResource Err:", err.Error())
+		}
+	}()
+	client := utils.EsClient
+
+	mustMap := make([]interface{}, 0)
+
+	mustMap = append(mustMap, map[string]interface{}{
+		"term": map[string]interface{}{
+			"ResourceType": resourceType,
+		},
+	})
+
+	//指标来源
+	if len(showSysIds) > 0 {
+		mustMap = append(mustMap, map[string]interface{}{
+			"terms": map[string]interface{}{
+				"SysUserId": showSysIds,
+			},
+		})
+	}
+	if len(tagIds) > 0 {
+		mustMap = append(mustMap, map[string]interface{}{
+			"terms": map[string]interface{}{
+				"TagId": tagIds,
+			},
+		})
+	}
+	if len(sourceList) > 0 {
+		mustMap = append(mustMap, map[string]interface{}{
+			"terms": map[string]interface{}{
+				"SourceFrom": sourceList,
+			},
+		})
+	}
+	if len(classifyIds) > 0 {
+		mustMap = append(mustMap, map[string]interface{}{
+			"terms": map[string]interface{}{
+				"ClassifyId": classifyIds,
+			},
+		})
+	}
+
+	mustMap = append(mustMap, map[string]interface{}{
+		"term": map[string]interface{}{
+			"IsDelete": 0,
+		},
+	})
+	if !isIncludeFile {
+		mustMap = append(mustMap, map[string]interface{}{
+			"term": map[string]interface{}{
+				"IsFile": 0,
+			},
+		})
+	}
+
+	shouldMap := map[string]interface{}{
+		"should": []interface{}{
+			map[string]interface{}{
+				"match": map[string]interface{}{
+					"Title": keywordStr,
+				},
+			},
+			// 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
+			map[string]interface{}{
+				"match": map[string]interface{}{
+					"Title": map[string]interface{}{
+						"query":    keywordStr,
+						"operator": "and",
+					},
+				},
+			},
+		},
+	}
+
+	mustMap = append(mustMap, map[string]interface{}{
+		"bool": shouldMap,
+	})
+
+	queryMap := map[string]interface{}{
+		"query": map[string]interface{}{
+			"bool": map[string]interface{}{
+				"must": mustMap,
+			},
+		},
+	}
+
+	//根据条件数量统计
+	requestTotalHits := client.Count(indexName).BodyJson(queryMap)
+	total, err = requestTotalHits.Do(context.Background())
+	if err != nil {
+		return
+	}
+
+	// 分页查询
+	queryMap["from"] = from
+	queryMap["size"] = size
+	jsonBytes, _ := json.Marshal(queryMap)
+	fmt.Println(string(jsonBytes))
+
+	request := client.Search(indexName).Source(queryMap) // sets the JSON request
+	searchMap := make(map[string]string)
+
+	searchResp, err := request.Do(context.Background())
+	if err != nil {
+		return
+	}
+	fmt.Println(searchResp)
+	fmt.Println(searchResp.Status)
+	if searchResp.Status != 0 {
+		return
+	}
+
+	if searchResp.Hits != nil {
+		for _, v := range searchResp.Hits.Hits {
+			if _, ok := searchMap[v.Id]; !ok {
+				itemJson, tmpErr := v.Source.MarshalJSON()
+				if tmpErr != nil {
+					err = tmpErr
+					fmt.Println("movieJson err:", err)
+					return
+				}
+				knowledgeItem := new(knowledge.KnowledgeResource)
+				tmpErr = json.Unmarshal(itemJson, &knowledgeItem)
+				if err != nil {
+					fmt.Println("json.Unmarshal chartInfoJson err:", err)
+					err = tmpErr
+					return
+				}
+				list = append(list, knowledgeItem)
+				searchMap[v.Id] = v.Id
+			}
+		}
+	}
+	return
+}
+
+// EsAddOrEditKnowledgeResource 新增/修改es中的知识资源数据
+func EsAddOrEditKnowledgeResource(item *knowledge.KnowledgeResource) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("EsAddOrEditData Err:", err.Error())
+			utils.FileLog.Info("EsAddOrEditKnowledgeResource err:", err)
+		}
+	}()
+	indexName := utils.EsKnowledgeResourceIndexName
+	client := utils.EsClient
+	itemJson, err := json.Marshal(item)
+	if err != nil {
+		fmt.Println("EsAddOrEditKnowledgeResource json.Marshal itemJson err:", err)
+		return
+	}
+
+	request := client.Index().Index(indexName).Id(strconv.Itoa(item.KnowledgeResourceId)).BodyJson(itemJson)
+	response, err := request.Do(context.Background())
+	if err != nil {
+		fmt.Println("add json:", string(itemJson))
+		fmt.Println("EsAddOrEditKnowledgeResource err:", err)
+		return
+	}
+	if response.Status == 0 {
+		err = fmt.Errorf("add knowledge resource to es failed, response result is %s", response.Result)
+		err = nil
+	} else {
+		fmt.Println("EsAddOrEditKnowledgeResource:", response.Status, response.Result)
+	}
+	return
+}

+ 22 - 20
services/knowledge/resource.go

@@ -152,9 +152,12 @@ func AddResource(req *knowledge.AddReq, sysUser *system.Admin) (item *knowledge.
 		err = fmt.Errorf("保存失败,Err:" + err.Error())
 		return
 	}
-	//todo 是否需要保存到es中
+	// 保存到es中
+	go EsAddOrEditKnowledgeResource(item)
+
 	return
 }
+
 func EditResource(resourceInfo *knowledge.KnowledgeResource, req knowledge.EditReq, sysUser *system.Admin) (err error, errMsg string) {
 	errMsg = `保存失败`
 	var startTime time.Time
@@ -278,6 +281,7 @@ func EditResource(resourceInfo *knowledge.KnowledgeResource, req knowledge.EditR
 	if err != nil {
 		return
 	}
+	go EsAddOrEditKnowledgeResource(resourceInfo)
 	return
 }
 
@@ -1058,7 +1062,7 @@ func addExcelResource(req *knowledge.AddReq, sysUser *system.Admin) (err error,
 	return
 }
 
-func GetKnowledgeResourceTmpList(dashboardDetailId, resourceType, adminId int) (resp *knowledge.BiDashboardResourceAddResp, msg string, err error) {
+func GetKnowledgeResourceTmpList(dashboardDetailId, adminId int) (resp *knowledge.BiDashboardResourceAddResp, msg string, err error) {
 	if dashboardDetailId <= 0 {
 		data, er := utils.Rc.RedisBytes(utils.CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE + strconv.Itoa(adminId))
 		req := new(knowledge.BiDashboardResourceAddReq)
@@ -1077,9 +1081,7 @@ func GetKnowledgeResourceTmpList(dashboardDetailId, resourceType, adminId int) (
 
 		selectedIds := make([]int, 0)
 		for _, item := range req.KnowledgeResourceList {
-			if item.ResourceType == resourceType {
-				selectedIds = append(selectedIds, item.KnowledgeResourceId)
-			}
+			selectedIds = append(selectedIds, item.KnowledgeResourceId)
 		}
 		knowledgeList, er := knowledge.GetKnowledgeResourceByIds(selectedIds)
 		if er != nil {
@@ -1089,8 +1091,8 @@ func GetKnowledgeResourceTmpList(dashboardDetailId, resourceType, adminId int) (
 		resp = new(knowledge.BiDashboardResourceAddResp)
 		resp.KnowledgeResourceList = toKnowledgeResourceList(knowledgeList)
 	} else {
-		condition := ` AND bi_dashboard_detail_id = ? AND knowledge_resource_type = ? `
-		pars := []interface{}{dashboardDetailId, resourceType}
+		condition := ` AND bi_dashboard_detail_id = ? `
+		pars := []interface{}{dashboardDetailId}
 		resourceIds, er := knowledge.GetKnowledgeResourceIdsByCondition(condition, pars)
 		if er != nil {
 			msg = "获取知识库模板列表失败"
@@ -1112,18 +1114,18 @@ func GetKnowledgeResourceTmpList(dashboardDetailId, resourceType, adminId int) (
 	return
 }
 
-func GetKnowledgeResourceList(dashboardDetailId, resourceType, currentIndex, pageSize int) (resp *knowledge.KnowledgeResourceListResp, msg string, err error) {
-	var startSize int
-	if pageSize <= 0 {
-		pageSize = utils.PageSize20
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	startSize = utils.StartIndex(currentIndex, pageSize)
+func GetKnowledgeResourceList(dashboardDetailId int) (resp *knowledge.KnowledgeResourceListResp, msg string, err error) {
+	// var startSize int
+	// if pageSize <= 0 {
+	// 	pageSize = utils.PageSize20
+	// }
+	// if currentIndex <= 0 {
+	// 	currentIndex = 1
+	// }
+	// startSize = utils.StartIndex(currentIndex, pageSize)
 
-	condition := ` AND bi_dashboard_detail_id = ? AND knowlege_resource_type = ? `
-	var pars = []interface{}{dashboardDetailId, resourceType}
+	condition := ` AND bi_dashboard_detail_id = ? `
+	var pars = []interface{}{dashboardDetailId}
 
 	resourceIds, err := knowledge.GetKnowledgeResourceIdsByCondition(condition, pars)
 	if err != nil {
@@ -1138,7 +1140,7 @@ func GetKnowledgeResourceList(dashboardDetailId, resourceType, currentIndex, pag
 		return
 	}
 
-	knowledgeList, err := knowledge.GetKnowledgeResourcePageByIds(resourceIds, startSize, pageSize)
+	knowledgeList, err := knowledge.GetKnowledgeResourceByIds(resourceIds)
 	if err != nil {
 		msg = "获取知识库列表失败"
 		return
@@ -1146,7 +1148,7 @@ func GetKnowledgeResourceList(dashboardDetailId, resourceType, currentIndex, pag
 
 	resp = new(knowledge.KnowledgeResourceListResp)
 	resp.List = toKnowledgeResourceList(knowledgeList)
-	resp.Paging = paging.GetPaging(currentIndex, pageSize, len(resourceIds))
+
 	return
 }
 

+ 123 - 0
services/task.go

@@ -2,6 +2,7 @@ package services
 
 import (
 	"eta_gn/eta_api/services/data"
+	"eta_gn/eta_api/services/elastic"
 	"eta_gn/eta_api/utils"
 	"fmt"
 	"strings"
@@ -19,6 +20,9 @@ func Task() {
 	// 进行指标替换操作
 	go DealReplaceEdbCache()
 
+	// 知识库索引创建
+	go EsCreateKnowledgeResourceIndexName()
+
 	fmt.Println("task end")
 }
 
@@ -39,3 +43,122 @@ func ImportManualDataRefresh() {
 		})
 	}
 }
+
+func EsCreateKnowledgeResourceIndexName() {
+	mappingJson := `
+	{
+  "mappings": {
+    "properties": {
+      "KnowledgeResourceId": {
+        "type": "integer"
+      },
+      "ResourceType": {
+        "type": "integer"
+      },
+      "ClassifyId": {
+        "type": "integer"
+      },
+      "Title": {
+        "type": "text",
+        "analyzer": "ik_max_word",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "CreateTime": {
+        "type": "text",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "ModifyTime": {
+        "type": "text",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "State": {
+        "type": "integer"
+      },
+      "Content": {
+        "type": "text",
+        "analyzer": "standard",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "ResourceCode": {
+        "type": "keyword"
+      },
+      "AdminId": {
+        "type": "integer"
+      },
+      "AdminRealName": {
+        "type": "text",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "SourceFrom": {
+        "type": "keyword"
+      },
+      "TagId": {
+        "type": "integer"
+      },
+      "StartTime": {
+        "type": "text",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "EndTime": {
+        "type": "text",
+        "fields": {
+          "keyword": {
+            "type": "keyword",
+            "ignore_above": 256
+          }
+        }
+      },
+      "IsFile": {
+        "type": "integer"
+      },
+      "FileUrl": {
+        "type": "keyword"
+      },
+      "IsDelete": {
+        "type": "integer"
+      }
+    }
+  }
+}
+	`
+	err := elastic.EsDeleteIndex(utils.EsKnowledgeResourceIndexName)
+	if err != nil {
+		fmt.Println("EsDeleteIndex err:", err)
+		utils.FileLog.Info("EsDeleteIndex err:", err)
+	}
+	err = elastic.EsCreateIndex(utils.EsKnowledgeResourceIndexName, mappingJson)
+	if err != nil {
+		fmt.Println("EsCreateKnowledgeResourceIndexName err:", err)
+		utils.FileLog.Info("EsCreateKnowledgeResourceIndexName err:", err)
+	}
+}

+ 2 - 0
utils/config.go

@@ -127,6 +127,7 @@ var (
 	MY_CHART_INDEX_NAME            string //研究图库(MY ETA)索引
 	EsSemanticAnalysisDocIndexName string //ES语义分析文档索引名
 	SmartReportIndexName           string //智能研报ES索引
+	EsKnowledgeResourceIndexName   string //ES知识库索引
 )
 
 var (
@@ -527,6 +528,7 @@ func init() {
 		EsEnglishReportIndexName = config["es_english_report_index_name"]
 		EsSemanticAnalysisDocIndexName = config["es_semantic_analysis_doc_index_name"]
 		SmartReportIndexName = config["es_smart_report_index_name"]
+		EsKnowledgeResourceIndexName = config["es_knowledge_resource_index_name"]
 	}
 
 	CrmEtaServerUrl = config["crm_eta_server_url"]

+ 1 - 1
utils/constants.go

@@ -226,7 +226,7 @@ const (
 	CACHE_EDB_TERMINAL_CODE_URL = "edb:terminal_code:edb_code:" // 指标与终端关系的缓存
 
 	CACHE_KEY_REPLACE_EDB                   = "eta:replace_edb"                   //系统用户操作日志队列
-	CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE = "eta:bi_dashboard:prepare_resource" // 准备看板资源
+	CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE = "eta:bi_dashboard:prepare_resource" // 准备引用到看板的知识资源
 )
 
 // 模板消息推送类型