Ver Fonte

普兰指标数据

xyxie há 3 semanas atrás
pai
commit
45aaecd596

+ 175 - 0
controllers/base_from_purang.go

@@ -0,0 +1,175 @@
+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"
+)
+
+// PurangController 普兰金融
+type BaseFromPurangController struct {
+	BaseAuthController
+}
+
+// Add
+// @Title 新增普兰金融指标接口
+// @Description 新增普兰金融指标接口
+// @Success 200 {object} models.AddEdbInfoReq
+// @router /add [post]
+func (this *BaseFromPurangController) Add() {
+	br := new(models.BaseResponse).Init()
+	var cacheKey string
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	purang := new(models.BaseFromPurang)
+	source := purang.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 = purang.Add(req.EdbCode)
+	if err != nil {
+		br.Msg = "获取指标信息失败!"
+		br.ErrMsg = "获取指标信息失败 AddEdbDataFromPurang,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 *BaseFromPurangController) Refresh() {
+	br := new(models.BaseResponse).Init()
+	var cacheKey string
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	purang := new(models.BaseFromPurang)
+	source := purang.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 = purang.Refresh(req.EdbInfoId, req.EdbCode, req.StartDate)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "刷新指标信息失败!"
+		br.ErrMsg = "刷新指标信息失败 RefreshEdbDataFromPurang,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.HandlePurangExcelDataReq
+// @router /handle/excel_data [post]
+func (this *BaseFromPurangController) HandleExcelData() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	var req models.HandlePurangExcelDataReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	// 处理excel表数据
+	err = services.HandlePurangIndex(&req)
+	if err != nil {
+		fmt.Println("HandlePurangIndex Err:" + err.Error())
+		br.Msg = "处理失败"
+		br.ErrMsg = "处理失败,Err:" + err.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "处理成功"
+} 

+ 346 - 0
models/base_from_purang_index.go

@@ -0,0 +1,346 @@
+package models
+
+import (
+	"bytes"
+	sql2 "database/sql"
+	"eta/eta_index_lib/global"
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// BaseFromPurang 普兰金融
+type BaseFromPurang struct{}
+
+type BaseFromPurangData struct {
+	BaseFromPurangDataId  int `gorm:"column:base_from_purang_data_id;primaryKey"`
+	BaseFromPurangIndexId int
+	IndexCode              string
+	DataTime               time.Time
+	Value                  string
+	CreateTime             time.Time
+	ModifyTime             time.Time
+	DataTimestamp          int64
+}
+
+func GetBaseFromPurangDataByCondition(condition string, pars []interface{}) (list []*BaseFromPurangData, err error) {
+	sql := `SELECT * FROM base_from_purang_data WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	err = global.DEFAULT_DB.Raw(sql, pars...).Find(&list).Error
+	return
+}
+
+// Add 添加
+func (obj BaseFromPurang) Add(edbCode string) (err error) {
+	var condition string
+	var pars []interface{}
+	if edbCode != "" {
+		condition += " AND index_code=? "
+		pars = append(pars, edbCode)
+	}
+	purangBaseDataAll, err := GetBaseFromPurangDataByCondition(condition, pars)
+	if err != nil && !utils.IsErrNoRow(err) {
+		return
+	}
+	var isAdd bool
+	addSql := ` INSERT INTO edb_data_purang(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
+	length := len(purangBaseDataAll)
+	existMap := make(map[string]struct{}, length)
+	nowStr := time.Now().Format(utils.FormatDateTime)
+	var buffer bytes.Buffer
+	buffer.WriteString(addSql)
+	for i := 0; i < length; i++ {
+		sv := purangBaseDataAll[i]
+		eDate := sv.DataTime.Format(utils.FormatDate)
+		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 {
+			sqlTmp := GetAddSqlV2("0", edbCode, eDate, timeStr, sv.Value, nowStr)
+			buffer.WriteString(sqlTmp)
+			isAdd = true
+		}
+		existMap[eDate] = struct{}{}
+	}
+	if isAdd {
+		addSql = buffer.String()
+		addSql = strings.TrimRight(addSql, ",")
+		utils.FileLog.Info("addSql:" + addSql)
+		err = global.DEFAULT_DB.Exec(addSql).Error
+		if err != nil {
+			return err
+		}
+	}
+	return
+}
+
+// Refresh 刷新普兰金融指标数据
+func (obj BaseFromPurang) Refresh(edbInfoId int, edbCode, startDate string) (err error) {
+	source := obj.GetSource()
+	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)
+	}
+
+	PurangDataList, err := GetBaseFromPurangDataByCondition(condition, pars)
+	if err != nil {
+		return
+	}
+
+	// 真实数据的最大日期  , 插入规则配置的日期
+	var realDataMaxDate, edbDataInsertConfigDate time.Time
+	var edbDataInsertConfig *EdbDataInsertConfig
+	var isFindConfigDateRealData bool //是否找到配置日期的实际数据的值
+	{
+		edbDataInsertConfig, err = GetEdbDataInsertConfigByEdbId(edbInfoId)
+		if err != nil && !utils.IsErrNoRow(err) {
+			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_purang_risk(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
+	var isAdd bool
+	for _, v := range PurangDataList {
+		item := v
+		eDate := item.DataTime.Format(utils.FormatDate)
+		dataTime := item.DataTime
+		if findItem, ok := existMap[eDate]; !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 = global.DEFAULT_DB.Exec(addSql).Error
+		if err != nil {
+			fmt.Println("RefreshEdbDataFromBaiinfo add Err", err.Error())
+			return
+		}
+	}
+	return
+}
+
+// GetSource 获取来源编码id
+func (obj BaseFromPurang) GetSource() int {
+	return utils.DATA_SOURCE_PuRang
+}
+
+// GetSourceName 获取来源名称
+func (obj BaseFromPurang) GetSourceName() string {
+	return utils.DATA_SOURCE_NAME_PuRang
+}
+
+type BaseFromPurangIndex struct {
+	BaseFromPurangIndexId int64 `gorm:"column:base_from_purang_index_id;primaryKey"`
+	IndexCode              string
+	IndexName              string
+	Frequency              string
+	Unit                   string
+	StartDate              time.Time
+	EndDate                time.Time
+	ClassifyId             int64
+	Sort                   int
+	BaseFileName           string
+	RenameFileName         string
+	TerminalCode           string
+	CreateTime             time.Time
+	ModifyTime             time.Time
+}
+
+type BaseFromPurangIndexList struct {
+	BaseFromPurangIndexId int64 `gorm:"column:base_from_purang_index_id;primaryKey"`
+	IndexCode              string
+	IndexName              string
+	Frequency              string
+	Unit                   string
+	Sort                   int
+	ClassifyId             int64
+	StartDate              time.Time
+	EndDate                time.Time
+	TerminalCode           string
+	CreateTime             time.Time
+	ModifyTime             time.Time
+}
+
+func (y *BaseFromPurangData) GetByIndexCode(indexCode string) (list []*BaseFromPurangData, err error) {
+	sql := ` SELECT * FROM base_from_purang_data WHERE index_code=? `
+	err = global.DEFAULT_DB.Raw(sql, indexCode).Find(&list).Error
+	return
+}
+
+func (y *BaseFromPurangData) AddMulti(item []*BaseFromPurangData) (err error) {
+	err = global.DEFAULT_DB.CreateInBatches(&item, 1).Error
+	return
+}
+
+// Update 修改
+func (y *BaseFromPurangData) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_DB.Model(&y).Select(updateCols).Updates(&y).Error
+	return
+}
+
+// HandlePurangExcelData 涌益咨询的excel数据
+type HandlePurangExcelData struct {
+	ClassifyName       string `description:"指标目录"`
+	ParentClassifyName string `description:"父级指标目录"`
+	ClassifySort       int    `description:"指标目录排序号"`
+	IndexName          string `description:"指标名称"`
+	IndexCode          string `description:"指标编码"`
+	Unit               string `description:"单位"`
+	Sort               int    `description:"排序号"`
+	Frequency          string `description:"频度"`
+	ExcelDataMap       map[string]string
+}
+
+type HandlePurangExcelDataReq struct {
+	List         []*HandlePurangExcelData
+	TerminalCode string `description:"编码"`
+}
+
+func (y *BaseFromPurangData) GetMaxAndMinDateByIndexCode(indexCode string) (item *EdbInfoMaxAndMinInfo, err error) {
+	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_purang_data WHERE index_code=? `
+	err = global.DEFAULT_DB.Raw(sql, indexCode).First(&item).Error
+	sql = ` SELECT value AS latest_value FROM %s WHERE index_code=? ORDER BY data_time DESC LIMIT 1 `
+	sql = fmt.Sprintf(sql, "base_from_purang_data")
+	var latestValueNull sql2.NullFloat64
+	err = global.DEFAULT_DB.Raw(sql, indexCode).Scan(&latestValueNull).Error
+	if err == nil && latestValueNull.Valid {
+		item.LatestValue = latestValueNull.Float64
+	}
+	return
+}
+
+func (y *BaseFromPurangIndex) ModifyIndexMaxAndMinDate(indexCode string, item *EdbInfoMaxAndMinInfo) (err error) {
+	sql := ` UPDATE base_from_purang_index SET start_date=?,end_date=?, end_value=?, modify_time=NOW() WHERE index_code=? `
+	err = global.DEFAULT_DB.Exec(sql, item.MinDate, item.MaxDate, item.LatestValue, indexCode).Error
+	return
+}
+
+func (y *BaseFromPurangIndex) GetByIndexCode(indexCode string) (item *BaseFromPurangIndex, err error) {
+	sql := ` SELECT * FROM base_from_purang_index WHERE index_code=? `
+	err = global.DEFAULT_DB.Raw(sql, indexCode).First(&item).Error
+	return
+}
+
+func (y *BaseFromPurangIndex) Add() (lastId int64, err error) {
+	err = global.DEFAULT_DB.Create(&y).Error
+	if err != nil {
+		return
+	}
+	lastId = y.BaseFromPurangIndexId
+	return
+}
+
+// Update 修改
+func (y *BaseFromPurangIndex) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_DB.Model(&y).Select(updateCols).Updates(&y).Error
+	return
+}
+
+// BaseFromPurangClassify Purang原始数据分类表
+type BaseFromPurangClassify struct {
+	ClassifyId      int64     `gorm:"column:classify_id;primaryKey"`
+	ClassifyName    string    `description:"分类名称"`
+	ClassifyNameEn  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 *BaseFromPurangClassify) Add() (lastId int64, err error) {
+	err = global.DEFAULT_DB.Create(&y).Error
+	if err != nil {
+		return
+	}
+	lastId = int64(y.ClassifyId)
+	return
+}
+
+// Update 修改
+func (y *BaseFromPurangClassify) Update(updateCols []string) (err error) {
+	err = global.DEFAULT_DB.Model(&y).Select(updateCols).Updates(&y).Error
+	return
+}
+
+func (y *BaseFromPurangClassify) GetByClassifyName(classifyName string) (item *BaseFromPurangClassify, err error) {
+	sql := ` SELECT * FROM base_from_purang_classify WHERE classify_name=? `
+	err = global.DEFAULT_DB.Raw(sql, classifyName).First(&item).Error
+	return
+}
+
+func (y *BaseFromPurangClassify) GetParentClassify() (items []*BaseFromPurangClassify, err error) {
+	sql := ` SELECT * FROM base_from_purang_classify WHERE parent_id=0 `
+	err = global.DEFAULT_DB.Raw(sql).Find(&items).Error
+	return
+} 

+ 3 - 0
models/db.go

@@ -182,6 +182,9 @@ func initBaseIndex() {
 		new(BaseFromGprRiskIndex),
 		new(BaseFromGprRiskData),
 		new(BaseFromGprRiskClassify),
+		new(BaseFromPurangIndex),
+		new(BaseFromPurangData),
+		new(BaseFromPurangClassify),
 	)
 }
 

+ 27 - 0
routers/commentsRouter.go

@@ -250,6 +250,33 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromPurangController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromPurangController"],
+        beego.ControllerComments{
+            Method: "Add",
+            Router: `/add`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromPurangController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromPurangController"],
+        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:BaseFromPurangController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromPurangController"],
+        beego.ControllerComments{
+            Method: "Refresh",
+            Router: `/refresh`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromRzdController"] = append(beego.GlobalControllerRouter["eta/eta_index_lib/controllers:BaseFromRzdController"],
         beego.ControllerComments{
             Method: "Add",

+ 5 - 0
routers/router.go

@@ -347,6 +347,11 @@ func init() {
 				&controllers.GprRiskController{},
 			),
 		),
+		beego.NSNamespace("/purang",
+			beego.NSInclude(
+				&controllers.BaseFromPurangController{},
+			),
+		),
 	)
 	beego.AddNamespace(ns)
 }

+ 309 - 0
services/base_from_purang.go

@@ -0,0 +1,309 @@
+package services
+
+import (
+	"eta/eta_index_lib/logic"
+	"eta/eta_index_lib/models"
+	"eta/eta_index_lib/services/alarm_msg"
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// HandlePurangIndex 处理普兰金融的excel数据
+func HandlePurangIndex(req *models.HandlePurangExcelDataReq) (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)
+		}
+	}()
+	// 查询所有的一级分类
+	classifyObj := new(models.BaseFromPurangClassify)
+	classifyList, err := classifyObj.GetParentClassify()
+	if err != nil {
+		err = fmt.Errorf("查询一级目录信息失败 Err:%s", err)
+		return
+	}
+	classifyMap := make(map[string]int, 0)
+	for _, v := range classifyList {
+		classifyMap[v.ClassifyName] = int(v.ClassifyId)
+	}
+
+	for _, v := range req.List {
+		if v.IndexName == "" || v.IndexCode == "" {
+			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码%s或者指标ID%s为空:", v.IndexCode, v.IndexName))
+			continue
+		}
+		err = handlePurangIndex(v, req.TerminalCode, classifyMap)
+		if err != nil {
+			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码:%s, Err: %s", v.IndexCode, err))
+			return
+		}
+	}
+	return
+}
+
+func handlePurangIndex(req *models.HandlePurangExcelData, terminalCode string, classifyMap map[string]int) (err error) {
+	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.BaseFromPurangIndex)
+	dataObj := new(models.BaseFromPurangData)
+	classifyObj := new(models.BaseFromPurangClassify)
+
+	var indexId int64
+
+	addDataList := make([]*models.BaseFromPurangData, 0)
+
+	exitDataMap := make(map[string]*models.BaseFromPurangData)
+
+	// 修改指标信息
+	if indexName == "" {
+		utils.FileLog.Info("未刷新到指标数据:indexName:" + indexName)
+		return
+	}
+	// 判断目录是否存在
+	var classifyId int64
+	now := time.Now()
+	if req.ClassifyName != "" {
+		classifyParentId := 0
+		level := 1
+		classifyParentId, _ = classifyMap[req.ParentClassifyName]
+		if classifyParentId > 0 {
+			level = 2
+		}
+		classifyObj, err = classifyObj.GetByClassifyName(req.ClassifyName)
+		if err != nil {
+			if err.Error() == utils.ErrNoRow() {
+				//新增分类
+				classifyObj = &models.BaseFromPurangClassify{
+					ClassifyName:    req.ClassifyName,
+					ClassifyNameEn:  req.ClassifyName,
+					ParentId:        classifyParentId,
+					SysUserId:       0,
+					SysUserRealName: "",
+					Level:           level,
+					Sort:            req.ClassifySort,
+					ModifyTime:      now,
+					CreateTime:      now,
+				}
+
+				classifyId, err = classifyObj.Add()
+				if err != nil {
+					err = fmt.Errorf("新增分类失败 Err:%s", err)
+					return
+				}
+				classifyObj.ClassifyId = classifyId
+			} else {
+				return
+			}
+		} else {
+			classifyId = classifyObj.ClassifyId
+			classifyObj.ModifyTime = now
+			//classifyObj.Sort = req.ClassifySort
+			classifyObj.ParentId = classifyParentId
+			//e := classifyObj.Update([]string{"ParentId", "Sort", "ModifyTime"})
+			e := classifyObj.Update([]string{"ParentId", "ModifyTime"})
+			if e != nil {
+				fmt.Println("classifyObj Update Err:" + e.Error())
+				return
+			}
+		}
+	}
+
+	//判断指标是否存在
+	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.BaseFromPurangIndexId > 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.BaseFromPurangIndexId = indexId
+	} else if isAdd == 2 {
+		indexId = item.BaseFromPurangIndexId
+		if item.TerminalCode == `` && terminalCode != `` {
+			item.TerminalCode = terminalCode
+			err = item.Update([]string{"TerminalCode"})
+			if err != nil {
+				err = fmt.Errorf("数据源更新普兰金融指标失败 Err:%s", err)
+				return
+			}
+		}
+
+		indexObj.BaseFromPurangIndexId = item.BaseFromPurangIndexId
+		indexObj.IndexName = indexName
+		indexObj.Frequency = req.Frequency
+		indexObj.ClassifyId = classifyId
+		indexObj.Unit = req.Unit
+		indexObj.Sort = req.Sort
+		indexObj.ModifyTime = time.Now()
+
+		//修改数据
+		updateColsArr := make([]string, 0)
+		updateColsArr = append(updateColsArr, "index_name")
+		updateColsArr = append(updateColsArr, "classify_id")
+		updateColsArr = append(updateColsArr, "frequency")
+		updateColsArr = append(updateColsArr, "sort")
+		updateColsArr = append(updateColsArr, "unit")
+		updateColsArr = append(updateColsArr, "modify_time")
+
+		e := indexObj.Update(updateColsArr)
+		if e != nil {
+			fmt.Println("Index Update Err:" + e.Error())
+			return
+		}
+	}
+
+	//获取已存在的所有数据
+	var exitDataList []*models.BaseFromPurangData
+	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.Format(utils.FormatDate)
+		exitDataMap[dateStr] = v
+	}
+
+	// 遍历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.BaseFromPurangData)
+			dataItem.BaseFromPurangIndexId = int(indexId)
+			dataItem.IndexCode = indexCode
+			dataItem.DataTime = saveDataTime
+			dataItem.Value = value
+			dataItem.CreateTime = time.Now()
+			dataItem.ModifyTime = time.Now()
+			dataItem.DataTimestamp = timestamp
+			addDataList = append(addDataList, dataItem)
+			if len(addDataList) > 500 {
+				err = dataObj.AddMulti(addDataList)
+				if err != nil {
+					err = fmt.Errorf("批量新增指标失败 Err:%s", err)
+					return
+				}
+				addDataList = make([]*models.BaseFromPurangData, 0)
+			}
+			//}
+		} else {
+			if findData != nil && findData.Value != value && !strings.Contains(value, "#N/A") { //修改数据
+				// 过滤0.50和0.5的比较
+				oldV, _ := strconv.ParseFloat(findData.Value, 64)
+				newV, _ := strconv.ParseFloat(value, 64)
+				if oldV == newV {
+					continue
+				}
+				dataObj.BaseFromPurangIndexId = findData.BaseFromPurangIndexId
+				dataObj.Value = value
+				dataObj.ModifyTime = time.Now()
+
+				updateDataColsArr := make([]string, 0)
+				updateDataColsArr = append(updateDataColsArr, "value")
+				updateDataColsArr = append(updateDataColsArr, "modify_time")
+				dataObj.Update(updateDataColsArr)
+			}
+		}
+	}
+
+	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)
+	}()
+
+	// 同步刷新ETA指标库的指标
+	{
+		// 获取指标详情
+		baseObj := new(models.BaseFromPurang)
+		var edbInfo *models.EdbInfo
+		edbInfo, err = models.GetEdbInfoByEdbCode(baseObj.GetSource(), indexCode)
+		if err != nil {
+			if !utils.IsErrNoRow(err) {
+				errMsgList = append(errMsgList, fmt.Sprint("刷新ETA指标异常,指标编码:", indexCode, err.Error()))
+				return
+			} else {
+				err = nil
+			}
+		}
+
+		// 已经加入到指标库的话,那么就去更新ETA指标库吧
+		if edbInfo != nil {
+			go logic.RefreshBaseEdbInfo(edbInfo, ``)
+		}
+	}
+	return
+} 

+ 2 - 0
utils/constants.go

@@ -125,6 +125,7 @@ const (
 	DATA_SOURCE_RESIDUAL_ANALYSIS                    = 99  // 残差分析
 	DATA_SOURCE_CLARKSONS                            = 101 // 克拉克森 -> 101
 	DATA_SOURCE_GPR_RISK                             = 102
+	DATA_SOURCE_PuRang                               = 104 // 普兰金融-> 104
 )
 
 // 指标来源的中文展示
@@ -219,6 +220,7 @@ const (
 	DATA_SOURCE_NAME_OILCHEM                              = `隆众资讯`      // 隆众资讯 -> 89
 	DATA_SOURCE_NAME_HISUGAR                              = `泛糖科技`      // 泛糖科技 -> 93
 	DATA_SOURCE_NAME_GPR_RISK                             = `GPR地缘风险指数` // GPR地缘风险指数 -> 102
+	DATA_SOURCE_NAME_PuRang                               = `普兰金融`      // 普兰金融 -> 104
 )
 
 // 基础数据初始化日期