소스 검색

Merge branch 'feature/eta1.4.3_yongyi_edb' into debug

xyxie 1 년 전
부모
커밋
33c3218253
10개의 변경된 파일957개의 추가작업 그리고 0개의 파일을 삭제
  1. 1 0
      .gitignore
  2. 174 0
      controllers/base_from_yongyi.go
  3. 333 0
      models/base_from_yongyi.go
  4. 3 0
      models/db.go
  5. 27 0
      routers/commentsRouter.go
  6. 5 0
      routers/router.go
  7. 259 0
      services/base_from_yongyi.go
  8. 150 0
      services/elastic/elastic.go
  9. 2 0
      utils/config.go
  10. 3 0
      utils/constants.go

+ 1 - 0
.gitignore

@@ -6,6 +6,7 @@
 .DS_Store
 binlog/
 /eta_index_lib.exe
+/eta_index_lib.tar.gz
 /eta_index_lib.exe~
 eta_index_lib
 /static/imgs/python/*

+ 174 - 0
controllers/base_from_yongyi.go

@@ -0,0 +1,174 @@
+package controllers
+
+import (
+	"encoding/json"
+	"eta/eta_index_lib/logic"
+	"eta/eta_index_lib/models"
+	"eta/eta_index_lib/services"
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"time"
+)
+
+// YongyiController 涌益咨询
+type YongyiController struct {
+	BaseAuthController
+}
+
+// Add
+// @Title 新增涌益咨询指标接口
+// @Description 新增涌益咨询指标接口
+// @Success 200 {object} models.AddEdbInfoReq
+// @router /add [post]
+func (this *YongyiController) Add() {
+	br := new(models.BaseResponse).Init()
+	var cacheKey string
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	yongyi := new(models.BaseFromYongyi)
+	source := yongyi.GetSource()
+	var req models.AddEdbInfoReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.EdbCode == "" {
+		br.Msg = "请输入指标编码!"
+		br.ErrMsg = "请输入指标编码,指标编码为空"
+		return
+	}
+	cacheKey = utils.CACHE_EDB_DATA_ADD + strconv.Itoa(source) + "_" + req.EdbCode
+	if utils.Rc.IsExist(cacheKey) {
+		br.Ret = 501
+		br.Success = true
+		br.Msg = "系统处理中,请稍后重试"
+		return
+	}
+	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
+	defer func() {
+		utils.Rc.Delete(cacheKey)
+	}()
+	err = yongyi.Add(req.EdbCode)
+	if err != nil {
+		br.Msg = "获取指标信息失败!"
+		br.ErrMsg = "获取指标信息失败 AddEdbDataFromYongyi,Err:" + err.Error()
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	return
+}
+
+// Refresh
+// @Title 刷新涌益咨询指标接口
+// @Description 刷新涌益咨询指标接口
+// @Success 200 {object} models.RefreshEdbInfoReq
+// @router /refresh [post]
+func (this *YongyiController) Refresh() {
+	br := new(models.BaseResponse).Init()
+	var cacheKey string
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	yongyi := new(models.BaseFromYongyi)
+	source := yongyi.GetSource()
+	var req models.RefreshEdbInfoReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.EdbCode == "" {
+		br.Msg = "请输入指标编码!"
+		br.ErrMsg = "请输入指标编码,指标编码为空"
+		return
+	}
+	if req.EdbInfoId < 0 {
+		br.Msg = "请输入指标ID!"
+		br.ErrMsg = "请输入指标ID"
+		return
+	}
+
+	// 获取指标详情
+	edbInfo, err := models.GetEdbInfoByEdbCode(source, req.EdbCode)
+	if err != nil {
+		br.Msg = "指标不存在!"
+		br.ErrMsg = "指标不存在"
+		return
+	}
+	cacheKey = utils.CACHE_EDB_DATA_REFRESH + strconv.Itoa(source) + "_" + req.EdbCode
+	if utils.Rc.IsExist(cacheKey) {
+		br.Ret = 501
+		br.Success = true
+		br.Msg = "系统处理中,请稍后重试"
+		return
+	}
+	utils.Rc.SetNX(cacheKey, 1, 1*time.Minute)
+	defer func() {
+		utils.Rc.Delete(cacheKey)
+	}()
+	if req.EdbInfoId <= 0 {
+		req.EdbInfoId = edbInfo.EdbInfoId
+	}
+	err = yongyi.Refresh(req.EdbInfoId, req.EdbCode, req.StartDate)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "刷新指标信息失败!"
+		br.ErrMsg = "刷新指标信息失败 RefreshEdbDataFromYongyi,Err:" + err.Error()
+		return
+	}
+	// 更新指标最大最小值
+	err, errMsg := models.UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo)
+	if err != nil {
+		br.Msg = errMsg
+		br.ErrMsg = err.Error()
+		return
+	}
+
+	// 更新ES
+	go logic.UpdateEs(edbInfo.EdbInfoId)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+}
+
+// HandleExcelData
+// @Title 处理涌益咨询指标的接口
+// @Description 处理涌益咨询指标的接口
+// @Success 200 {object} models.HandleYongyiExcelDataReq
+// @router /handle/excel_data [post]
+func (this *YongyiController) HandleExcelData() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	var req models.HandleYongyiExcelDataReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	// 处理excel表数据
+	err = services.HandleYongyiIndex(&req)
+	if err != nil {
+		fmt.Println("HandleMysteelIndex Err:" + err.Error())
+		br.Msg = "处理失败"
+		br.ErrMsg = "处理失败,Err:" + err.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "处理成功"
+}

+ 333 - 0
models/base_from_yongyi.go

@@ -0,0 +1,333 @@
+package models
+
+import (
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/beego/beego/v2/client/orm"
+)
+
+// BaseFromYongyi 涌溢咨询
+type BaseFromYongyi struct{}
+
+type BaseFromYongyiData struct {
+	YongyiDataId  int `orm:"column(yongyi_data_id);pk"`
+	YongyiIndexId int
+	IndexCode     string
+	DataTime      string
+	Value         string
+	CreateTime    time.Time
+	ModifyTime    time.Time
+	DataTimestamp int64
+}
+
+func GetBaseFromYongyiDataByCondition(condition string, pars []interface{}) (list []*BaseFromYongyiData, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM base_from_yongyi_data WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&list)
+	return
+}
+
+// Add 添加
+func (obj BaseFromYongyi) Add(edbCode string) (err error) {
+	o := orm.NewOrm()
+
+	var condition string
+	var pars []interface{}
+	if edbCode != "" {
+		condition += " AND index_code=? "
+		pars = append(pars, edbCode)
+	}
+	yongyiBaseDataAll, err := GetBaseFromYongyiDataByCondition(condition, pars)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		return
+	}
+	var isAdd bool
+	addSql := ` INSERT INTO edb_data_yongyi(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
+	existMap := make(map[string]string)
+	for _, sv := range yongyiBaseDataAll {
+		eDate := sv.DataTime
+		dataTime, err := time.Parse(utils.FormatDate, eDate)
+		if err != nil {
+			return err
+		}
+		timestamp := dataTime.UnixNano() / 1e6
+		timeStr := fmt.Sprintf("%d", timestamp)
+		if _, ok := existMap[eDate]; !ok {
+			addSql += GetAddSql("0", edbCode, eDate, timeStr, sv.Value)
+			isAdd = true
+		}
+		existMap[eDate] = sv.Value
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		utils.FileLog.Info("addSql:" + addSql)
+		_, err = o.Raw(addSql).Exec()
+		if err != nil {
+			return err
+		}
+	}
+	return
+}
+
+// Refresh 刷新涌益咨询指标数据
+func (obj BaseFromYongyi) Refresh(edbInfoId int, edbCode, startDate string) (err error) {
+	source := obj.GetSource()
+	o := orm.NewOrm()
+	if err != nil {
+		return
+	}
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	//计算数据
+	var condition string
+	var pars []interface{}
+
+	if edbCode != "" {
+		condition += " AND index_code=? "
+		pars = append(pars, edbCode)
+	}
+
+	if startDate != "" {
+		condition += " AND data_time>=? "
+		pars = append(pars, startDate)
+	}
+
+	yongyiDataList, err := GetBaseFromYongyiDataByCondition(condition, pars)
+	if err != nil {
+		return
+	}
+
+	// 真实数据的最大日期  , 插入规则配置的日期
+	var realDataMaxDate, edbDataInsertConfigDate time.Time
+	var edbDataInsertConfig *EdbDataInsertConfig
+	var isFindConfigDateRealData bool //是否找到配置日期的实际数据的值
+	{
+		edbDataInsertConfig, err = GetEdbDataInsertConfigByEdbId(edbInfoId)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			return
+		}
+		if edbDataInsertConfig != nil {
+			edbDataInsertConfigDate = edbDataInsertConfig.Date
+		}
+	}
+
+	var existCondition string
+	var existPars []interface{}
+
+	existCondition += " AND edb_info_id=? "
+	existPars = append(existPars, edbInfoId)
+	if startDate != "" {
+		existCondition += " AND data_time>=? "
+		existPars = append(existPars, startDate)
+	}
+
+	existList, err := GetEdbDataByCondition(source, 0, existCondition, existPars)
+	if err != nil {
+		return err
+	}
+	existMap := make(map[string]*EdbInfoSearchData)
+	for _, v := range existList {
+		existMap[v.DataTime] = v
+	}
+	addSql := ` INSERT INTO edb_data_yongyi(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
+	var isAdd bool
+	for _, v := range yongyiDataList {
+		item := v
+		eDate := item.DataTime
+		dataTime, err := time.ParseInLocation(utils.FormatDate, eDate, time.Local)
+		if err != nil {
+			return err
+		}
+		if findItem, ok := existMap[v.DataTime]; !ok {
+			sValue := item.Value
+
+			timestamp := dataTime.UnixNano() / 1e6
+			timeStr := fmt.Sprintf("%d", timestamp)
+
+			addSql += GetAddSql(edbInfoIdStr, edbCode, eDate, timeStr, sValue)
+			isAdd = true
+		} else {
+			if findItem != nil && utils.SubFloatToString(findItem.Value, 30) != item.Value {
+				err = ModifyEdbDataById(source, 0, findItem.EdbDataId, item.Value)
+				if err != nil {
+					return err
+				}
+			}
+		}
+
+		// 下面代码主要目的是处理掉手动插入的数据判断
+		{
+			if realDataMaxDate.IsZero() || dataTime.After(realDataMaxDate) {
+				realDataMaxDate = dataTime
+			}
+			if edbDataInsertConfigDate.IsZero() || dataTime.Equal(edbDataInsertConfigDate) {
+				isFindConfigDateRealData = true
+			}
+		}
+	}
+
+	// 处理手工数据补充的配置
+	HandleConfigInsertEdbData(realDataMaxDate, edbDataInsertConfig, edbInfoId, source, 0, existMap, isFindConfigDateRealData)
+
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = o.Raw(addSql).Exec()
+		if err != nil {
+			fmt.Println("RefreshEdbDataFromBaiinfo add Err", err.Error())
+			return
+		}
+	}
+	return
+}
+
+// GetSource 获取来源编码id
+func (obj BaseFromYongyi) GetSource() int {
+	return utils.DATA_SOURCE_YONYI
+}
+
+// GetSourceName 获取来源名称
+func (obj BaseFromYongyi) GetSourceName() string {
+	return utils.DATA_SOURCE_NAME_YONYI
+}
+
+type BaseFromYongyiIndex struct {
+	YongyiIndexId int64 `orm:"column(yongyi_index_id);pk"`
+	IndexCode     string
+	IndexName     string
+	Frequency     string
+	Unit          string
+	ClassifyId    int64
+	StartDate     string
+	EndDate       string
+	Sort          int
+	TerminalCode  string
+	CreateTime    time.Time
+	ModifyTime    time.Time
+}
+
+type BaseFromYongyiIndexList struct {
+	YongyiIndexId int64 `orm:"column(yongyi_index_id);pk"`
+	IndexCode     string
+	IndexName     string
+	Frequency     string
+	Unit          string
+	ClassifyId    int64
+	StartDate     string
+	EndDate       string
+	TerminalCode  string
+	CreateTime    string
+	ModifyTime    string
+}
+
+func (y *BaseFromYongyiData) GetByIndexCode(indexCode string) (list []*BaseFromYongyiData, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT * FROM base_from_yongyi_data WHERE index_code=? `
+	_, err = o.Raw(sql, indexCode).QueryRows(&list)
+	return
+}
+
+func (y *BaseFromYongyiData) AddMulti(item []*BaseFromYongyiData) (err error) {
+	o := orm.NewOrm()
+	_, err = o.InsertMulti(1, item)
+	return
+}
+
+// HandleYongyiExcelData 涌益咨询的excel数据
+type HandleYongyiExcelData struct {
+	//BaseFilePath   string
+	//RenameFilePath string
+	ClassifyName string `description:"指标目录"`
+	IndexName    string `description:"指标名称"`
+	IndexCode    string `description:"指标编码"`
+	Unit         string `description:"单位"`
+	Sort         int    `description:"排序号"`
+	Frequency    string `description:"频度"`
+	TerminalCode string `description:"编码"`
+	ExcelDataMap map[string]string
+}
+
+type HandleYongyiExcelDataReq struct {
+	List []*HandleYongyiExcelData
+}
+
+func (y *BaseFromYongyiData) GetMaxAndMinDateByIndexCode(indexCode string) (item *EdbInfoMaxAndMinInfo, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT MIN(data_time) AS min_date,MAX(data_time) AS max_date,MIN(value) AS min_value,MAX(value) AS max_value FROM base_from_yongyi_data WHERE index_code=? `
+	err = o.Raw(sql, indexCode).QueryRow(&item)
+	return
+}
+
+func (y *BaseFromYongyiIndex) ModifyIndexMaxAndMinDate(indexCode string, item *EdbInfoMaxAndMinInfo) (err error) {
+	o := orm.NewOrm()
+	sql := ` UPDATE base_from_yongyi_index SET start_date=?,end_date=?,modify_time=NOW() WHERE index_code=? `
+	_, err = o.Raw(sql, item.MinDate, item.MaxDate, indexCode).Exec()
+	return
+}
+
+func (y *BaseFromYongyiIndex) GetByIndexCode(indexCode string) (item *BaseFromYongyiIndex, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT * FROM base_from_yongyi_index WHERE index_code=? `
+	err = o.Raw(sql, indexCode).QueryRow(&item)
+	return
+}
+
+func (y *BaseFromYongyiIndex) GetByIndexId(id int) (item *BaseFromYongyiIndexList, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT * FROM base_from_yongyi_index WHERE yongyi_index_id=? `
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (y *BaseFromYongyiIndex) Add() (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(y)
+	return
+}
+
+// Update 修改
+func (y *BaseFromYongyiIndex) Update(updateCols []string) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Update(y, updateCols...)
+
+	return
+}
+
+// BaseFromYongyiClassify Yongyi原始数据分类表
+type BaseFromYongyiClassify struct {
+	ClassifyId      int64     `orm:"column(classify_id);pk"`
+	ClassifyName    string    `description:"分类名称"`
+	ParentId        int       `description:"父级id"`
+	SysUserId       int       `description:"创建人id"`
+	SysUserRealName string    `description:"创建人姓名"`
+	Level           int       `description:"层级"`
+	Sort            int       `description:"排序字段,越小越靠前,默认值:10"`
+	ModifyTime      time.Time `description:"修改时间"`
+	CreateTime      time.Time `description:"创建时间"`
+}
+
+func (y *BaseFromYongyiClassify) Add() (lastId int64, err error) {
+	o := orm.NewOrm()
+	lastId, err = o.Insert(y)
+	return
+}
+
+// Update 修改
+func (y *BaseFromYongyiClassify) Update(updateCols []string) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Update(y, updateCols...)
+
+	return
+}
+
+func (y *BaseFromYongyiClassify) GetByClassifyName(classifyName string) (item *BaseFromYongyiClassify, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT * FROM base_from_yongyi_classify WHERE classify_name=? `
+	err = o.Raw(sql, classifyName).QueryRow(&item)
+	return
+}

+ 3 - 0
models/db.go

@@ -111,6 +111,9 @@ func initBaseIndex() {
 		new(BaseFromTradeShanghaiIndex),
 		new(BaseFromTradeIneIndex),
 		new(BaseFromSmmClassify),
+		new(BaseFromYongyiIndex),
+		new(BaseFromYongyiData),
+		new(BaseFromYongyiClassify),
 	)
 }
 

+ 27 - 0
routers/commentsRouter.go

@@ -1024,6 +1024,33 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"],
+        beego.ControllerComments{
+            Method: "Add",
+            Router: `/add`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"],
+        beego.ControllerComments{
+            Method: "HandleExcelData",
+            Router: `/handle/excel_data`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:YongyiController"],
+        beego.ControllerComments{
+            Method: "Refresh",
+            Router: `/refresh`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_index_lib/controllers:ZzController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:ZzController"],
         beego.ControllerComments{
             Method: "Add",

+ 5 - 0
routers/router.go

@@ -164,6 +164,11 @@ func init() {
 				&controllers.BaiinfoController{},
 			),
 		),
+		beego.NSNamespace("/yongyi",
+			beego.NSInclude(
+				&controllers.YongyiController{},
+			),
+		),
 		beego.NSNamespace("/stock_plant",
 			beego.NSInclude(
 				&controllers.StockPlantController{},

+ 259 - 0
services/base_from_yongyi.go

@@ -0,0 +1,259 @@
+package services
+
+import (
+	"eta/eta_index_lib/logic"
+	"eta/eta_index_lib/models"
+	"eta/eta_index_lib/services/alarm_msg"
+	"eta/eta_index_lib/services/elastic"
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// HandleYongyiIndex 处理涌益咨询的excel数据
+func HandleYongyiIndex(req *models.HandleYongyiExcelDataReq) (err error) {
+	errMsgList := make([]string, 0)
+	defer func() {
+		if len(errMsgList) > 0 {
+			msg := fmt.Sprint("数据源-涌益咨询数据处理失败,err:", strings.Join(errMsgList, "\n"))
+			utils.FileLog.Info(msg)
+			go alarm_msg.SendAlarmMsg(msg, 3)
+		}
+	}()
+	for _, v := range req.List {
+		if v.IndexName == "" || v.IndexCode == "" {
+			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码%s或者指标ID%s为空:", v.IndexCode, v.IndexName))
+			continue
+		}
+		err = handleYongyiIndex(v)
+		if err != nil {
+			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码:%s, Err: %s", v.IndexCode, err))
+			return
+		}
+	}
+	return
+}
+
+func handleYongyiIndex(req *models.HandleYongyiExcelData) (err error) {
+	terminalCode := req.TerminalCode
+	indexName := req.IndexName
+	indexCode := req.IndexCode
+	excelDataMap := req.ExcelDataMap
+	errMsgList := make([]string, 0)
+	defer func() {
+		if len(errMsgList) > 0 {
+			msg := fmt.Sprint("数据源-涌益咨询数据处理失败,err:", strings.Join(errMsgList, "\n"))
+			utils.FileLog.Info(msg)
+			go alarm_msg.SendAlarmMsg(msg, 3)
+		}
+	}()
+	indexObj := new(models.BaseFromYongyiIndex)
+	dataObj := new(models.BaseFromYongyiData)
+	classifyObj := new(models.BaseFromYongyiClassify)
+
+	var indexId int64
+
+	addDataList := make([]*models.BaseFromYongyiData, 0)
+
+	exitDataMap := make(map[string]*models.BaseFromYongyiData)
+
+	// 修改指标信息
+	if indexName == "" {
+		utils.FileLog.Info("未刷新到指标数据:indexName:" + indexName)
+		return
+	}
+	// 判断目录是否存在
+	var classifyId int64
+	now := time.Now()
+	if req.ClassifyName != "" {
+		classifyObj, err = classifyObj.GetByClassifyName(req.ClassifyName)
+		if err != nil {
+			if err.Error() == utils.ErrNoRow() {
+				//新增分类
+				classifyObj = &models.BaseFromYongyiClassify{
+					ClassifyName:    req.ClassifyName,
+					ParentId:        0,
+					SysUserId:       0,
+					SysUserRealName: "",
+					Level:           1,
+					Sort:            0,
+					ModifyTime:      now,
+					CreateTime:      now,
+				}
+
+				classifyId, err = classifyObj.Add()
+				if err != nil {
+					err = fmt.Errorf("新增分类失败 Err:%s", err)
+					return
+				}
+				classifyObj.ClassifyId = classifyId
+				//修改排序
+				classifyObj.Sort = int(classifyId)
+				err = classifyObj.Update([]string{"Sort"})
+				if err != nil {
+					err = fmt.Errorf("修改分类排序失败 Err:%s", err)
+					return
+				}
+			} else {
+				return
+			}
+		} else {
+			classifyId = classifyObj.ClassifyId
+		}
+	}
+
+	//判断指标是否存在
+	var isAdd int
+	item, err := indexObj.GetByIndexCode(indexCode)
+	if err != nil {
+		if err.Error() == utils.ErrNoRow() {
+			isAdd = 1
+			err = nil
+		} else {
+			isAdd = -1
+			err = fmt.Errorf("查询数据源指标库失败 GetByIndexCode Err:%s", err)
+			return
+		}
+	}
+	if item != nil && item.YongyiIndexId > 0 {
+		fmt.Println("item:", item)
+		isAdd = 2
+	} else {
+		isAdd = 1
+	}
+
+	if isAdd == 1 {
+		indexObj.IndexCode = indexCode
+		indexObj.IndexName = indexName
+		indexObj.Frequency = req.Frequency
+		indexObj.ClassifyId = classifyId
+		indexObj.Unit = req.Unit
+		indexObj.Sort = req.Sort
+		indexObj.ModifyTime = time.Now()
+		indexObj.CreateTime = time.Now()
+		indexObj.TerminalCode = terminalCode
+		indexId, err = indexObj.Add()
+		if err != nil {
+			err = fmt.Errorf("数据源新增涌溢指标失败 Err:%s", err)
+			return
+		}
+		indexObj.YongyiIndexId = indexId
+	} else if isAdd == 2 {
+		if item.TerminalCode == `` && terminalCode != `` {
+			item.TerminalCode = terminalCode
+			err = item.Update([]string{"TerminalCode"})
+			if err != nil {
+				err = fmt.Errorf("数据源更新涌溢指标失败 Err:%s", err)
+				return
+			}
+		}
+
+		//获取已存在的所有数据
+		var exitDataList []*models.BaseFromYongyiData
+		exitDataList, err = dataObj.GetByIndexCode(indexCode)
+		if err != nil {
+			err = fmt.Errorf("数据源查询涌溢指标数据失败 Err:%s", err)
+			return
+		}
+		fmt.Println("exitDataListLen:", len(exitDataList))
+		for _, v := range exitDataList {
+			dateStr := v.DataTime
+			exitDataMap[dateStr] = v
+		}
+		indexId = item.YongyiIndexId
+	}
+
+	// 遍历excel数据,然后跟现有的数据做校验,不存在则入库
+	for date, value := range excelDataMap {
+		if findData, ok := exitDataMap[date]; !ok {
+			_, err = time.ParseInLocation(utils.FormatDate, date, time.Local)
+			if err != nil {
+				err = fmt.Errorf("%s 转换日期格式失败 Err:%s", date, err)
+				return
+			}
+			if !strings.Contains(value, "#N/A") {
+				var saveDataTime time.Time
+				if strings.Contains(date, "00:00:00") {
+					saveDataTime, err = time.Parse(utils.FormatDateTime, date)
+				} else {
+					saveDataTime, err = time.Parse(utils.FormatDate, date)
+				}
+				if err != nil {
+					err = fmt.Errorf("%s 转换日期格式失败 Err:%s", date, err)
+					continue
+				}
+				timestamp := saveDataTime.UnixNano() / 1e6
+
+				dataItem := new(models.BaseFromYongyiData)
+				dataItem.YongyiIndexId = int(indexId)
+				dataItem.IndexCode = indexCode
+				dataItem.DataTime = date
+				dataItem.Value = value
+				dataItem.CreateTime = time.Now()
+				dataItem.ModifyTime = time.Now()
+				dataItem.DataTimestamp = timestamp
+				addDataList = append(addDataList, dataItem)
+			}
+		} else {
+			if findData != nil && findData.Value != value && !strings.Contains(value, "#N/A") { //修改数据
+
+			}
+		}
+	}
+
+	if len(addDataList) > 0 {
+		err = dataObj.AddMulti(addDataList)
+		if err != nil {
+			err = fmt.Errorf("批量新增指标失败 Err:%s", err)
+			return
+		}
+
+		var dateItem *models.EdbInfoMaxAndMinInfo
+		dateItem, err = dataObj.GetMaxAndMinDateByIndexCode(indexCode)
+		if err != nil {
+			err = fmt.Errorf("查询指标最新日期失败 Err:%s", err)
+			return
+		}
+
+		go func() {
+			indexObj.ModifyIndexMaxAndMinDate(indexCode, dateItem)
+			UpdateEsBaseFromYongyi(int(indexObj.YongyiIndexId))
+		}()
+	}
+
+	// 同步刷新ETA指标库的指标
+	{
+		// 获取指标详情
+		baseObj := new(models.BaseFromYongyi)
+		var edbInfo *models.EdbInfo
+		edbInfo, err = models.GetEdbInfoByEdbCode(baseObj.GetSource(), indexCode)
+		if err != nil {
+			if err.Error() != utils.ErrNoRow() {
+				errMsgList = append(errMsgList, fmt.Sprint("刷新ETA指标异常,指标编码:", indexCode, err.Error()))
+				return
+			} else {
+				err = nil
+			}
+		}
+
+		// 已经加入到指标库的话,那么就去更新ETA指标库吧
+		if edbInfo != nil {
+			go logic.RefreshBaseEdbInfo(edbInfo, ``)
+		}
+	}
+	return
+}
+
+// UpdateEsBaseFromYongyi 更新数据源的es
+func UpdateEsBaseFromYongyi(yongyiIndexId int) (err error) {
+	indexObj := new(models.BaseFromYongyiIndex)
+	//添加es
+	itemInfo, err := indexObj.GetByIndexId(yongyiIndexId)
+	if err == nil {
+		err = elastic.EsAddOrEditBaseFromYongyiIndex(utils.ES_INDEX_BASE_FROM_YONGYI_INDEX, strconv.Itoa(yongyiIndexId), itemInfo)
+		return
+	}
+	return
+}

+ 150 - 0
services/elastic/elastic.go

@@ -5,8 +5,31 @@ import (
 	"eta/eta_index_lib/models"
 	"eta/eta_index_lib/utils"
 	"fmt"
+	"strings"
 )
 
+func EsCreateIndex(indexName, mappingJson string) (err error) {
+	client := utils.EsClient
+
+	//定义表结构
+	exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
+	if err != nil {
+		return
+	}
+	if !exists {
+		resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
+		//BodyJson(bodyJson).Do(context.Background())
+		if err != nil {
+			fmt.Println("CreateIndex Err:" + err.Error())
+			return err
+		}
+		fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
+	} else {
+		fmt.Println(indexName + " 已存在")
+	}
+	return
+}
+
 // EsAddOrEditEdbInfoData 新增/修改es中的指标数据
 func EsAddOrEditEdbInfoData(indexName, docId string, item *models.EdbInfoList) (err error) {
 	defer func() {
@@ -33,3 +56,130 @@ func EsAddOrEditEdbInfoData(indexName, docId string, item *models.EdbInfoList) (
 	}
 	return
 }
+
+// EsAddOrEditBaseFromYongyiIndex 新增/修改es中的原始涌溢指标
+func EsAddOrEditBaseFromYongyiIndex(indexName, docId string, item *models.BaseFromYongyiIndexList) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("EsAddOrEditData Err:", err.Error())
+		}
+	}()
+	client := utils.EsClient
+	if err != nil {
+		return
+	}
+
+	resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
+	if err != nil {
+		if strings.Contains(err.Error(), "no such index") {
+			//新增index
+			err = CreateEsEditBaseFromYongyiIndex()
+			if err != nil {
+				return
+			}
+			resp, err = client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
+			if err != nil {
+				return
+			}
+		} else {
+			fmt.Println("新增失败:", err.Error())
+			return err
+		}
+	}
+	fmt.Println(resp)
+	if resp.Status == 0 {
+		fmt.Println("新增成功", resp.Result)
+		err = nil
+	} else {
+		fmt.Println("AddData", resp.Status, resp.Result)
+	}
+	return
+}
+
+func CreateEsEditBaseFromYongyiIndex() (err error) {
+	indexName := utils.ES_INDEX_BASE_FROM_YONGYI_INDEX
+	mappingJson := `{
+  "mappings": {
+    "dynamic": true,
+    "properties": {
+      "YongyiIndexId": {
+         "type" : "long"
+      },
+      "IndexName": {
+        "type": "text",
+          "fields" : {
+            "keyword" : {
+              "type" : "keyword",
+              "ignore_above" : 256
+            }
+          }
+      },
+      "ClassifyId": {
+         "type" : "long"
+      },
+      "Frequency": {
+        "type": "text",
+          "fields" : {
+            "keyword" : {
+              "type" : "keyword",
+              "ignore_above" : 256
+            }
+          }
+      },
+      "IndexCode": {
+        "type": "text"
+      },
+      "Unit": {
+        "type": "text",
+          "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
+            }
+          }
+        },
+      "StartDate": {
+          "type" : "text",
+          "fields" : {
+            "keyword" : {
+              "type" : "keyword",
+              "ignore_above" : 256
+            }
+          }
+        },
+      "EndDate": {
+          "type" : "text",
+          "fields" : {
+            "keyword" : {
+              "type" : "keyword",
+              "ignore_above" : 256
+            }
+          }
+        },
+      "TerminalCode": {
+        "type": "text"
+      }
+    }
+  }
+}`
+	err = EsCreateIndex(indexName, mappingJson)
+	return
+}

+ 2 - 0
utils/config.go

@@ -28,6 +28,7 @@ var (
 
 // DATA_INDEX_NAME 数据指标库ES索引名称
 var DATA_INDEX_NAME string
+var ES_INDEX_BASE_FROM_YONGYI_INDEX string
 
 // 基础配置
 var (
@@ -214,6 +215,7 @@ func init() {
 		ES_USERNAME = config["es_username"]
 		ES_PASSWORD = config["es_password"]
 		DATA_INDEX_NAME = config["data_index_name"]
+		ES_INDEX_BASE_FROM_YONGYI_INDEX = config["es_index_base_from_yongyi_index"]
 	}
 
 	//日志配置

+ 3 - 0
utils/constants.go

@@ -20,6 +20,8 @@ const (
 	PageSize30                 = 30
 )
 
+const DATA_SOURCE_YONYI = 76 //涌益咨询 =
+
 // 数据来源渠道
 const (
 	DATA_SOURCE_THS                                  = iota + 1 //同花顺
@@ -175,6 +177,7 @@ const (
 	DATA_SOURCE_NAME_CALCULATE_ZSXY                       = `指数修匀`              //指数修匀->72
 	DATA_SOURCE_NAME_PREDICT_CALCULATE_ZSXY               = `预测指数修匀`            //预测指数修匀->73
 	DATA_SOURCE_NAME_CALCULATE_ZDYFX                      = `自定义分析`             //自定义分析->74
+	DATA_SOURCE_NAME_YONYI                                = `涌益咨询`              // 涌益咨询
 )
 
 // 基础数据初始化日期