Jelajahi Sumber

Merge branch 'feature/eta_1.7.1'

hsun 1 tahun lalu
induk
melakukan
d647f41ded
33 mengubah file dengan 4670 tambahan dan 3963 penghapusan
  1. 115 115
      controllers/data_manage/edb_info.go
  2. 1152 0
      controllers/data_manage/edb_info_calculate.go
  3. 27 0
      models/data_manage/edb_data_calculate_ljztbpj.go
  4. 160 0
      models/data_manage/edb_data_calculate_time_shift.go
  5. 34 0
      models/data_manage/edb_data_calculate_zjpj.go
  6. 390 8
      models/data_manage/edb_info.go
  7. 89 0
      models/data_manage/edb_info_calculate.go
  8. 157 0
      models/data_manage/edb_info_calculate_bp.go
  9. 144 0
      models/data_manage/edb_info_calculate_hbz.go
  10. 149 0
      models/data_manage/edb_info_calculate_hcz.go
  11. 387 0
      models/data_manage/edb_info_calculate_ljztbpj.go
  12. 210 0
      models/data_manage/edb_info_calculate_ljzzy.go
  13. 173 0
      models/data_manage/edb_info_calculate_nszydpjjs.go
  14. 256 0
      models/data_manage/edb_info_calculate_tcz.go
  15. 286 0
      models/data_manage/edb_info_calculate_zjpj.go
  16. 10 0
      models/data_manage/predict_edb_conf.go
  17. 4 18
      models/db.go
  18. 0 275
      models/report_chapter_type.go
  19. 0 58
      models/report_chapter_type_permission.go
  20. 0 302
      models/research_report.go
  21. 0 376
      models/system/sys_admin.go
  22. 0 226
      models/system/sys_role_admin.go
  23. 0 106
      models/system/sys_user.go
  24. 0 1417
      models/target.go
  25. 0 426
      models/user_view_history.go
  26. 0 444
      models/wechat_send_msg.go
  27. 72 0
      routers/commentsRouter.go
  28. 89 0
      services/data/base_edb_lib.go
  29. 0 114
      services/data/edb_data.go
  30. 685 0
      services/data/edb_info_calculate.go
  31. 14 0
      services/data/predict_edb_info.go
  32. 67 67
      services/data/predict_edb_info_rule.go
  33. 0 11
      services/wechat_send_msg.go

+ 115 - 115
controllers/data_manage/edb_info.go

@@ -2987,121 +2987,121 @@ func (this *EdbInfoController) EdbInfoReplaceCheck() {
 // @Param	request	body data_manage.EdbInfoReplaceReq true "type json string"
 // @Success 200 {object} data_manage.EdbInfoDataResp
 // @router /edb_info/replace [post]
-//func (this *ChartInfoController) EdbInfoReplace() {
-//	br := new(models.BaseResponse).Init()
-//	setNxKey := "EDB_INFO_REPLACE"
-//	deleteCache := true
-//
-//	defer func() {
-//		if deleteCache {
-//			utils.Rc.Delete(setNxKey)
-//		}
-//		this.Data["json"] = br
-//		this.ServeJSON()
-//	}()
-//
-//	sysUser := this.SysUser
-//	if sysUser == nil {
-//		br.Msg = "请登录"
-//		br.ErrMsg = "请登录,SysUser Is Empty"
-//		br.Ret = 408
-//		return
-//	}
-//
-//	if !utils.Rc.SetNX(setNxKey, 1, 30*time.Minute) {
-//		deleteCache = false
-//		br.Msg = "当前正在替换中,请耐心等待!"
-//		br.IsSendEmail = false
-//		return
-//	}
-//
-//	var req data_manage.EdbInfoReplaceReq
-//	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
-//	if err != nil {
-//		br.Msg = "参数解析异常!"
-//		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-//		return
-//	}
-//	if req.OldEdbInfoId <= 0 || req.NewEdbInfoId <= 0 {
-//		br.Msg = "参数错误!"
-//		br.ErrMsg = "参数错误,指标id为0"
-//		return
-//	}
-//
-//	oldEdbInfo, err := data_manage.GetEdbInfoById(req.OldEdbInfoId)
-//	if err != nil {
-//		br.Msg = "替换失败!"
-//		br.ErrMsg = "获取原指标失败,Err:" + err.Error()
-//		return
-//	}
-//
-//	newEdbInfo, err := data_manage.GetEdbInfoById(req.NewEdbInfoId)
-//	if err != nil {
-//		br.Msg = "替换失败!"
-//		br.ErrMsg = "获取替换目标指标失败,Err:" + err.Error()
-//		return
-//	}
-//
-//	//if oldEdbInfo.EdbType != 1 {
-//	//	br.Msg = "原指标为计算指标,不可替换!"
-//	//	br.ErrMsg = "原指标为计算指标,不可替换!"
-//	//	return
-//	//}
-//	//
-//	//if newEdbInfo.EdbType != 1 {
-//	//	br.Msg = "替换指标为计算指标,不可替换!"
-//	//	br.ErrMsg = "替换指标为计算指标,不可替换!"
-//	//	return
-//	//}
-//
-//	if oldEdbInfo.Frequency != newEdbInfo.Frequency {
-//		br.Msg = "原指标频度为:" + oldEdbInfo.Frequency + " 替换指标频度为:" + newEdbInfo.Frequency + ",频度不同,不可进行替换操作!"
-//		br.ErrMsg = "原指标频度为:" + oldEdbInfo.Frequency + " 替换指标频度为:" + newEdbInfo.Frequency + ",频度不同,不可进行替换操作!"
-//		return
-//	}
-//
-//	sysAdminId := sysUser.AdminId
-//	//replaceChartTotal, replaceCalculateTotal, err := data.EdbInfoReplace(oldEdbInfo, newEdbInfo, sysAdminId, sysUser.RealName)
-//	_, _, err = data_manage.EdbInfoReplaceV2(oldEdbInfo, newEdbInfo, sysAdminId, sysUser.RealName)
-//	//msgContent := ``
-//	isFail := false
-//	var errmsg string
-//	if err != nil {
-//		//msgContent = oldEdbInfo.EdbName + "指标替换" + newEdbInfo.EdbName + "指标,全部替换失败,涉及" + strconv.Itoa(replaceChartTotal) + "张图表,\n\n " + strconv.Itoa(replaceCalculateTotal) + "个计算指标"
-//		isFail = true
-//		errmsg = "replace err:" + err.Error()
-//	} else {
-//		//msgContent = oldEdbInfo.EdbName + "指标替换" + newEdbInfo.EdbName + "指标,全部替换成功,涉及" + strconv.Itoa(replaceChartTotal) + "张图表,\n\n" + strconv.Itoa(replaceCalculateTotal) + "个计算指标"
-//		isFail = false
-//	}
-//
-//	// 添加站内信息
-//	//{
-//	//	msgItem := new(company.CompanyApprovalMessage)
-//	//	msgItem.CreateUserId = sysAdminId
-//	//	msgItem.ReceiveUserId = sysAdminId
-//	//	msgItem.MessageStatus = 0
-//	//	msgItem.Remark = "指标替换"
-//	//	msgItem.OperationStatus = 1
-//	//	msgItem.Content = msgContent
-//	//	msgItem.CreateTime = time.Now()
-//	//	msgItem.ModifyTime = time.Now()
-//	//	msgItem.MessageType = 3 //1:申请消息,2:审批结果,3:文字消息
-//	//	msgItem.SourceType = 4  //消息来源
-//	//	err = company.AddCompanyApprovalMessage(msgItem)
-//	//}
-//
-//	if isFail {
-//		br.Msg = "替换失败"
-//		br.ErrMsg = "替换失败 err:" + errmsg
-//	} else {
-//		br.Msg = "替换成功"
-//		br.ErrMsg = "替换成功"
-//		br.Ret = 200
-//	}
-//	br.IsAddLog = true
-//	return
-//}
+func (this *ChartInfoController) EdbInfoReplace() {
+	br := new(models.BaseResponse).Init()
+	setNxKey := "EDB_INFO_REPLACE"
+	deleteCache := true
+
+	defer func() {
+		if deleteCache {
+			utils.Rc.Delete(setNxKey)
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	if !utils.Rc.SetNX(setNxKey, 1, 30*time.Minute) {
+		deleteCache = false
+		br.Msg = "当前正在替换中,请耐心等待!"
+		br.IsSendEmail = false
+		return
+	}
+
+	var req data_manage.EdbInfoReplaceReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.OldEdbInfoId <= 0 || req.NewEdbInfoId <= 0 {
+		br.Msg = "参数错误!"
+		br.ErrMsg = "参数错误,指标id为0"
+		return
+	}
+
+	oldEdbInfo, err := data_manage.GetEdbInfoById(req.OldEdbInfoId)
+	if err != nil {
+		br.Msg = "替换失败!"
+		br.ErrMsg = "获取原指标失败,Err:" + err.Error()
+		return
+	}
+
+	newEdbInfo, err := data_manage.GetEdbInfoById(req.NewEdbInfoId)
+	if err != nil {
+		br.Msg = "替换失败!"
+		br.ErrMsg = "获取替换目标指标失败,Err:" + err.Error()
+		return
+	}
+
+	//if oldEdbInfo.EdbType != 1 {
+	//	br.Msg = "原指标为计算指标,不可替换!"
+	//	br.ErrMsg = "原指标为计算指标,不可替换!"
+	//	return
+	//}
+	//
+	//if newEdbInfo.EdbType != 1 {
+	//	br.Msg = "替换指标为计算指标,不可替换!"
+	//	br.ErrMsg = "替换指标为计算指标,不可替换!"
+	//	return
+	//}
+
+	if oldEdbInfo.Frequency != newEdbInfo.Frequency {
+		br.Msg = "原指标频度为:" + oldEdbInfo.Frequency + " 替换指标频度为:" + newEdbInfo.Frequency + ",频度不同,不可进行替换操作!"
+		br.ErrMsg = "原指标频度为:" + oldEdbInfo.Frequency + " 替换指标频度为:" + newEdbInfo.Frequency + ",频度不同,不可进行替换操作!"
+		return
+	}
+
+	sysAdminId := sysUser.AdminId
+	//replaceChartTotal, replaceCalculateTotal, err := data.EdbInfoReplace(oldEdbInfo, newEdbInfo, sysAdminId, sysUser.RealName)
+	_, _, err = data_manage.EdbInfoReplaceV2(oldEdbInfo, newEdbInfo, sysAdminId, sysUser.RealName)
+	//msgContent := ``
+	isFail := false
+	var errmsg string
+	if err != nil {
+		//msgContent = oldEdbInfo.EdbName + "指标替换" + newEdbInfo.EdbName + "指标,全部替换失败,涉及" + strconv.Itoa(replaceChartTotal) + "张图表,\n\n " + strconv.Itoa(replaceCalculateTotal) + "个计算指标"
+		isFail = true
+		errmsg = "replace err:" + err.Error()
+	} else {
+		//msgContent = oldEdbInfo.EdbName + "指标替换" + newEdbInfo.EdbName + "指标,全部替换成功,涉及" + strconv.Itoa(replaceChartTotal) + "张图表,\n\n" + strconv.Itoa(replaceCalculateTotal) + "个计算指标"
+		isFail = false
+	}
+
+	// 添加站内信息
+	//{
+	//	msgItem := new(company.CompanyApprovalMessage)
+	//	msgItem.CreateUserId = sysAdminId
+	//	msgItem.ReceiveUserId = sysAdminId
+	//	msgItem.MessageStatus = 0
+	//	msgItem.Remark = "指标替换"
+	//	msgItem.OperationStatus = 1
+	//	msgItem.Content = msgContent
+	//	msgItem.CreateTime = time.Now()
+	//	msgItem.ModifyTime = time.Now()
+	//	msgItem.MessageType = 3 //1:申请消息,2:审批结果,3:文字消息
+	//	msgItem.SourceType = 4  //消息来源
+	//	err = company.AddCompanyApprovalMessage(msgItem)
+	//}
+
+	if isFail {
+		br.Msg = "替换失败"
+		br.ErrMsg = "替换失败 err:" + errmsg
+	} else {
+		br.Msg = "替换成功"
+		br.ErrMsg = "替换成功"
+		br.Ret = 200
+	}
+	br.IsAddLog = true
+	return
+}
 
 // RelationChartList
 // @Title 获取ETA指标关联的图表列表接口

+ 1152 - 0
controllers/data_manage/edb_info_calculate.go

@@ -8,9 +8,793 @@ import (
 	"eta/eta_mobile/utils"
 	"fmt"
 	"strconv"
+	"strings"
 	"time"
 )
 
+// @Title 生成计算指标
+// @Description 生成计算指标接口
+// @Param	request	body data_manage.EdbInfoCalculateSaveReq true "type json string"
+// @Success Ret=200 返回图表id
+// @router /edb_info/calculate/save [post]
+func (this *ChartInfoController) CalculateSave() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var req data_manage.EdbInfoCalculateSaveReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	req.EdbName = strings.Trim(req.EdbName, " ")
+	if req.EdbName == "" {
+		br.Msg = "指标名称不能为空"
+		return
+	}
+
+	if req.Frequency == "" {
+		br.Msg = "频率不能为空"
+		return
+	}
+
+	if req.Unit == "" {
+		br.Msg = "单位不能为空"
+		return
+	}
+
+	if req.ClassifyId <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+
+	if len(req.EdbInfoIdArr) <= 0 {
+		br.Msg = "请选择指标"
+		return
+	}
+
+	if req.CalculateFormula == "" {
+		br.Msg = "请填写指标"
+		return
+	}
+	calculateFormula := req.CalculateFormula
+	calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
+	calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
+	calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
+	calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
+	calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
+	req.CalculateFormula = calculateFormula
+
+	//判断是否重复指标
+	edbInfoMap := make(map[int]string)
+	//移除研究员选择指标中的未使用的指标
+	{
+		//转大写的计算公式
+		upperCalculateFormulaStr := strings.ToUpper(req.CalculateFormula)
+		//用到的指标
+		newEdbInfoIdArr := make([]data_manage.EdbInfoFromTag, 0)
+		for _, tmpEdbInfo := range req.EdbInfoIdArr {
+			_, ok := edbInfoMap[tmpEdbInfo.EdbInfoId]
+			if ok {
+				br.Msg = "选择指标失败,请勿选择重复指标!"
+				return
+			}
+			edbInfoMap[tmpEdbInfo.EdbInfoId] = tmpEdbInfo.FromTag
+
+			upperFromTag := strings.ToUpper(tmpEdbInfo.FromTag)
+			if strings.Contains(upperCalculateFormulaStr, upperFromTag) {
+				newEdbInfoIdArr = append(newEdbInfoIdArr, tmpEdbInfo)
+			}
+		}
+		req.EdbInfoIdArr = newEdbInfoIdArr
+	}
+
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_name=? "
+	pars = append(pars, req.EdbName)
+
+	count, err := data_manage.GetEdbInfoCountByCondition(condition, pars)
+	if err != nil {
+		br.Msg = "判断指标名称是否存在失败"
+		br.ErrMsg = "判断指标名称是否存在失败,Err:" + err.Error()
+		return
+	}
+
+	if count > 0 {
+		br.Msg = "指标名称已存在,请重新填写"
+		br.ErrMsg = "指标名称已存在,请重新填写"
+		br.IsSendEmail = false
+		return
+	}
+	//检验公式
+	var formulaStr string
+	var edbInfoIdBytes []string
+	for _, v := range req.EdbInfoIdArr {
+		formulaStr += v.FromTag + ","
+		edbInfoIdBytes = append(edbInfoIdBytes, v.FromTag)
+	}
+	formulaMap := data.CheckFormula(req.CalculateFormula)
+	for _, v := range formulaMap {
+		if !strings.Contains(formulaStr, v) {
+			br.Msg = "公式错误,请重新填写"
+			return
+		}
+	}
+
+	// 调用指标库去新增
+	req2 := &data_manage.EdbInfoCalculateBatchSaveReqByEdbLib{
+		AdminId:   sysUser.AdminId,
+		AdminName: sysUser.RealName,
+		//EdbInfoId:        req.EdbInfoId,
+		EdbName:          req.EdbName,
+		Frequency:        req.Frequency,
+		Unit:             req.Unit,
+		ClassifyId:       req.ClassifyId,
+		CalculateFormula: req.CalculateFormula,
+		EdbInfoIdArr:     req.EdbInfoIdArr,
+	}
+	reqJson, err := json.Marshal(req2)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	respItem, err := data.AddEdbCalculateData(string(reqJson))
+	if err != nil {
+		br.Msg = "新增失败"
+		br.ErrMsg = "新增失败,Err:" + err.Error()
+		return
+	}
+	if respItem.Ret != 200 {
+		br.Msg = respItem.Msg
+		br.ErrMsg = respItem.ErrMsg
+		return
+	}
+
+	resp := respItem.Data
+
+	//添加es
+	data.AddOrEditEdbInfoToEs(resp.EdbInfoId)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.Data = resp
+	br.IsAddLog = true
+}
+
+// @Title 获取计算指标详情
+// @Description 获取计算指标详情接口
+// @Param   EdbInfoId   query   int  true       "指标id"
+// @Success 200 {object} data_manage.CalculateDetailResp
+// @router /edb_info/calculate/detail [get]
+func (this *ChartInfoController) CalculateDetail() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	edbInfoId, _ := this.GetInt("EdbInfoId")
+	edbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+
+	calculateList, err := data_manage.GetEdbInfoCalculateDetail(edbInfoId, edbInfo.Source)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	resp := new(data_manage.CalculateDetailResp)
+	resp.EdbInfoDetail = edbInfo
+	resp.CalculateList = calculateList
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.Data = resp
+}
+
+// @Title 修改计算指标
+// @Description 修改计算指标接口
+// @Param	request	body data_manage.EdbInfoCalculateEditReq true "type json string"
+// @Success Ret=200 返回图表id
+// @router /edb_info/calculate/edit [post]
+func (this *ChartInfoController) CalculateEdit() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var req data_manage.EdbInfoCalculateEditReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	if req.EdbInfoId <= 0 {
+		br.Msg = "参数错误"
+		br.ErrMsg = "指标ID:" + strconv.Itoa(req.EdbInfoId)
+		return
+	}
+
+	req.EdbName = strings.Trim(req.EdbName, " ")
+	if req.EdbName == "" {
+		br.Msg = "指标名称不能为空"
+		return
+	}
+
+	if req.Frequency == "" {
+		br.Msg = "频率不能为空"
+		return
+	}
+
+	if req.Unit == "" {
+		br.Msg = "单位不能为空"
+		return
+	}
+
+	if req.ClassifyId <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+
+	if len(req.EdbInfoIdArr) <= 0 {
+		br.Msg = "请选择指标"
+		return
+	}
+
+	if req.CalculateFormula == "" {
+		br.Msg = "请填写指标"
+		return
+	}
+
+	calculateFormula := req.CalculateFormula
+	calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
+	calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
+	calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
+	calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
+	calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
+	req.CalculateFormula = calculateFormula
+	fmt.Println("calculateFormula:" + calculateFormula)
+
+	//判断是否重复指标
+	edbInfoMap := make(map[int]string)
+	//移除研究员选择指标中的未使用的指标
+	{
+		//转大写的计算公式
+		upperCalculateFormulaStr := strings.ToUpper(req.CalculateFormula)
+		//用到的指标
+		newEdbInfoIdArr := make([]data_manage.EdbInfoFromTag, 0)
+		for _, tmpEdbInfo := range req.EdbInfoIdArr {
+			_, ok := edbInfoMap[tmpEdbInfo.EdbInfoId]
+			if ok {
+				br.Msg = "选择指标失败,请勿选择重复指标!"
+				return
+			}
+			edbInfoMap[tmpEdbInfo.EdbInfoId] = tmpEdbInfo.FromTag
+
+			upperFromTag := strings.ToUpper(tmpEdbInfo.FromTag)
+			if strings.Contains(upperCalculateFormulaStr, upperFromTag) {
+				newEdbInfoIdArr = append(newEdbInfoIdArr, tmpEdbInfo)
+			}
+		}
+		req.EdbInfoIdArr = newEdbInfoIdArr
+	}
+
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_name=? "
+	pars = append(pars, req.EdbName)
+
+	condition += " AND edb_info_id<>? "
+	pars = append(pars, req.EdbInfoId)
+
+	count, err := data_manage.GetEdbInfoCountByCondition(condition, pars)
+	if err != nil {
+		br.Msg = "判断指标名称是否存在失败"
+		br.ErrMsg = "判断指标名称是否存在失败,Err:" + err.Error()
+		return
+	}
+
+	if count > 0 {
+		br.Msg = "指标名称已存在,请重新填写"
+		br.ErrMsg = "指标名称已存在,请重新填写"
+		br.IsSendEmail = false
+		return
+	}
+
+	//判断公式,指标是否有改动
+	edbInfoDetail, err := data_manage.GetEdbInfoById(req.EdbInfoId)
+	if err != nil {
+		br.Msg = "修改失败"
+		br.Msg = "获取指标信息失败,GetEdbInfoById Err:" + err.Error()
+		return
+	}
+	if edbInfoDetail == nil {
+		br.Msg = "修改失败"
+		br.Msg = "指标信息不存在,EdbInfoId:" + strconv.Itoa(req.EdbInfoId)
+		return
+	}
+
+	// 调用指标库去更新
+	req2 := &data_manage.EdbInfoCalculateBatchSaveReqByEdbLib{
+		AdminId:          sysUser.AdminId,
+		AdminName:        sysUser.RealName,
+		EdbInfoId:        req.EdbInfoId,
+		EdbName:          req.EdbName,
+		Frequency:        req.Frequency,
+		Unit:             req.Unit,
+		ClassifyId:       req.ClassifyId,
+		CalculateFormula: req.CalculateFormula,
+		EdbInfoIdArr:     req.EdbInfoIdArr,
+	}
+	reqJson, err := json.Marshal(req2)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	respItem, err := data.EditEdbCalculateData(string(reqJson))
+	if err != nil {
+		br.Msg = "编辑失败"
+		br.ErrMsg = "编辑失败,Err:" + err.Error()
+		return
+	}
+	if respItem.Ret != 200 {
+		br.Msg = respItem.Msg
+		br.ErrMsg = respItem.ErrMsg
+		return
+	}
+
+	resp := respItem.Data
+
+	//添加es
+	data.AddOrEditEdbInfoToEs(req.EdbInfoId)
+
+	// 修改关联的预测指标基础信息
+	go data.ModifyPredictEdbBaseInfoBySourceEdb(edbInfoDetail)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.IsAddLog = true
+	br.Data = resp
+}
+
+// @Title 累计值转月-同比值-同差等计算新增
+// @Description 累计值转月-同比值-同差等计算新增接口
+// @Param	request	body data_manage.EdbInfoCalculateBatchSaveReq true "type json string"
+// @Success Ret=200 返回指标id
+// @router /edb_info/calculate/batch/save [post]
+func (this *ChartInfoController) CalculateBatchSave() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var req data_manage.EdbInfoCalculateBatchSaveReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	req.EdbName = strings.Trim(req.EdbName, " ")
+	if req.EdbName == "" {
+		br.Msg = "指标名称不能为空"
+		return
+	}
+
+	if req.Frequency == "" {
+		br.Msg = "频率不能为空"
+		return
+	}
+
+	if req.Unit == "" {
+		br.Msg = "单位不能为空"
+		return
+	}
+
+	if req.ClassifyId <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+
+	fromEdbInfoId := req.FromEdbInfoId
+
+	var formulaInt int
+	switch req.Source {
+	case utils.DATA_SOURCE_CALCULATE_NSZYDPJJS, utils.DATA_SOURCE_CALCULATE_HBZ, utils.DATA_SOURCE_CALCULATE_HCZ, utils.DATA_SOURCE_CALCULATE_TIME_SHIFT, utils.DATA_SOURCE_CALCULATE_CJJX:
+		if req.Formula == "" {
+			br.Msg = "请填写N值"
+			return
+		}
+		formulaInt, _ = strconv.Atoi(req.Formula)
+		if formulaInt <= 0 {
+			br.Msg = "N值输入错误,请重新输入"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_ZJPJ:
+		//直接拼接指标
+		//校验时间格式
+		_, err = time.ParseInLocation(utils.FormatDate, req.Formula, time.Local)
+		if err != nil {
+			br.Msg = "拼接日期有误,请重新输入"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_NHCC: //拟合残差指标
+		//指标校验
+		if len(req.EdbInfoIdArr) != 2 {
+			br.Msg = "选择的指标异常,请重新选择"
+			return
+		}
+		fromEdbInfoId = req.EdbInfoIdArr[0].EdbInfoId
+
+		//校验时间格式
+		//数据格式:2022-11-01,2022-11-10
+		timeList := strings.Split(req.Formula, ",")
+		if len(timeList) != 2 {
+			br.Msg = "选择时间有误,请重新输入"
+			return
+		}
+		startDate, err := time.ParseInLocation(utils.FormatDate, timeList[0], time.Local)
+		if err != nil {
+			br.Msg = "开始日期有误,请重新输入"
+			return
+		}
+		endDate, err := time.ParseInLocation(utils.FormatDate, timeList[1], time.Local)
+		if err != nil {
+			br.Msg = "结束日期有误,请重新输入"
+			return
+		}
+		if utils.GetTimeSubDay(startDate, endDate) < 2 {
+			br.Msg = "日期间隔不得少于两天"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_ZSXY: // 指数修匀
+		if req.Formula == "" {
+			br.Msg = "请填写alpha值"
+			return
+		}
+		alpha, e := strconv.ParseFloat(req.Formula, 64)
+		if e != nil {
+			br.Msg = "alpha值输入错误, 请重新输入"
+			return
+		}
+		if alpha <= 0 || alpha >= 1 {
+			br.Msg = "alpha值输入错误, 请重新输入"
+			return
+		}
+	}
+
+	notNeedFromEdbSourceList := []int{utils.DATA_SOURCE_CALCULATE_KSZS} // 不需要传入来源指标id的 指标类型
+	if fromEdbInfoId <= 0 && !utils.InArrayByInt(notNeedFromEdbSourceList, req.Source) {
+		br.Msg = "请选择指标"
+		return
+	}
+
+	//加入缓存机制,避免创建同一个名称的指标 start
+	redisKey := fmt.Sprint("edb_info:calculate:batch:save:", req.Source, ":", req.EdbName)
+	isExist := utils.Rc.IsExist(redisKey)
+	if isExist {
+		br.Msg = "指标正在处理,请勿重复提交"
+		return
+	} else {
+		//设置3分钟缓存
+		utils.Rc.SetNX(redisKey, 1, time.Second*300)
+		defer func() {
+			utils.Rc.Delete(redisKey)
+		}()
+	}
+	//加入缓存机制,避免创建同一个名称的指标 end
+
+	req2 := &data_manage.EdbInfoCalculateBatchSaveReqByEdbLib{
+		AdminId:          sysUser.AdminId,
+		AdminName:        sysUser.RealName,
+		EdbInfoId:        req.EdbInfoId,
+		EdbName:          req.EdbName,
+		Frequency:        req.Frequency,
+		Unit:             req.Unit,
+		ClassifyId:       req.ClassifyId,
+		Formula:          req.Formula, //N数值移动平均计算、环比值、环差值
+		FromEdbInfoId:    req.FromEdbInfoId,
+		CalculateFormula: req.CalculateFormula,
+		Source:           req.Source,
+		MoveType:         req.MoveType,
+		MoveFrequency:    req.MoveFrequency,
+
+		//CalculateFormula: edbInfo.CalculateFormula,
+		EdbInfoIdArr: req.EdbInfoIdArr,
+		Calendar:     req.Calendar,
+	}
+
+	// 调用指标库去更新
+	reqJson, err := json.Marshal(req2)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	respItem, err := data.BatchSaveEdbCalculateData(string(reqJson))
+	if err != nil {
+		br.Msg = "新增失败"
+		br.ErrMsg = "新增失败,Err:" + err.Error()
+		return
+	}
+	if respItem.Ret != 200 {
+		br.Msg = respItem.Msg
+		br.ErrMsg = respItem.ErrMsg
+		return
+	}
+
+	resp := respItem.Data
+
+	//添加es
+	data.AddOrEditEdbInfoToEs(resp.EdbInfoId)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.Data = resp
+	br.IsAddLog = true
+}
+
+// @Title 累计值转月-同比值-同差等计算编辑
+// @Description 累计值转月-同比值-同差等计算编辑接口
+// @Param	request	body data_manage.EdbInfoCalculateBatchEditReq true "type json string"
+// @Success Ret=200 返回指标id
+// @router /edb_info/calculate/batch/edit [post]
+func (this *ChartInfoController) CalculateBatchEdit() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var req data_manage.EdbInfoCalculateBatchEditReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	if req.EdbName == "" {
+		br.Msg = "指标名称不能为空"
+		return
+	}
+
+	if req.Frequency == "" {
+		br.Msg = "频率不能为空"
+		return
+	}
+
+	if req.Unit == "" {
+		br.Msg = "单位不能为空"
+		return
+	}
+
+	if req.ClassifyId <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+
+	if req.EdbInfoId <= 0 {
+		br.Msg = "请选择指标"
+		return
+	}
+
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_name=? "
+	pars = append(pars, req.EdbName)
+
+	condition += " AND edb_info_id<>? "
+	pars = append(pars, req.EdbInfoId)
+
+	count, err := data_manage.GetEdbInfoCountByCondition(condition, pars)
+	if err != nil {
+		br.Msg = "判断指标名称是否存在失败"
+		br.ErrMsg = "判断指标名称是否存在失败,Err:" + err.Error()
+		return
+	}
+
+	if count > 0 {
+		br.Msg = "指标名称已存在,请重新填写"
+		br.ErrMsg = "指标名称已存在,请重新填写"
+		br.IsSendEmail = false
+		return
+	}
+
+	edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
+	if err != nil {
+		if err.Error() == utils.ErrNoRow() {
+			br.Msg = "指标已被删除,请刷新页面"
+			br.ErrMsg = "指标已被删除,请刷新页面:Err:" + err.Error()
+			return
+		}
+		br.Msg = "获取指标信息失败"
+		br.ErrMsg = "获取指标信息失败:Err:" + err.Error()
+		return
+	}
+
+	if req.Source <= 0 {
+		req.Source = edbInfo.Source
+	}
+
+	var formulaInt int
+	switch req.Source {
+	case utils.DATA_SOURCE_CALCULATE_NSZYDPJJS, utils.DATA_SOURCE_CALCULATE_HBZ, utils.DATA_SOURCE_CALCULATE_HCZ, utils.DATA_SOURCE_CALCULATE_TIME_SHIFT, utils.DATA_SOURCE_CALCULATE_CJJX:
+		if req.Formula == "" {
+			br.Msg = "请填写N值"
+			return
+		}
+		formulaInt, _ = strconv.Atoi(req.Formula)
+		if formulaInt <= 0 {
+			br.Msg = "N值输入错误,请重新输入"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_ZJPJ:
+		//直接拼接指标
+
+		//校验时间格式
+		_, err = time.ParseInLocation(utils.FormatDate, req.Formula, time.Local)
+		if err != nil {
+			br.Msg = "拼接日期有误,请重新输入"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_NHCC: //拟合残差指标
+		//指标校验
+		if len(req.EdbInfoIdArr) != 2 {
+			br.Msg = "选择的指标异常,请重新选择"
+			return
+		}
+
+		//校验时间格式
+		//数据格式:2022-11-01,2022-11-10
+		timeList := strings.Split(req.Formula, ",")
+		if len(timeList) != 2 {
+			br.Msg = "选择时间有误,请重新输入"
+			return
+		}
+		startDate, err := time.ParseInLocation(utils.FormatDate, timeList[0], time.Local)
+		if err != nil {
+			br.Msg = "开始日期有误,请重新输入"
+			return
+		}
+		endDate, err := time.ParseInLocation(utils.FormatDate, timeList[1], time.Local)
+		if err != nil {
+			br.Msg = "结束日期有误,请重新输入"
+			return
+		}
+		if utils.GetTimeSubDay(startDate, endDate) < 2 {
+			br.Msg = "日期间隔不得少于两天"
+			return
+		}
+	case utils.DATA_SOURCE_CALCULATE_ZSXY: // 指数修匀
+		if req.Formula == "" {
+			br.Msg = "请填写alpha值"
+			return
+		}
+		alpha, e := strconv.ParseFloat(req.Formula, 64)
+		if e != nil {
+			br.Msg = "alpha值输入错误, 请重新输入"
+			return
+		}
+		if alpha <= 0 || alpha >= 1 {
+			br.Msg = "alpha值输入错误, 请重新输入"
+			return
+		}
+	}
+
+	// 构造请求
+	req2 := &data_manage.EdbInfoCalculateBatchEditReqByEdbLib{
+		EdbInfoId:     req.EdbInfoId,
+		EdbName:       req.EdbName,
+		Frequency:     req.Frequency,
+		Unit:          req.Unit,
+		ClassifyId:    req.ClassifyId,
+		Formula:       req.Formula, //N数值移动平均计算、环比值、环差值
+		FromEdbInfoId: req.FromEdbInfoId,
+		Source:        req.Source,
+		MoveType:      req.MoveType,
+		MoveFrequency: req.MoveFrequency,
+		EdbInfoIdArr:  req.EdbInfoIdArr,
+		Calendar:      req.Calendar,
+	}
+
+	// 调用指标库去更新
+	reqJson, err := json.Marshal(req2)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	respItem, err := data.BatchEditEdbCalculateData(string(reqJson))
+	if err != nil {
+		br.Msg = "编辑失败"
+		br.ErrMsg = "编辑失败,Err:" + err.Error()
+		return
+	}
+	if respItem.Ret != 200 {
+		br.Msg = respItem.Msg
+		br.ErrMsg = respItem.ErrMsg
+		return
+	}
+
+	resp := respItem.Data
+
+	//添加es
+	data.AddOrEditEdbInfoToEs(resp.EdbInfoId)
+
+	// 修改关联的预测指标基础信息
+	go data.ModifyPredictEdbBaseInfoBySourceEdb(edbInfo)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.Data = resp
+	br.IsAddLog = true
+}
+
 // @Title 累计值转月-同比值-同差等重新计算
 // @Description 累计值转月-同比值-同差等重新计算接口
 // @Param	request	body data_manage.EdbInfoCalculateBatchSaveReq true "type json string"
@@ -171,3 +955,371 @@ func (this *ChartInfoController) CalculateBatchReset() {
 	br.Data = resp
 	br.IsAddLog = true
 }
+
+// BatchCalculateBatchSave
+// @Title 批量添加 累计值转月-同比值-同差等计算新增
+// @Description 批量添加 累计值转月-同比值-同差等计算新增接口
+// @Param	request	body data_manage.EdbInfoCalculateBatchSaveReq true "type json string"
+// @Success Ret=200 返回指标id
+// @router /edb_info/calculate/batch/save/batch [post]
+func (this *ChartInfoController) BatchCalculateBatchSave() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var reqList []data_manage.BatchEdbInfoCalculateBatchSaveReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &reqList)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	resp := data_manage.BatchEdbInfoCalculateBatchSaveResp{
+		Fail:    make([]data_manage.BatchEdbInfoCalculateBatchSaveFailResp, 0),
+		Success: make([]data_manage.BatchEdbInfoCalculateBatchSaveSuccessResp, 0),
+	}
+	redisKeyList := make([]string, 0) //需要清理的缓存key列表
+	defer func() {
+		for _, redisKey := range redisKeyList {
+			utils.Rc.Delete(redisKey)
+		}
+	}()
+
+	for _, v := range reqList {
+		req := v.CalculateInfo
+		req.EdbName = strings.Trim(req.EdbName, " ")
+		if req.EdbName == "" {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "指标名称不能为空",
+			})
+			continue
+		}
+
+		if req.Frequency == "" {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "频率不能为空",
+			})
+			continue
+		}
+
+		if req.Unit == "" {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "单位不能为空",
+			})
+			continue
+		}
+
+		if req.ClassifyId <= 0 {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "请选择分类",
+			})
+			continue
+		}
+
+		fromEdbInfoId := req.FromEdbInfoId
+
+		var formulaInt int
+		switch req.Source {
+		case utils.DATA_SOURCE_CALCULATE_NSZYDPJJS, utils.DATA_SOURCE_CALCULATE_HBZ, utils.DATA_SOURCE_CALCULATE_HCZ, utils.DATA_SOURCE_CALCULATE_TIME_SHIFT, utils.DATA_SOURCE_CALCULATE_CJJX:
+			if req.Formula == "" {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "请选择分类",
+				})
+				continue
+			}
+			formulaInt, _ = strconv.Atoi(req.Formula)
+			if formulaInt <= 0 {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "N值输入错误,请重新输入",
+				})
+				continue
+			}
+		case utils.DATA_SOURCE_CALCULATE_ZJPJ:
+			//直接拼接指标
+			//校验时间格式
+			_, err = time.ParseInLocation(utils.FormatDate, req.Formula, time.Local)
+			if err != nil {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "拼接日期有误,请重新输入",
+				})
+				continue
+			}
+		case utils.DATA_SOURCE_CALCULATE_NHCC: //拟合残差指标
+			//指标校验
+			if len(req.EdbInfoIdArr) != 2 {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "选择的指标异常,请重新选择",
+				})
+				continue
+			}
+			fromEdbInfoId = req.EdbInfoIdArr[0].EdbInfoId
+
+			//校验时间格式
+			//数据格式:2022-11-01,2022-11-10
+			timeList := strings.Split(req.Formula, ",")
+			if len(timeList) != 2 {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "选择时间有误,请重新输入",
+				})
+				continue
+			}
+			startDate, err := time.ParseInLocation(utils.FormatDate, timeList[0], time.Local)
+			if err != nil {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "开始日期有误,请重新输入",
+				})
+				continue
+			}
+			endDate, err := time.ParseInLocation(utils.FormatDate, timeList[1], time.Local)
+			if err != nil {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "结束日期有误,请重新输入",
+				})
+				continue
+			}
+			if utils.GetTimeSubDay(startDate, endDate) < 2 {
+				resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+					CalculateId: v.CalculateId,
+					Msg:         "日期间隔不得少于两天",
+				})
+				continue
+			}
+		case utils.DATA_SOURCE_CALCULATE_ZSXY: // 指数修匀
+			if req.Formula == "" {
+				br.Msg = "请填写alpha值"
+				return
+			}
+			alpha, e := strconv.ParseFloat(req.Formula, 64)
+			if e != nil {
+				br.Msg = "alpha值输入错误, 请重新输入"
+				return
+			}
+			if alpha <= 0 || alpha >= 1 {
+				br.Msg = "alpha值输入错误, 请重新输入"
+				return
+			}
+		}
+
+		if fromEdbInfoId <= 0 {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "请选择指标",
+			})
+			continue
+		}
+
+		//加入缓存机制,避免创建同一个名称的指标 start
+		redisKey := fmt.Sprint("edb_info:calculate:batch:save:", sysUser.AdminId, ":", req.Source, ":", v.CalculateId)
+		isExist := utils.Rc.IsExist(redisKey)
+		if isExist {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "指标正在处理,请勿重复提交",
+			})
+			continue
+		} else {
+			//设置3分钟缓存
+			utils.Rc.SetNX(redisKey, 1, time.Second*300)
+			redisKeyList = append(redisKeyList, redisKey)
+		}
+		//加入缓存机制,避免创建同一个名称的指标 end
+
+		req2 := &data_manage.EdbInfoCalculateBatchSaveReqByEdbLib{
+			AdminId:          sysUser.AdminId,
+			AdminName:        sysUser.RealName,
+			EdbInfoId:        req.EdbInfoId,
+			EdbName:          req.EdbName,
+			Frequency:        req.Frequency,
+			Unit:             req.Unit,
+			ClassifyId:       req.ClassifyId,
+			Formula:          req.Formula, //N数值移动平均计算、环比值、环差值
+			FromEdbInfoId:    req.FromEdbInfoId,
+			CalculateFormula: req.CalculateFormula,
+			Source:           req.Source,
+			MoveType:         req.MoveType,
+			MoveFrequency:    req.MoveFrequency,
+
+			//CalculateFormula: edbInfo.CalculateFormula,
+			EdbInfoIdArr: req.EdbInfoIdArr,
+			Calendar:     req.Calendar,
+		}
+
+		// 调用指标库去更新
+		reqJson, err := json.Marshal(req2)
+		if err != nil {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "参数解析异常!",
+				ErrMsg:      "参数解析失败,Err:" + err.Error(),
+			})
+			continue
+		}
+		respItem, err := data.BatchSaveEdbCalculateData(string(reqJson))
+		if err != nil {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         "新增失败!",
+				ErrMsg:      "新增失败,Err:" + err.Error(),
+			})
+			continue
+		}
+		if respItem.Ret != 200 {
+			resp.Fail = append(resp.Fail, data_manage.BatchEdbInfoCalculateBatchSaveFailResp{
+				CalculateId: v.CalculateId,
+				Msg:         respItem.Msg,
+				ErrMsg:      respItem.ErrMsg,
+			})
+			continue
+		}
+
+		result := respItem.Data
+
+		//添加es
+		data.AddOrEditEdbInfoToEs(result.EdbInfoId)
+		resp.Success = append(resp.Success, data_manage.BatchEdbInfoCalculateBatchSaveSuccessResp{
+			ClassifyId:  req.ClassifyId,
+			CalculateId: v.CalculateId,
+			EdbInfoId:   result.EdbInfoId,
+			UniqueCode:  result.UniqueCode,
+		})
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "批量保存成功"
+	br.Data = resp
+	br.IsAddLog = true
+}
+
+// CalculateComputeCorrelation
+// @Title 拟合残差计算相关性
+// @Description 拟合残差计算相关性接口
+// @Param	request	body data_manage.EdbInfoCalculateBatchSaveReq true "type json string"
+// @Success Ret=200 返回指标id
+// @router /edb_info/calculate/compute_correlation [post]
+func (this *ChartInfoController) CalculateComputeCorrelation() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	var req data_manage.EdbInfoCalculateBatchSaveReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+
+	if len(req.EdbInfoIdArr) != 2 {
+		br.Msg = "选择的指标异常,请重新选择"
+		return
+	}
+	fromEdbInfoId := req.EdbInfoIdArr[0].EdbInfoId
+
+	//校验时间格式
+	//数据格式:2022-11-01,2022-11-10
+	timeList := strings.Split(req.Formula, ",")
+	if len(timeList) != 2 {
+		br.Msg = "选择时间有误,请重新输入"
+		return
+	}
+	startDate, err := time.ParseInLocation(utils.FormatDate, timeList[0], time.Local)
+	if err != nil {
+		br.Msg = "开始日期有误,请重新输入"
+		return
+	}
+	endDate, err := time.ParseInLocation(utils.FormatDate, timeList[1], time.Local)
+	if err != nil {
+		br.Msg = "结束日期有误,请重新输入"
+		return
+	}
+	if utils.GetTimeSubDay(startDate, endDate) < 2 {
+		br.Msg = "日期间隔不得少于两天"
+		return
+	}
+
+	if fromEdbInfoId <= 0 {
+		br.Msg = "请选择指标"
+		return
+	}
+
+	req2 := &data_manage.EdbInfoCalculateBatchSaveReqByEdbLib{
+		AdminId:          sysUser.AdminId,
+		AdminName:        sysUser.RealName,
+		EdbInfoId:        req.EdbInfoId,
+		EdbName:          req.EdbName,
+		Frequency:        req.Frequency,
+		Unit:             req.Unit,
+		ClassifyId:       req.ClassifyId,
+		Formula:          req.Formula, //N数值移动平均计算、环比值、环差值
+		FromEdbInfoId:    req.FromEdbInfoId,
+		CalculateFormula: req.CalculateFormula,
+		Source:           req.Source,
+		MoveType:         req.MoveType,
+		MoveFrequency:    req.MoveFrequency,
+
+		//CalculateFormula: edbInfo.CalculateFormula,
+		EdbInfoIdArr: req.EdbInfoIdArr,
+		Calendar:     req.Calendar,
+	}
+
+	// 调用指标库去更新
+	reqJson, err := json.Marshal(req2)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	respItem, err := data.CalculateComputeCorrelation(string(reqJson))
+	if err != nil {
+		br.Msg = "新增失败"
+		br.ErrMsg = "新增失败,Err:" + err.Error()
+		return
+	}
+
+	if respItem.Ret == 200 {
+		br.Data = respItem.Data
+	} else {
+		br.Data = ``
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "计算成功"
+	br.IsAddLog = true
+}

+ 27 - 0
models/data_manage/edb_data_calculate_ljztbpj.go

@@ -0,0 +1,27 @@
+package data_manage
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// EdbDataCalculateLjztbpj 累计值同比拼接数据结构体
+type EdbDataCalculateLjztbpj struct {
+	EdbDataId     int `orm:"column(edb_data_id);pk"`
+	EdbInfoId     int
+	EdbCode       string
+	DataTime      string
+	Value         float64
+	Status        int
+	CreateTime    time.Time
+	ModifyTime    time.Time
+	DataTimestamp int64
+}
+
+// GetAllEdbDataCalculateLjztbpjByEdbInfoId 根据指标id获取全部的数据
+func GetAllEdbDataCalculateLjztbpjByEdbInfoId(edbInfoId int) (items []*EdbDataCalculateLjztbpj, err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` SELECT * FROM edb_data_calculate_ljztbpj WHERE edb_info_id=? ORDER BY data_time DESC `
+	_, err = o.Raw(sql, edbInfoId).QueryRows(&items)
+	return
+}

+ 160 - 0
models/data_manage/edb_data_calculate_time_shift.go

@@ -0,0 +1,160 @@
+package data_manage
+
+import (
+	"errors"
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// 时间移位
+func EditCalculateTimeShift(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, oldEdbInfo *EdbInfo) (edbInfoId int, err error) {
+	edbInfoId = req.EdbInfoId
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	//修改指标信息
+	sql := ` UPDATE  edb_info
+			SET
+			  edb_name =?,
+			  edb_name_source=?,
+			  frequency = ?,
+			  unit = ?,
+			  classify_id = ?,
+			  move_type=?,
+			  move_frequency=?,
+			  calculate_formula=?,
+			  modify_time = NOW()
+			WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.MoveType, req.MoveFrequency, req.Formula, edbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	var existCondition string
+	var existPars []interface{}
+	existCondition += " AND edb_info_id=? "
+	existPars = append(existPars, edbInfoId)
+
+	existCondition += " AND from_edb_info_id=? "
+	existPars = append(existPars, req.FromEdbInfoId)
+
+	//判断计算指标是否被更换
+	count, err := GetEdbInfoCalculateCountByCondition(req.Source, existCondition, existPars)
+	if err != nil {
+		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
+		return
+	}
+	if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
+		if count <= 0 {
+			//删除,计算指标关联的,基础指标的关联关系
+			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+			_, err = to.Raw(sql, edbInfoId).Exec()
+			if err != nil {
+				err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
+				return
+			}
+			//关联关系
+			{
+				calculateMappingItem := new(EdbInfoCalculateMapping)
+				calculateMappingItem.CreateTime = time.Now()
+				calculateMappingItem.ModifyTime = time.Now()
+				calculateMappingItem.Sort = 1
+				calculateMappingItem.EdbCode = edbCode
+				calculateMappingItem.EdbInfoId = edbInfoId
+				calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+				calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+				calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+				calculateMappingItem.FromSource = fromEdbInfo.Source
+				calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+				calculateMappingItem.FromTag = ""
+				calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
+				calculateMappingItem.SourceName = "时间移位"
+				_, err = to.Insert(calculateMappingItem)
+				if err != nil {
+					return
+				}
+			}
+		}
+		//清空原有数据
+		sql = ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
+		_, err = to.Raw(sql, edbInfoId).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+
+		edbInfoIdStr := strconv.Itoa(edbInfoId)
+
+		var shiftDay int
+		formulaInt, _ := strconv.Atoi(req.Formula)
+		switch req.MoveFrequency {
+		case "天":
+			shiftDay = formulaInt
+		case "周":
+			shiftDay = formulaInt * 7
+		case "月":
+			shiftDay = formulaInt * 30
+		case "季":
+			shiftDay = formulaInt * 90
+		case "年":
+			shiftDay = formulaInt * 365
+		default:
+			shiftDay = formulaInt
+		}
+
+		//计算数据
+		var condition string
+		var pars []interface{}
+		condition += " AND edb_info_id=? "
+		pars = append(pars, req.FromEdbInfoId)
+		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
+		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+		if err != nil {
+			return edbInfoId, err
+		}
+		addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+		var isAdd bool
+		existMap := make(map[string]string)
+		dataLen := len(dataList)
+		if req.MoveType == 2 {
+			shiftDay = -shiftDay
+		}
+		for i := 0; i < dataLen; i++ {
+			//当期
+			currentItem := dataList[i]
+			currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
+			newDate := currentDate.AddDate(0, 0, shiftDay)
+			existKey := edbCode + newDate.Format(utils.FormatDate)
+			if _, ok := existMap[existKey]; !ok {
+				timestamp := newDate.UnixNano() / 1e6
+				timestampStr := fmt.Sprintf("%d", timestamp)
+				valStr := decimal.NewFromFloat(currentItem.Value).String()
+				addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
+				isAdd = true
+			}
+			existMap[existKey] = currentItem.DataTime
+		}
+		if isAdd {
+			addSql = strings.TrimRight(addSql, ",")
+			_, err = to.Raw(addSql).Exec()
+			if err != nil {
+				return edbInfoId, err
+			}
+		}
+	}
+	return
+}

+ 34 - 0
models/data_manage/edb_data_calculate_zjpj.go

@@ -0,0 +1,34 @@
+package data_manage
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// EdbDataCalculateZjpj 直接拼接数据结构体
+type EdbDataCalculateZjpj struct {
+	EdbDataId     int `orm:"column(edb_data_id);pk"`
+	EdbInfoId     int
+	EdbCode       string
+	DataTime      string
+	Value         float64
+	Status        int
+	CreateTime    time.Time
+	ModifyTime    time.Time
+	DataTimestamp int64
+}
+
+// GetAllEdbDataCalculateZjpjByEdbInfoId 根据指标id获取全部的数据
+func GetAllEdbDataCalculateZjpjByEdbInfoId(edbInfoId int) (items []*EdbDataCalculateZjpj, err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` SELECT * FROM edb_data_calculate_zjpj WHERE edb_info_id=? ORDER BY data_time DESC `
+	_, err = o.Raw(sql, edbInfoId).QueryRows(&items)
+	return
+}
+
+type EdbDataFromZjpj struct {
+	Date   map[string]int64   `json:"date"`
+	Ticker map[string]string  `json:"ticker"`
+	Field  map[string]string  `json:"field"`
+	Value  map[string]float64 `json:"value"`
+}

+ 390 - 8
models/data_manage/edb_info.go

@@ -6,6 +6,8 @@ import (
 	"fmt"
 	"github.com/beego/beego/v2/client/orm"
 	"github.com/rdlucklib/rdluck_tools/paging"
+	"strconv"
+	"strings"
 	"time"
 )
 
@@ -61,7 +63,7 @@ type EdbInfoItem struct {
 // GetEdbInfoAll 用于分类展示
 func GetEdbInfoAll(edbInfoType uint8) (items []*EdbClassifyItems, err error) {
 	o := orm.NewOrmUsingDB("data")
-	sql := ` SELECT edb_info_id,classify_id,edb_name_source AS classify_name,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
+	sql := ` SELECT edb_info_id,classify_id,edb_name_source AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
 	_, err = o.Raw(sql, edbInfoType).QueryRows(&items)
 	return
 }
@@ -69,7 +71,7 @@ func GetEdbInfoAll(edbInfoType uint8) (items []*EdbClassifyItems, err error) {
 // GetPredictEdbInfoAll 用于分类展示(预测指标)
 func GetPredictEdbInfoAll(edbInfoType uint8) (items []*EdbClassifyItems, err error) {
 	o := orm.NewOrmUsingDB("data")
-	sql := ` SELECT edb_info_id,classify_id,edb_name AS classify_name,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
+	sql := ` SELECT edb_info_id,classify_id,edb_name AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
 	_, err = o.Raw(sql, edbInfoType).QueryRows(&items)
 	return
 }
@@ -552,6 +554,7 @@ func ModifyCalculateEdbInfo(item *EditEdbInfoReq) (err error) {
 type AddEdbInfoResp struct {
 	EdbInfoId  int    `description:"指标ID"`
 	UniqueCode string `description:"指标唯一编码"`
+	ClassifyId int    `description:"分类id"`
 }
 
 // 根据基础指标获取所有关联指标
@@ -749,6 +752,21 @@ type EdbInfoReplaceReq struct {
 	NewEdbInfoId int `description:"替换为指标ID"`
 }
 
+// EdbInfoReplaceV2 替换指标v2版本(更换时间:2022年01月05日15:33:42)
+func EdbInfoReplaceV2(oldEdbInfo, newEdbInfo *EdbInfo, sysAdminId int, sysAdminRealName string) (replaceChartTotal, replaceCalculateTotal int, err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("ERR:", err.Error())
+		}
+	}()
+	mappingList, replaceChartTotal, replaceCalculateTotal, err := replaceChartEdb(oldEdbInfo, newEdbInfo)
+	if err != nil {
+		return
+	}
+	err = replaceRelationEdbInfo(mappingList, oldEdbInfo, newEdbInfo, sysAdminId, sysAdminRealName)
+	return
+}
+
 // ReplaceChartEdb 替换图表中的指标
 func ReplaceChartEdb(oldEdbInfo, newEdbInfo *EdbInfo) (mappingList []*EdbInfoCalculateMapping, replaceChartTotal, replaceCalculateTotal int, err error) {
 	return replaceChartEdb(oldEdbInfo, newEdbInfo)
@@ -844,6 +862,340 @@ func replaceChartEdb(oldEdbInfo, newEdbInfo *EdbInfo) (mappingList []*EdbInfoCal
 	return
 }
 
+// replaceRelationEdbInfo 替换关联指标
+func replaceRelationEdbInfo(mappingList []*EdbInfoCalculateMapping, oldEdbInfo, newEdbInfo *EdbInfo, sysAdminId int, sysAdminRealName string) (err error) {
+	errmsg := ``
+	defer func() {
+		if errmsg != "" {
+			fmt.Println("errmsg:" + errmsg)
+		}
+		if err != nil && errmsg != "" {
+			go alarm_msg.SendAlarmMsg("替换关联指标失败提醒,errmsg:"+errmsg, 3)
+			//go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"替换指标失败提醒", "errmsg:"+errmsg, utils.EmailSendToUsers)
+		}
+	}()
+	//获取计算指标关联指标
+	allMappingList := make([]*EdbInfoCalculateMapping, 0)
+	allMapping := make(map[int]int)
+	tmpMapping := make(map[int]int)
+	for _, v := range mappingList {
+		if _, ok := allMapping[v.EdbInfoId]; !ok {
+			allMappingList = append(allMappingList, v)
+		}
+		newList, _ := GetAllCalculateV2(v.EdbInfoId, newEdbInfo.EdbInfoId, tmpMapping)
+		for _, nv := range newList {
+			if _, ok := allMapping[v.EdbInfoId]; !ok {
+				allMappingList = append(allMappingList, nv)
+			}
+			allMapping[v.EdbInfoId] = v.EdbInfoId
+		}
+		allMapping[v.EdbInfoId] = v.EdbInfoId
+	}
+	for mk, mv := range allMappingList { //原指标关联的所有计算指标
+		fmt.Println("mk/mv", mk, mv)
+		//重新计算计算指标
+		{
+			edbInfo, tmpErr := GetEdbInfoById(mv.EdbInfoId) //计算指标
+			err = tmpErr
+			if err != nil {
+				if err.Error() == utils.ErrNoRow() {
+					errmsg = "计算指标已被删除"
+				} else {
+					errmsg = "获取计算指标失败:err:" + err.Error()
+				}
+				return
+			}
+
+			fromEdbInfoList, tmpErr := GetEdbInfoCalculateDetail(mv.EdbInfoId, edbInfo.Source)
+			err = tmpErr
+			if err != nil {
+				errmsg = "获取计算指标失败:err:" + err.Error()
+				return
+			}
+			if len(fromEdbInfoList) <= 0 {
+				errmsg = "计算指标所依赖指标不存在"
+				err = fmt.Errorf("计算指标所依赖指标不存在")
+				return
+			}
+			fromEdbInfoItem := fromEdbInfoList[0]
+			if fromEdbInfoItem == nil {
+				return
+			}
+			fromEdbInfo, tmpErr := GetEdbInfoById(fromEdbInfoItem.FromEdbInfoId)
+			err = tmpErr
+			if err != nil {
+				errmsg = "获取计算指标 来源指标失败:err:" + err.Error()
+				return
+			}
+			edbCode := edbInfo.EdbCode
+			uniqueCode := edbInfo.UniqueCode
+			sourName := edbInfo.SourceName
+			source := edbInfo.Source
+			edbInfoId := edbInfo.EdbInfoId
+
+			req := new(EdbInfoCalculateBatchSaveReq)
+			req.EdbInfoId = edbInfoId
+			req.EdbName = edbInfo.EdbName
+			req.Frequency = edbInfo.Frequency
+			req.Unit = edbInfo.Unit
+			req.ClassifyId = edbInfo.ClassifyId
+			req.FromEdbInfoId = fromEdbInfoList[0].FromEdbInfoId
+
+			if source == utils.DATA_SOURCE_CALCULATE {
+				//检验公式
+				var formulaStr string
+				var edbInfoIdBytes []string
+				for _, v := range fromEdbInfoList {
+					formulaStr += v.FromTag + ","
+					edbInfoIdBytes = append(edbInfoIdBytes, v.FromTag)
+				}
+				formulaStr = strings.Trim(formulaStr, ",")
+				formulaMap := CheckFormula(edbInfo.CalculateFormula)
+				for _, v := range formulaMap {
+					if !strings.Contains(formulaStr, v) {
+						errmsg = "公式错误,请重新填写"
+						err = fmt.Errorf("公式错误,请重新填写")
+						return
+					}
+				}
+
+				edbInfoList := make([]*EdbInfo, 0)
+
+				for _, v := range fromEdbInfoList {
+					edbInfo, tmpErr := GetEdbInfoById(v.FromEdbInfoId)
+					err = tmpErr
+					if err != nil {
+						if err.Error() == utils.ErrNoRow() {
+							errmsg = "指标 " + strconv.Itoa(v.FromEdbInfoId) + " 不存在"
+						} else {
+							errmsg = "获取指标失败:Err:" + err.Error()
+						}
+						return
+					}
+					edbInfoList = append(edbInfoList, edbInfo)
+				}
+				//清除历史数据
+				err = DeleteCalculateData(edbInfoId)
+				if err != nil {
+					errmsg = "清空运算指标失败:Err:" + err.Error() + " edb_info_id:" + strconv.Itoa(edbInfoId)
+					return
+				}
+				err = Calculate(edbInfoList, int(edbInfoId), edbCode, edbInfo.CalculateFormula, edbInfoIdBytes)
+				if err != nil {
+					errmsg = "生成计算指标失败,Calculate Err:" + err.Error()
+					return
+				}
+			} else if source == utils.DATA_SOURCE_CALCULATE_LJZZY {
+				_, err = AddCalculateLjzzy(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName)
+			} else if source == utils.DATA_SOURCE_CALCULATE_TBZ {
+				sourName = "同比值"
+				edbInfoId, err = AddCalculateTbz(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName)
+			} else if source == utils.DATA_SOURCE_CALCULATE_TCZ {
+				sourName = "同差值"
+				edbInfoId, err = AddCalculateTcz(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName)
+			} else if source == utils.DATA_SOURCE_CALCULATE_NSZYDPJJS {
+				sourName = "N数值移动平均计算"
+				formulaInt, _ := strconv.Atoi(edbInfo.CalculateFormula)
+				edbInfoId, err = AddCalculateNszydpjjs(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName, formulaInt)
+			} else if source == utils.DATA_SOURCE_CALCULATE_HBZ {
+				sourName = "环比值"
+				formulaInt, _ := strconv.Atoi(edbInfo.CalculateFormula)
+				edbInfoId, err = AddCalculateHbz(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName, formulaInt)
+			} else if source == utils.DATA_SOURCE_CALCULATE_HCZ {
+				sourName = "环差值"
+				formulaInt, _ := strconv.Atoi(edbInfo.CalculateFormula)
+				edbInfoId, err = AddCalculateHcz(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName, formulaInt)
+			} else if source == utils.DATA_SOURCE_CALCULATE_BP {
+				sourName = "变频"
+				fmt.Println("变频", req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName)
+				edbInfoId, err = AddCalculateBp(req, fromEdbInfo, edbCode, uniqueCode, sysAdminId, sysAdminRealName)
+			} else if source == utils.DATA_SOURCE_CALCULATE_TIME_SHIFT {
+				req2 := &EdbInfoCalculateBatchEditReq{
+					EdbName:       edbInfo.EdbName,
+					Frequency:     edbInfo.Frequency,
+					Unit:          edbInfo.Unit,
+					ClassifyId:    edbInfo.ClassifyId,
+					Formula:       edbInfo.CalculateFormula,
+					EdbInfoId:     edbInfo.EdbInfoId,
+					FromEdbInfoId: fromEdbInfoList[0].FromEdbInfoId,
+					Source:        edbInfo.Source,
+					MoveType:      edbInfo.MoveType,
+					MoveFrequency: edbInfo.MoveFrequency,
+				}
+				sourName = "时间移位"
+				edbInfoId, err = EditCalculateTimeShift(req2, fromEdbInfo, edbCode, edbInfo)
+			} else if source == utils.DATA_SOURCE_CALCULATE_ZJPJ {
+				edbInfoIdArr := make([]EdbInfoFromTag, 0)
+				//A指标
+				aFromEdbInfoId := fromEdbInfoList[0].FromEdbInfoId
+				for _, v := range fromEdbInfoList {
+					if v.FromTag == "A" {
+						if v.FromEdbInfoId == oldEdbInfo.EdbInfoId {
+							aFromEdbInfoId = newEdbInfo.EdbInfoId
+						} else {
+							aFromEdbInfoId = fromEdbInfoList[0].FromEdbInfoId
+						}
+					}
+					if v.FromTag == "B" {
+						if v.FromEdbInfoId == oldEdbInfo.EdbInfoId {
+							edbInfoIdArr = append(edbInfoIdArr, EdbInfoFromTag{
+								EdbInfoId: newEdbInfo.EdbInfoId,
+								FromTag:   v.FromTag,
+								MoveValue: v.MoveValue,
+							})
+						} else {
+							edbInfoIdArr = append(edbInfoIdArr, EdbInfoFromTag{
+								EdbInfoId: v.FromEdbInfoId,
+								FromTag:   v.FromTag,
+								MoveValue: v.MoveValue,
+							})
+						}
+					}
+				}
+				req2 := &EdbInfoCalculateBatchEditReq{
+					EdbName:       edbInfo.EdbName,
+					Frequency:     edbInfo.Frequency,
+					Unit:          edbInfo.Unit,
+					ClassifyId:    edbInfo.ClassifyId,
+					Formula:       edbInfo.CalculateFormula,
+					EdbInfoId:     edbInfo.EdbInfoId,
+					FromEdbInfoId: aFromEdbInfoId,
+					Source:        edbInfo.Source,
+					MoveType:      edbInfo.MoveType,
+					MoveFrequency: edbInfo.MoveFrequency,
+					EdbInfoIdArr:  edbInfoIdArr,
+				}
+
+				sourName = "直接拼接"
+				if len(req2.EdbInfoIdArr) != 1 {
+					errmsg = "请传入拼接日期之后的指标"
+					err = fmt.Errorf("请传入拼接日期之后的指标")
+					return
+				}
+
+				secondEdbInfoReq := req2.EdbInfoIdArr[0]
+				secondEdbInfo, tmpErr := GetEdbInfoById(secondEdbInfoReq.EdbInfoId)
+				err = tmpErr
+				if err != nil {
+					errmsg = "获取拼接日期之后的指标信息失败:Err:" + err.Error()
+					err = fmt.Errorf("获取拼接日期之后的指标信息失败:Err:" + err.Error())
+					return
+				}
+
+				if fromEdbInfo.EdbInfoId == secondEdbInfo.EdbInfoId {
+					errmsg = "两个指标不允许为同一个"
+					err = fmt.Errorf("两个指标不允许为同一个")
+					return
+				}
+				tmpEdbInfoId, tmpErr := EditCalculateZjpj(req2, edbInfo, fromEdbInfo, secondEdbInfo)
+				err = tmpErr
+				edbInfoId = tmpEdbInfoId
+			} else if source == utils.DATA_SOURCE_CALCULATE_LJZTBPJ { //累计值同比拼接
+				edbInfoIdArr := make([]EdbInfoFromTag, 0)
+				//A指标
+				aFromEdbInfoId := fromEdbInfoList[0].FromEdbInfoId
+				for _, v := range fromEdbInfoList {
+					if v.FromTag == "A" {
+						if v.FromEdbInfoId == oldEdbInfo.EdbInfoId {
+							aFromEdbInfoId = newEdbInfo.EdbInfoId
+						} else {
+							aFromEdbInfoId = fromEdbInfoList[0].FromEdbInfoId
+						}
+					}
+					if v.FromTag == "B" {
+						if v.FromEdbInfoId == oldEdbInfo.EdbInfoId {
+							edbInfoIdArr = append(edbInfoIdArr, EdbInfoFromTag{
+								EdbInfoId: newEdbInfo.EdbInfoId,
+								FromTag:   v.FromTag,
+								MoveValue: v.MoveValue,
+							})
+						} else {
+							edbInfoIdArr = append(edbInfoIdArr, EdbInfoFromTag{
+								EdbInfoId: v.FromEdbInfoId,
+								FromTag:   v.FromTag,
+								MoveValue: v.MoveValue,
+							})
+						}
+					}
+				}
+
+				req2 := &EdbInfoCalculateBatchEditReq{
+					EdbName:       edbInfo.EdbName,
+					Frequency:     edbInfo.Frequency,
+					Unit:          edbInfo.Unit,
+					ClassifyId:    edbInfo.ClassifyId,
+					Formula:       edbInfo.CalculateFormula,
+					EdbInfoId:     edbInfo.EdbInfoId,
+					FromEdbInfoId: aFromEdbInfoId,
+					Source:        edbInfo.Source,
+					MoveType:      edbInfo.MoveType,
+					MoveFrequency: edbInfo.MoveFrequency,
+					EdbInfoIdArr:  edbInfoIdArr,
+				}
+
+				sourName = "累计值同比拼接"
+
+				if fromEdbInfo.Frequency != "月度" {
+					errmsg = "累计值同比拼接,待拼接指标只能筛选月度指标"
+					err = fmt.Errorf("累计值同比拼接,待拼接指标只能筛选月度指标")
+					return
+				}
+				if len(req2.EdbInfoIdArr) != 1 {
+					errmsg = "请传入同比值指标"
+					err = fmt.Errorf("请传入同比值指标")
+					return
+				}
+
+				secondEdbInfoReq := req2.EdbInfoIdArr[0]
+				tbzEdbInfo, tmpErr := GetEdbInfoById(secondEdbInfoReq.EdbInfoId)
+				err = tmpErr
+				if err != nil {
+					errmsg = "获取同比值指标信息失败:Err:" + err.Error()
+					err = fmt.Errorf("获取同比值指标信息失败:Err:" + err.Error())
+					return
+				}
+				if tbzEdbInfo.Source != utils.DATA_SOURCE_CALCULATE_TBZ {
+					errmsg = "指标必须是传入同比值指标类型"
+					err = fmt.Errorf("指标必须是传入同比值指标类型")
+					return
+				}
+				if tbzEdbInfo.Frequency != "月度" {
+					errmsg = "同比值指标只能筛选月度指标"
+					err = fmt.Errorf("同比值指标只能筛选月度指标")
+					return
+				}
+
+				if fromEdbInfo.EdbInfoId == tbzEdbInfo.EdbInfoId {
+					errmsg = "两个指标不允许为同一个"
+					err = fmt.Errorf("两个指标不允许为同一个")
+					return
+				}
+				tmpEdbInfoId, tmpErr := EditCalculateLjztbpj(req2, edbInfo, fromEdbInfo, tbzEdbInfo)
+				err = tmpErr
+				edbInfoId = tmpEdbInfoId
+			} else if source == utils.DATA_SOURCE_PYTHON {
+				//python代码运算的过滤
+				continue
+			} else {
+				errmsg = "无效计算方式,source:" + strconv.Itoa(source)
+				err = fmt.Errorf("无效计算方式,source:" + strconv.Itoa(source))
+				return
+			}
+			maxAndMinItem, tmpErr := GetEdbInfoMaxAndMinInfo(source, edbCode)
+			err = tmpErr
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				errmsg = "生成" + sourName + "失败,GetEdbInfoMaxAndMinInfo Err:" + err.Error()
+				err = fmt.Errorf("生成" + sourName + "失败,GetEdbInfoMaxAndMinInfo Err:" + err.Error())
+				return
+			}
+			if maxAndMinItem != nil {
+				err = ModifyEdbInfoMaxAndMinInfo(edbInfoId, maxAndMinItem)
+			}
+		}
+	}
+	return
+}
+
 type EdbInfoView struct {
 	EdbInfoId        int    `orm:"column(edb_info_id);pk"`
 	EdbInfoType      int    `description:"指标类型,0:普通指标,1:预测指标"`
@@ -1042,6 +1394,18 @@ func GetEdbInfoListByCondition(condition string, pars []interface{}, startSize,
 	return
 }
 
+// GetEdbInfoListV2ByCondition 根据条件获取指标列表数据(EdbInfo原始数据结构)
+func GetEdbInfoListV2ByCondition(condition string, pars []interface{}, startSize, pageSize int) (items []*EdbInfo, err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` SELECT * FROM edb_info WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` ORDER BY edb_info_id ASC LIMIT ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
 // GetEdbInfoListGroupByUserId 根据指标id列表、用户分组获取指标信息
 func GetEdbInfoListGroupByUserId(edbIdList []string) (items []*EdbInfo, err error) {
 	num := len(edbIdList)
@@ -1117,7 +1481,7 @@ type SetEdbDataInsertConfigReq struct {
 // GetEdbInfoAll 用于分类展示
 func GetEdbInfoByClassifyId(classifyId, edbInfoType int) (items []*EdbClassifyItems, err error) {
 	o := orm.NewOrmUsingDB("data")
-	sql := ` SELECT edb_info_id,classify_id,edb_name_source AS classify_name,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE classify_id = ? AND edb_info_type = ? order by sort asc,edb_info_id asc`
+	sql := ` SELECT edb_info_id,classify_id,edb_name_source AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE classify_id = ? AND edb_info_type = ? order by sort asc,edb_info_id asc`
 	_, err = o.Raw(sql, classifyId, edbInfoType).QueryRows(&items)
 	return
 }
@@ -1152,9 +1516,27 @@ func GetEdbInfoAndClassifyListByEdbIdList(edbIdList []int) (items []*EdbAndClass
 
 // TraceEdbInfoResp 指标追溯数据返回
 type TraceEdbInfoResp struct {
-	//EdbInfo   *EdbInfo
-	EdbInfoId int                `description:"指标id"`
-	EdbName   string             `description:"指标名称"`
-	RuleTitle string             `description:"指标规则"`
-	Child     []TraceEdbInfoResp `description:"下级来源"`
+	EdbInfoId   int                `description:"指标id"`
+	EdbInfoType int                `description:"指标类型: 0-普通指标; 1-预测指标"`
+	EdbName     string             `description:"指标名称"`
+	EdbType     int                `description:"指标类型: 1-基础指标; 2-计算指标"`
+	RuleTitle   string             `description:"指标规则"`
+	UniqueCode  string             `description:"唯一编码"`
+	ClassifyId  int                `description:"分类ID"`
+	Child       []TraceEdbInfoResp `description:"下级来源"`
+}
+
+// BeforeAndAfterDateDataResp 前后几期数据
+type BeforeAndAfterDateDataResp struct {
+	List []*EdbDataList `description:"list"`
+	Date string         `description:"实际日期"`
+}
+
+// GetEdbInfoAdminList
+func GetEdbInfoAdminList(edbType int) (list []int, err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` SELECT sys_user_id FROM edb_info WHERE edb_info_type = ? GROUP BY sys_user_id  `
+
+	_, err = o.Raw(sql, edbType).QueryRows(&list)
+	return
 }

+ 89 - 0
models/data_manage/edb_info_calculate.go

@@ -1,9 +1,12 @@
 package data_manage
 
 import (
+	"errors"
 	"eta/eta_mobile/utils"
 	"fmt"
 	"github.com/beego/beego/v2/client/orm"
+	"github.com/yidane/formula"
+	"strconv"
 	"strings"
 	"time"
 )
@@ -546,6 +549,92 @@ func GetFormulaMap() map[string]string {
 	return funMap
 }
 
+func Calculate(edbInfoIdArr []*EdbInfo, edbInfoId int, edbCode, formulaStr string, edbInfoIdBytes []string) (err error) {
+	defer func() {
+		if err != nil {
+			utils.FileLog.Info("Calculate Err:%s" + err.Error())
+		}
+	}()
+	saveDataMap := make(map[string]map[int]float64)
+	for _, v := range edbInfoIdArr {
+		var condition string
+		var pars []interface{}
+		condition += " AND edb_info_id=? "
+		pars = append(pars, v.EdbInfoId)
+		dataList, err := GetEdbDataListAll(condition, pars, v.Source, 1)
+		if err != nil {
+			return err
+		}
+		dataMap := make(map[string]float64)
+		for _, dv := range dataList {
+			if val, ok := saveDataMap[dv.DataTime]; ok {
+				if _, ok := val[v.EdbInfoId]; !ok {
+					val[v.EdbInfoId] = dv.Value
+				}
+			} else {
+				temp := make(map[int]float64)
+				temp[v.EdbInfoId] = dv.Value
+				saveDataMap[dv.DataTime] = temp
+			}
+		}
+		item := new(CalculateItems)
+		item.EdbInfoId = v.EdbInfoId
+		item.DataMap = dataMap
+	}
+	formulaMap := CheckFormula(formulaStr)
+	addSql := ` INSERT INTO edb_data_calculate(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	nowStr := time.Now().Format(utils.FormatDateTime)
+	var isAdd bool
+
+	for sk, sv := range saveDataMap {
+		formulaStr = strings.ToUpper(formulaStr)
+		formulaFormStr := ReplaceFormula(edbInfoIdArr, sv, formulaMap, formulaStr, edbInfoIdBytes)
+		if formulaStr == "" {
+			return
+		}
+		if formulaFormStr != "" {
+			utils.FileLog.Info("formulaFormStr:%s", formulaFormStr)
+			expression := formula.NewExpression(formulaFormStr)
+			calResult, err := expression.Evaluate()
+			if err != nil {
+				err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+			calVal, err := calResult.Float64()
+			if err != nil {
+				err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+
+			//需要存入的数据
+			{
+				dataTime, _ := time.Parse(utils.FormatDate, sk)
+				timestamp := dataTime.UnixNano() / 1e6
+				timeStr := fmt.Sprintf("%d", timestamp)
+				addSql += "("
+				addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + sk + "'" + "," + utils.SubFloatToString(calVal, 4) + "," + "'" + nowStr + "'" +
+					"," + "'" + nowStr + "'" + "," + "1"
+				addSql += "," + "'" + timeStr + "'"
+				addSql += "),"
+				isAdd = true
+			}
+		} else {
+			fmt.Println("formulaFormStr is empty")
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		AddEdbDataCalculateBySql(addSql)
+		if err != nil {
+			fmt.Println("AddEdbDataCalculate Err:" + err.Error())
+			return err
+		}
+	}
+	return
+}
+
 // SaveAdjustEdbInfoReq 保存数据调整请求参数(请求指标服务)
 type SaveAdjustEdbInfoReq struct {
 	AdminId       int                    `description:"添加人id"`

+ 157 - 0
models/data_manage/edb_info_calculate_bp.go

@@ -0,0 +1,157 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// 变频
+func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+	fmt.Println("AddCalculateBp")
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("AddCalculateBp,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_BP
+		edbInfo.SourceName = "变频"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_BP)
+		fmt.Println("dataTableName:" + dataTableName)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+		if err != nil {
+			return 0, err
+		}
+	}
+
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return edbInfoId, err
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+	existMap := make(map[string]string)
+	dataLen := len(dataList)
+	fmt.Println("dataLen:", dataLen)
+
+	for i := 0; i < dataLen; i++ {
+		//当期
+		currentItem := dataList[i]
+		currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
+		var day int
+		var preItem *EdbInfoSearchData
+		var preDate time.Time
+		if i == 0 {
+			day = int(time.Now().Sub(currentDate).Hours() / float64(24))
+			preDate = time.Now()
+		} else {
+			j := i - 1
+			if j < dataLen {
+				preItem = dataList[j]
+				preDate, _ = time.Parse(utils.FormatDate, preItem.DataTime)
+				day = int(preDate.Sub(currentDate).Hours() / float64(24))
+				utils.FileLog.Info("preItem.DataTime:" + preItem.DataTime + ";currentItem.DataTime" + currentItem.DataTime)
+			}
+		}
+		for k := 0; k <= day; k++ {
+			needDay := preDate.AddDate(0, 0, -k)
+			needDayStr := needDay.Format(utils.FormatDate)
+			existKey := edbCode + needDayStr
+			if _, ok := existMap[existKey]; !ok {
+				timestamp := needDay.UnixNano() / 1e6
+				timestampStr := fmt.Sprintf("%d", timestamp)
+				valStr := decimal.NewFromFloat(currentItem.Value).String()
+				addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
+				isAdd = true
+			}
+			existMap[existKey] = needDayStr
+		}
+		existKey := edbCode + currentItem.DataTime
+		if _, ok := existMap[existKey]; !ok {
+			currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
+			timestamp := currentDate.UnixNano() / 1e6
+			timestampStr := fmt.Sprintf("%d", timestamp)
+			valStr := decimal.NewFromFloat(currentItem.Value).String()
+			addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, valStr)
+			isAdd = true
+		}
+		existMap[existKey] = currentItem.DataTime
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}

+ 144 - 0
models/data_manage/edb_info_calculate_hbz.go

@@ -0,0 +1,144 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/shopspring/decimal"
+)
+
+// 环比值
+func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+	fmt.Println("AddCalculateHbz")
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("AddCalculateHbz,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HBZ
+		edbInfo.SourceName = "环比值"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HBZ)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+	}
+
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return edbInfoId, err
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+	existMap := make(map[string]string)
+	dataLen := len(dataList)
+	for i := 0; i < dataLen; i++ {
+		j := i + formulaInt
+		if j < dataLen {
+			//当期
+			currentItem := dataList[i]
+			preItem := dataList[j]
+			fmt.Println("preItem.Value:", preItem.Value)
+			if currentItem != nil && preItem != nil && preItem.Value != 0 {
+				existKey := edbCode + currentItem.DataTime
+				if _, ok := existMap[existKey]; !ok {
+					currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
+					timestamp := currentDate.UnixNano() / 1e6
+					timestampStr := fmt.Sprintf("%d", timestamp)
+					val := HbzDiv(currentItem.Value, preItem.Value)
+					if val != "" {
+						addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
+						isAdd = true
+					}
+				}
+				existMap[existKey] = currentItem.DataTime
+			}
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}
+
+// 环比值,current:当期,pre:上期 公式: (当期-上期)/上期
+func HbzDiv(current, pre float64) string {
+	if pre == 0 {
+		return ""
+	}
+	currentVal := decimal.NewFromFloat(float64(current))
+	preVal := decimal.NewFromFloat(float64(pre))
+	val, _ := currentVal.Sub(preVal).Div(preVal).Float64()
+	valStr := utils.SubFloatToString(val, 4)
+	return valStr
+}

+ 149 - 0
models/data_manage/edb_info_calculate_hcz.go

@@ -0,0 +1,149 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// 环差值
+func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+	fmt.Println("AddCalculateHcz")
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("AddCalculateHcz,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HCZ
+		edbInfo.SourceName = "环差值"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HCZ)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+	}
+
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return edbInfoId, err
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+	existMap := make(map[string]string)
+	dataLen := len(dataList)
+	fmt.Println("dataLen:", dataLen)
+	for i := 0; i < dataLen; i++ {
+		j := i + formulaInt
+		if j < dataLen {
+			//当期
+			currentItem := dataList[i]
+			preItem := dataList[j]
+			if currentItem != nil && preItem != nil {
+				existKey := edbCode + currentItem.DataTime
+				if _, ok := existMap[existKey]; !ok {
+					currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
+					timestamp := currentDate.UnixNano() / 1e6
+					timestampStr := fmt.Sprintf("%d", timestamp)
+					val := ""
+					if preItem.Value == 0 {
+						val = "0"
+					} else {
+						val = HczDiv(currentItem.Value, preItem.Value)
+					}
+					if val != "" {
+						addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
+						isAdd = true
+					}
+				}
+				existMap[existKey] = currentItem.DataTime
+			}
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}
+
+// 环差值,current:当期,pre:上期 公式:当期-上期
+func HczDiv(current, pre float64) string {
+	if pre == 0 {
+		return ""
+	}
+	currentVal := decimal.NewFromFloat(current)
+	preVal := decimal.NewFromFloat(pre)
+	val, _ := currentVal.Sub(preVal).Float64()
+	valStr := utils.SubFloatToString(val, 4)
+	return valStr
+}

+ 387 - 0
models/data_manage/edb_info_calculate_ljztbpj.go

@@ -0,0 +1,387 @@
+package data_manage
+
+import (
+	"errors"
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"sort"
+	"strings"
+	"time"
+)
+
+// EditCalculateLjztbpj 编辑累计值同比拼接数据
+func EditCalculateLjztbpj(req *EdbInfoCalculateBatchEditReq, nowEdbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (edbInfoId int, err error) {
+	edbInfoId = req.EdbInfoId
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	sql := ``
+
+	var existCondition string
+	var existPars []interface{}
+	existCondition += " AND edb_info_id=? "
+	existPars = append(existPars, edbInfoId)
+
+	//查询出所有的关联指标
+	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
+	if err != nil {
+		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
+		return
+	}
+
+	var existItemA, existItemB *EdbInfoCalculateMapping
+	for _, existItem := range existList {
+		if existItem.FromTag == "A" {
+			existItemA = existItem
+		} else if existItem.FromTag == "B" {
+			existItemB = existItem
+		}
+	}
+	// 原数据开始计算日期
+	startCalculationDate, _ := time.ParseInLocation(utils.FormatDate, nowEdbInfo.CalculateFormula, time.Local)
+
+	//待拼接指标map
+	pjDataMap := make(map[string]float64)     //需要入库的数据
+	nowEdbDataMap := make(map[string]float64) //当前指标的数据(已经在库里了,不需要重新)
+
+	//拼接指标的日期切片数据
+	pjEdbDataTimeList := make([]string, 0)
+
+	//最近开始的时间
+	lastDateTime := startCalculationDate
+
+	//待拼接指标数据
+	{
+		//如果拼接指标变更了,那么需要删除所有的指标进行重新拼接
+		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
+			//删除旧的指标数据
+			{
+				//删除之前的A指标关联关系
+				sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+				_, err = to.Raw(sql, edbInfoId, existItemA.FromEdbInfoId).Exec()
+				if err != nil {
+					err = errors.New("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
+					return
+				}
+
+				//如果拼接指标变更了,那么需要删除所有的指标数据
+				tableName := GetEdbDataTableName(nowEdbInfo.Source)
+				sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
+
+				_, err = to.Raw(sql, edbInfoId).Exec()
+				if err != nil {
+					err = errors.New("删除所有的累计值同比拼接指标数据失败,Err:" + err.Error())
+					return
+				}
+			}
+
+			//添加新的指标关系
+			{
+				calculateMappingItem := new(EdbInfoCalculateMapping)
+				calculateMappingItem.CreateTime = time.Now()
+				calculateMappingItem.ModifyTime = time.Now()
+				calculateMappingItem.Sort = 1
+				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
+				calculateMappingItem.EdbInfoId = edbInfoId
+				calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
+				calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
+				calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
+				calculateMappingItem.FromSource = firstEdbInfo.Source
+				calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
+				calculateMappingItem.FromTag = "A"
+				calculateMappingItem.Source = nowEdbInfo.Source
+				calculateMappingItem.SourceName = nowEdbInfo.SourceName
+				_, err = to.Insert(calculateMappingItem)
+				if err != nil {
+					return
+				}
+			}
+
+			var condition string
+			var pars []interface{}
+
+			//获取待拼接指标最近的个12月31日有值的年份
+			condition += " AND data_time like ? AND edb_info_id=? "
+			pars = append(pars, "%12-31", firstEdbInfo.EdbInfoId)
+
+			//获取最新的待拼接指标
+			lastEdbData, tmpErr := GetLastEdbData(condition, pars, firstEdbInfo.Source)
+			if tmpErr != nil {
+				return edbInfoId, tmpErr
+			}
+			lastDateTime, _ = time.ParseInLocation(utils.FormatDate, lastEdbData.DataTime, time.Local)
+
+			//获取待拼接指标的数据列表
+			condition = ``
+			pars = make([]interface{}, 0)
+			condition += " AND data_time <= ? AND edb_info_id=? "
+			pars = append(pars, lastEdbData.DataTime, firstEdbInfo.EdbInfoId)
+
+			firstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
+			if tmpErr != nil {
+				return edbInfoId, tmpErr
+			}
+
+			for _, v := range firstDataList {
+				pjDataMap[v.DataTime] = v.Value
+				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
+
+				//将新的数据存入已入库指标map里面,以便后续计算
+				nowEdbDataMap[v.DataTime] = v.Value
+			}
+		} else {
+			// 获取当前指标的所有数据
+			var condition string
+			var pars []interface{}
+			condition += " AND edb_info_id=? and data_time <= ?"
+			pars = append(pars, nowEdbInfo.EdbInfoId, nowEdbInfo.CalculateFormula)
+
+			nowEdbDataList, tmpErr := GetEdbDataListAll(condition, pars, nowEdbInfo.Source, 0)
+			if tmpErr != nil {
+				return edbInfoId, tmpErr
+			}
+
+			for _, v := range nowEdbDataList {
+				nowEdbDataMap[v.DataTime] = v.Value
+				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
+			}
+		}
+	}
+
+	//同比值指标map
+	tbzEdbDataMap := make(map[string]float64)
+
+	//同比值日期切片列表
+	tbzEdbDataTimeList := make([]string, 0)
+
+	//同比值指标
+	{
+		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
+			//删除通过B指标生成的数据
+			{
+				//删除之前的B指标关联关系
+				sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+				_, err = to.Raw(sql, edbInfoId, existItemB.FromEdbInfoId).Exec()
+				if err != nil {
+					err = errors.New("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
+					return
+				}
+
+				//如果同比值指标变更了,那么需要删除所有计算出来的指标数据
+				tableName := GetEdbDataTableName(nowEdbInfo.Source)
+				sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time > ? `, tableName)
+
+				_, err = to.Raw(sql, edbInfoId, nowEdbInfo.CalculateFormula).Exec()
+				if err != nil {
+					err = errors.New("删除计算出来的累计值同比拼接指标数据失败,Err:" + err.Error())
+					return
+				}
+			}
+
+			//添加新的指标关系
+			{
+				calculateMappingItem := new(EdbInfoCalculateMapping)
+				calculateMappingItem.CreateTime = time.Now()
+				calculateMappingItem.ModifyTime = time.Now()
+				calculateMappingItem.Sort = 1
+				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
+				calculateMappingItem.EdbInfoId = edbInfoId
+				calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
+				calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
+				calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
+				calculateMappingItem.FromSource = secondEdbInfo.Source
+				calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
+				calculateMappingItem.FromTag = "B"
+				calculateMappingItem.Source = nowEdbInfo.Source
+				calculateMappingItem.SourceName = nowEdbInfo.SourceName
+				_, err = to.Insert(calculateMappingItem)
+				if err != nil {
+					return
+				}
+			}
+		}
+
+		var condition string
+		var pars []interface{}
+
+		condition += " AND data_time > ? AND edb_info_id = ? "
+		pars = append(pars, lastDateTime, secondEdbInfo.EdbInfoId)
+
+		//同比值指标的数据列表
+		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+
+		for _, v := range secondDataList {
+			tbzEdbDataMap[v.DataTime] = v.Value
+			tbzEdbDataTimeList = append(tbzEdbDataTimeList, v.DataTime)
+		}
+	}
+
+	sort.Strings(tbzEdbDataTimeList)
+
+	// 遍历现有的数据,判断拼接指标中是否存在该日期数据,如果拼接指标无此数据,那么需要删除该日期数据(日期的判断:需要在开始计算日期之后)
+	removeDateList := make([]string, 0)
+	for nowEdbDate := range nowEdbDataMap {
+		nowEdbDateTime, _ := time.ParseInLocation(utils.FormatDate, nowEdbDate, time.Local)
+		//校验日期 需要 大于 拼接前日期
+		if startCalculationDate.Before(nowEdbDateTime) {
+			if _, ok := tbzEdbDataMap[nowEdbDate]; !ok {
+				// 同比指标中,不存在该日期数据,那么需要移除 现有数据 中该日期的数据
+				removeDateList = append(removeDateList, nowEdbDate)
+			}
+		}
+	}
+
+	//待修改的指标数据map(index:日期,value:值)
+	updateEdbDataMap := make(map[string]float64)
+	for _, v := range tbzEdbDataTimeList {
+		tbzDataTime, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
+
+		//获取拼接指标上一年同一天的数据
+		var pjDataTime time.Time
+		if tbzDataTime.Month() == 2 {
+			pjDataTime = tbzDataTime.AddDate(0, -11, 0)
+			pjDataTime = time.Date(pjDataTime.Year(), pjDataTime.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, -1)
+		} else {
+			pjDataTime = tbzDataTime.AddDate(-1, 0, 0)
+		}
+
+		//校验现有数据中,是否存在该日期的数据,如果存在的话,那么就要去校验 最新计算数据 与 现有数据 是否一致
+		if nowEdbDataValue, isHas := nowEdbDataMap[v]; isHas {
+			//获取去年今日的数据,获取到后,然后是去修改该日期的数据
+			if lastYearEdbDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
+				tbzDataValue := tbzEdbDataMap[v] //同比值
+				currValue := lastYearEdbDataValue * (1 + tbzDataValue/100)
+				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64() //保留4位小数
+				//如果计算出来的值与库里面的值不匹配,那么就去修改该值
+				if nowEdbDataValue != currValue {
+					//将计算后的数据存入待拼接指标map里面,以便后续计算
+					updateEdbDataMap[v] = currValue
+				}
+			}
+		} else {
+			//因为 现有数据中 不存在该日期数据,那么需要做新增数据处理
+
+			//如果去年今日存在该数据,那么就去计算当前的数据
+			if pjDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
+				tbzDataValue := tbzEdbDataMap[v] //同比值
+				currValue := pjDataValue * (1 + tbzDataValue/100)
+
+				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64()
+				//将计算后的数据存入已入库指标map里面,以便后续计算
+				nowEdbDataMap[v] = currValue
+
+				//将计算后的数据存入待拼接指标map里面,以便后续入库
+				pjDataMap[v] = currValue
+				pjEdbDataTimeList = append(pjEdbDataTimeList, v)
+			}
+		}
+	}
+
+	//新增的数据入库
+	{
+		addDataList := make([]*EdbDataCalculateLjztbpj, 0)
+		for dataTime, dataValue := range pjDataMap {
+			//时间戳
+			currentDate, _ := time.Parse(utils.FormatDate, dataTime)
+			timestamp := currentDate.UnixNano() / 1e6
+
+			edbDataLjztbpj := &EdbDataCalculateLjztbpj{
+				EdbInfoId:     edbInfoId,
+				EdbCode:       nowEdbInfo.EdbCode,
+				DataTime:      dataTime,
+				Value:         dataValue,
+				Status:        1,
+				CreateTime:    time.Now(),
+				ModifyTime:    time.Now(),
+				DataTimestamp: timestamp,
+			}
+			addDataList = append(addDataList, edbDataLjztbpj)
+		}
+
+		tmpAddDataList := make([]*EdbDataCalculateLjztbpj, 0)
+		for _, v := range addDataList {
+			tmpAddDataList = append(tmpAddDataList, v)
+
+			if len(tmpAddDataList) >= 200 {
+				_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+				if tmpErr != nil {
+					err = tmpErr
+					return
+				}
+				//重新初始化需要加入的数据切片
+				tmpAddDataList = make([]*EdbDataCalculateLjztbpj, 0)
+			}
+		}
+		//最后如果还有需要新增的数据,那么就统一入库
+		if len(tmpAddDataList) > 0 {
+			_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+			if tmpErr != nil {
+				err = tmpErr
+				return
+			}
+		}
+	}
+
+	//删除已经不存在的累计同比拼接指标数据(由于同比值当日的数据删除了)
+	{
+		if len(removeDateList) > 0 {
+			removeDateStr := strings.Join(removeDateList, `","`)
+			removeDateStr = `"` + removeDateStr + `"`
+			//如果拼接指标变更了,那么需要删除所有的指标数据
+			tableName := GetEdbDataTableName(nowEdbInfo.Source)
+			sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
+
+			_, err = to.Raw(sql, edbInfoId).Exec()
+			if err != nil {
+				err = errors.New("删除不存在的累计值同比拼接指标数据失败,Err:" + err.Error())
+				return
+			}
+		}
+	}
+
+	//修改现有的数据中对应的值
+	{
+		tableName := GetEdbDataTableName(nowEdbInfo.Source)
+		for edbDate, edbDataValue := range updateEdbDataMap {
+			sql = fmt.Sprintf(` UPDATE  %s set value = %f,modify_time=now() WHERE edb_info_id = ? and data_time = %s `, tableName, edbDataValue, edbDate)
+
+			_, err = to.Raw(sql, edbInfoId).Exec()
+			if err != nil {
+				err = errors.New("更新现有的累计值同比拼接指标数据失败,Err:" + err.Error())
+				return
+			}
+		}
+	}
+
+	//修改指标信息
+	sql = ` UPDATE  edb_info SET
+			  edb_name =?,
+			  edb_name_source=?,
+			  frequency = ?,
+			  unit = ?,
+			  classify_id = ?, 
+			  calculate_formula=?,
+			  modify_time = NOW()
+			WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, lastDateTime.Format(utils.FormatDate), edbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	return
+}

+ 210 - 0
models/data_manage/edb_info_calculate_ljzzy.go

@@ -0,0 +1,210 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// 累计值转月
+func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_LJZZY
+		edbInfo.SourceName = "累计值转月值"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return int(newEdbInfoId), tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+
+		//calculateItem := new(EdbInfoCalculateLjzzy)
+		//calculateItem.CreateTime = time.Now()
+		//calculateItem.ModifyTime = time.Now()
+		//calculateItem.Sort = 1
+		//calculateItem.EdbCode = edbCode
+		//calculateItem.EdbInfoId = edbInfoId
+		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
+		//calculateItem.FromEdbName = fromEdbInfo.EdbName
+		//calculateItem.FromSource = fromEdbInfo.Source
+		//calculateItem.FromSourceName = fromEdbInfo.SourceName
+		//_, err = to.Insert(calculateItem)
+		//if err != nil {
+		//	return edbInfoId, err
+		//}
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_LJZZY)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+	}
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+	fmt.Println("EdbInfoId:", req.FromEdbInfoId)
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
+	if err != nil {
+		return edbInfoId, err
+	}
+
+	yearMap := make(map[int]map[int]*EdbInfoSearchData)
+	dataLen := len(dataList)
+	for i := 0; i < dataLen; i++ {
+		item := dataList[i]
+		//日其中获取年
+		itemDate, err := time.Parse(utils.FormatDate, item.DataTime)
+		if err != nil {
+			return edbInfoId, err
+		}
+		year := itemDate.Year()
+		month := int(itemDate.Month())
+		if monthMap, yok := yearMap[year]; yok {
+			monthMap[month] = item
+			yearMap[year] = monthMap
+		} else {
+			monthMap = make(map[int]*EdbInfoSearchData)
+			monthMap[month] = item
+			yearMap[year] = monthMap
+		}
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+	existMap := make(map[string]string)
+	for yk, yv := range yearMap {
+		_, oneMonthOk := yv[1]
+		_, twoMonthOk := yv[2]
+		if !oneMonthOk && !twoMonthOk {
+			continue
+		}
+		for i := 1; i <= 12; i++ {
+			fmt.Println(yk, i, yv[i])
+			dataCurrentItem := yv[i]
+			fmt.Println("i:", i, yk, dataCurrentItem)
+			var date string
+			var val float64
+			if i == 1 || i == 2 {
+				if _, mok := yv[1]; mok { //1月有值
+					if i == 1 {
+						date = dataCurrentItem.DataTime
+						val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
+					}
+					if i == 2 {
+						dataOneItem := yv[1]
+						if dataCurrentItem != nil {
+							date = dataCurrentItem.DataTime
+							twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
+							oneMonth := decimal.NewFromFloat(dataOneItem.Value)
+							val, _ = twoMonth.Sub(oneMonth).Float64()
+						} else {
+							continue
+						}
+					}
+				} else { //1月无值
+					dataTwoItem := yv[2]
+					if i == 1 {
+						date = strconv.Itoa(yk) + "-01-31"
+						a := decimal.NewFromFloat(dataTwoItem.Value)
+						b := decimal.NewFromFloat(2.0)
+						val, _ = a.Div(b).Float64()
+					}
+					if i == 2 {
+						date = dataCurrentItem.DataTime
+						a := decimal.NewFromFloat(dataTwoItem.Value)
+						b := decimal.NewFromFloat(2.0)
+						val, _ = a.Div(b).Float64()
+					}
+				}
+			} else {
+				dataPreItem := yv[i-1]
+				if dataCurrentItem != nil && dataPreItem != nil {
+					date = dataCurrentItem.DataTime
+					//val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Sub(decimal.NewFromFloat(dataPreItem.Value)).Float64()
+					a := decimal.NewFromFloat(dataCurrentItem.Value)
+					b := decimal.NewFromFloat(dataPreItem.Value)
+					val, _ = a.Sub(b).Float64()
+				}
+			}
+
+			if date != "" {
+				dataTime, _ := time.Parse(utils.FormatDate, date)
+				timestamp := dataTime.UnixNano() / 1e6
+				timeStr := fmt.Sprintf("%d", timestamp)
+
+				if _, ok := existMap[edbCode+date]; !ok {
+					addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, utils.SubFloatToString(val, 4))
+					isAdd = true
+				}
+				existMap[edbCode+date] = date
+			}
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}

+ 173 - 0
models/data_manage/edb_info_calculate_nszydpjjs.go

@@ -0,0 +1,173 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// N数值移动平均计算
+func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
+		edbInfo.SourceName = "N数值移动平均计算"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+
+		//calculateItem := new(EdbInfoCalculateNszydpjjs)
+		//calculateItem.CreateTime = time.Now()
+		//calculateItem.ModifyTime = time.Now()
+		//calculateItem.Sort = 1
+		//calculateItem.EdbCode = edbCode
+		//calculateItem.EdbInfoId = edbInfoId
+		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
+		//calculateItem.FromEdbName = fromEdbInfo.EdbName
+		//calculateItem.FromSource = fromEdbInfo.Source
+		//calculateItem.FromSourceName = fromEdbInfo.SourceName
+		//
+		//_, err = to.Insert(calculateItem)
+		//if err != nil {
+		//	return edbInfoId, err
+		//}
+
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NSZYDPJJS)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+	}
+
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return edbInfoId, err
+	}
+	var dateArr []string
+	dataMap := make(map[string]*EdbInfoSearchData)
+	for _, v := range dataList {
+		dateArr = append(dateArr, v.DataTime)
+		dataMap[v.DataTime] = v
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+
+	arrLen := len(dateArr)
+	for ak, av := range dateArr {
+		//处理第一个值
+		var valArr []float64
+		if findItem, ok := dataMap[av]; ok {
+			valArr = append(valArr, findItem.Value)
+		} else {
+			continue
+		}
+		if ak+1 != arrLen {
+			//处理除第一个值之外的N-1个值
+			for i := 1; i < formulaInt; i++ {
+				arrIndex := ak + i
+				if arrIndex >= arrLen {
+					break
+				}
+				arrVal := dateArr[arrIndex]
+				if findItem, ok := dataMap[arrVal]; ok {
+					valArr = append(valArr, findItem.Value)
+				} else {
+					continue
+				}
+			}
+		}
+		valArrLen := len(valArr)
+		totalVal := decimal.NewFromFloat(0.00)
+		for _, v := range valArr {
+			newDecimal := decimal.NewFromFloat(v)
+			totalVal = totalVal.Add(newDecimal)
+		}
+		af := totalVal //decimal.NewFromFloat(totalVal)
+		bf := decimal.NewFromFloat(float64(valArrLen))
+		val, _ := af.Div(bf).Float64()
+		currentDate, err := time.Parse(utils.FormatDate, av)
+		if err != nil {
+			return edbInfoId, err
+		}
+
+		timestamp := currentDate.UnixNano() / 1e6
+		timestampStr := fmt.Sprintf("%d", timestamp)
+		valStr := utils.SubFloatToString(val, 4)
+		addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
+		isAdd = true
+	}
+
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}

+ 256 - 0
models/data_manage/edb_info_calculate_tcz.go

@@ -0,0 +1,256 @@
+package data_manage
+
+import (
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// 同差值
+func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("err:", err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	fmt.Println("req.EdbInfoId:", req.EdbInfoId)
+	if req.EdbInfoId <= 0 {
+		edbInfo := new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TCZ
+		edbInfo.SourceName = "同差值"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			return edbInfoId, tmpErr
+		}
+		edbInfoId = int(newEdbInfoId)
+
+		//calculateItem := new(EdbInfoCalculateTcz)
+		//calculateItem.CreateTime = time.Now()
+		//calculateItem.ModifyTime = time.Now()
+		//calculateItem.Sort = 1
+		//calculateItem.EdbCode = edbCode
+		//calculateItem.EdbInfoId = edbInfoId
+		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
+		//calculateItem.FromEdbName = fromEdbInfo.EdbName
+		//calculateItem.FromSource = fromEdbInfo.Source
+		//calculateItem.FromSourceName = fromEdbInfo.SourceName
+		//
+		//_, err = to.Insert(calculateItem)
+		//if err != nil {
+		//	return edbInfoId, err
+		//}
+
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfoId = req.EdbInfoId
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TCZ)
+		fmt.Println("dataTableName:", dataTableName)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+
+	//计算数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	if req.EdbInfoId <= 0 {
+		pars = append(pars, req.FromEdbInfoId)
+	} else {
+		pars = append(pars, fromEdbInfo.EdbInfoId)
+	}
+
+	fmt.Println("EdbInfoId:", req.FromEdbInfoId)
+	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return edbInfoId, err
+	}
+	var dateArr []string
+	dataMap := make(map[string]*EdbInfoSearchData)
+	for _, v := range dataList {
+		dateArr = append(dateArr, v.DataTime)
+		dataMap[v.DataTime] = v
+	}
+	fmt.Println("Frequency:", fromEdbInfo.Frequency)
+	addSql := ` INSERT INTO edb_data_calculate_tcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	var isAdd bool
+	existMap := make(map[string]string)
+	for _, av := range dateArr {
+		//fmt.Println("dateArr:", ak, av)
+		currentItem := dataMap[av]
+		if currentItem != nil {
+			//当前日期
+			currentDate, err := time.Parse(utils.FormatDate, av)
+			if err != nil {
+				return edbInfoId, err
+			}
+			//上一年的日期
+			preDate := currentDate.AddDate(-1, 0, 0)
+			preDateStr := preDate.Format(utils.FormatDate)
+			if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
+				//dataTime, _ := time.Parse(utils.FormatDate, date)
+				if _, ok := existMap[edbCode+av]; !ok {
+					timestamp := currentDate.UnixNano() / 1e6
+					timestampStr := fmt.Sprintf("%d", timestamp)
+
+					val := TczSub(currentItem.Value, findItem.Value)
+					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+					isAdd = true
+				}
+				existMap[edbCode+av] = av
+			} else {
+				if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
+					nextDateDay := preDate
+					preDateDay := preDate
+					for i := 0; i <= 35; i++ {
+						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
+						if findItem, ok := dataMap[nextDateDayStr]; ok { //下一年同期->下一个月找到
+							if _, ok := existMap[edbCode+av]; !ok {
+								timestamp := currentDate.UnixNano() / 1e6
+								timestampStr := fmt.Sprintf("%d", timestamp)
+								val := TczSub(currentItem.Value, findItem.Value)
+
+								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+								isAdd = true
+							}
+							existMap[edbCode+av] = av
+							break
+						} else {
+							preDateDayStr := preDateDay.Format(utils.FormatDate)
+							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
+								if _, ok := existMap[edbCode+av]; !ok {
+									timestamp := currentDate.UnixNano() / 1e6
+									timestampStr := fmt.Sprintf("%d", timestamp)
+									val := TczSub(currentItem.Value, findItem.Value)
+
+									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+									isAdd = true
+								}
+								existMap[edbCode+av] = av
+								break
+							}
+						}
+						nextDateDay = nextDateDay.AddDate(0, 0, 1)
+						preDateDay = preDateDay.AddDate(0, 0, -1)
+					}
+				} else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
+					if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
+						if _, ok := existMap[edbCode+av]; !ok {
+							timestamp := currentDate.UnixNano() / 1e6
+							timestampStr := fmt.Sprintf("%d", timestamp)
+							val := TczSub(currentItem.Value, findItem.Value)
+							addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+							isAdd = true
+						}
+						existMap[edbCode+av] = av
+						break
+					}
+				} else {
+					nextDateDay := preDate
+					preDateDay := preDate
+					for i := 0; i < 35; i++ {
+						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
+						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
+							if _, ok := existMap[edbCode+av]; !ok {
+								timestamp := currentDate.UnixNano() / 1e6
+								timestampStr := fmt.Sprintf("%d", timestamp)
+								val := TczSub(currentItem.Value, findItem.Value)
+
+								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+								isAdd = true
+							}
+							existMap[edbCode+av] = av
+							break
+						} else {
+							preDateDayStr := preDateDay.Format(utils.FormatDate)
+							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
+								if _, ok := existMap[edbCode+av]; !ok {
+									timestamp := currentDate.UnixNano() / 1e6
+									timestampStr := fmt.Sprintf("%d", timestamp)
+									val := TczSub(currentItem.Value, findItem.Value)
+
+									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+									isAdd = true
+								}
+								existMap[edbCode+av] = av
+								break
+							} else {
+
+							}
+						}
+						nextDateDay = nextDateDay.AddDate(0, 0, 1)
+						preDateDay = preDateDay.AddDate(0, 0, -1)
+					}
+				}
+			}
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return edbInfoId, err
+		}
+	}
+	return
+}
+
+func TczSub(a, b float64) string {
+	af := decimal.NewFromFloat(float64(a))
+	fmt.Println(af)
+	bf := decimal.NewFromFloat(float64(b))
+	val, _ := af.Sub(bf).Float64()
+	valStr := utils.SubFloatToString(val, 4)
+	return valStr
+}

+ 286 - 0
models/data_manage/edb_info_calculate_zjpj.go

@@ -0,0 +1,286 @@
+package data_manage
+
+import (
+	"errors"
+	"eta/eta_mobile/utils"
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// EditCalculateZjpj 编辑直接拼接数据
+func EditCalculateZjpj(req *EdbInfoCalculateBatchEditReq, nowEdbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (edbInfoId int, err error) {
+	edbInfoId = req.EdbInfoId
+	o := orm.NewOrmUsingDB("data")
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	//修改指标信息
+	sql := ` UPDATE  edb_info SET
+			  edb_name =?,
+			  edb_name_source=?,
+			  frequency = ?,
+			  unit = ?,
+			  classify_id = ?, 
+			  calculate_formula=?,
+			  modify_time = NOW()
+			WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	var existCondition string
+	var existPars []interface{}
+	existCondition += " AND edb_info_id=? "
+	existPars = append(existPars, edbInfoId)
+
+	//查询出所有的关联指标
+	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
+	if err != nil {
+		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
+		return
+	}
+
+	var existItemA, existItemB *EdbInfoCalculateMapping
+	for _, existItem := range existList {
+		if existItem.FromTag == "A" {
+			existItemA = existItem
+		} else if existItem.FromTag == "B" {
+			existItemB = existItem
+		}
+	}
+
+	addDataList := make([]*EdbDataCalculateZjpj, 0)
+	firstDataList := make([]*EdbInfoSearchData, 0)
+	secondDataList := make([]*EdbInfoSearchData, 0)
+
+	//如果 之前的拼接日期 与 现在的拼接日期 不一致的话,需要做以下处理
+	nowFormulaDate, _ := time.ParseInLocation(utils.FormatDate, nowEdbInfo.CalculateFormula, time.Local)
+	reqFormulaDate, _ := time.ParseInLocation(utils.FormatDate, req.Formula, time.Local)
+
+	//如果前后选择的日期不一致,那么需要删除一部分数据
+	if nowEdbInfo.CalculateFormula != req.Formula {
+		var startDate, endDate time.Time
+		//如果当前选择的日期 小于 之前选择的日期
+		if reqFormulaDate.Before(nowFormulaDate) {
+			startDate = reqFormulaDate
+			endDate = nowFormulaDate
+		} else { //如果当前选择的日期 大于 之前选择的日期
+			startDate = nowFormulaDate
+			endDate = reqFormulaDate
+		}
+		//删除 之前日期 与 当前日期 之间的指标数据
+		sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time >= ? and data_time < ?`
+		_, err = to.Raw(sql, edbInfoId, startDate, endDate).Exec()
+		if err != nil {
+			err = errors.New("删除 之前日期 与 当前日期 之间的指标数据失败,Err:" + err.Error())
+			return
+		}
+	}
+	//第一个指标数据
+	{
+		var condition string
+		var pars []interface{}
+		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
+			//删除之前的A指标关联关系
+			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+			_, err = to.Raw(sql, edbInfoId, existItemA.FromEdbInfoId).Exec()
+			if err != nil {
+				err = errors.New("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
+				return
+			}
+
+			//删除之前所有的A指标数据
+			sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time < ?`
+			_, err = to.Raw(sql, edbInfoId, req.Formula).Exec()
+			if err != nil {
+				err = errors.New("删除拼接日期之前的数据失败,Err:" + err.Error())
+				return
+			}
+
+			//获取第一个指标的数据列表
+			condition += " AND data_time < ? AND edb_info_id=? "
+			pars = append(pars, req.Formula, firstEdbInfo.EdbInfoId)
+
+			tmpFirstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
+			if tmpErr != nil {
+				return edbInfoId, tmpErr
+			}
+			firstDataList = tmpFirstDataList
+
+			//添加新的指标关系
+			{
+				calculateMappingItem := new(EdbInfoCalculateMapping)
+				calculateMappingItem.CreateTime = time.Now()
+				calculateMappingItem.ModifyTime = time.Now()
+				calculateMappingItem.Sort = 1
+				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
+				calculateMappingItem.EdbInfoId = edbInfoId
+				calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
+				calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
+				calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
+				calculateMappingItem.FromSource = firstEdbInfo.Source
+				calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
+				calculateMappingItem.FromTag = "A"
+				calculateMappingItem.Source = nowEdbInfo.Source
+				calculateMappingItem.SourceName = nowEdbInfo.SourceName
+				_, err = to.Insert(calculateMappingItem)
+				if err != nil {
+					return
+				}
+			}
+		} else {
+			if req.Formula != nowEdbInfo.CalculateFormula {
+				//获取第一个指标的数据列表
+				condition += " AND data_time >= ?  AND data_time < ? AND edb_info_id=? "
+				pars = append(pars, nowFormulaDate, reqFormulaDate, firstEdbInfo.EdbInfoId)
+
+				tmpFirstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
+				if tmpErr != nil {
+					return edbInfoId, tmpErr
+				}
+				firstDataList = tmpFirstDataList
+			}
+		}
+
+		//待插入数据
+		for _, v := range firstDataList {
+			//时间戳
+			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
+			timestamp := currentDate.UnixNano() / 1e6
+
+			edbDataZjpj := &EdbDataCalculateZjpj{
+				EdbInfoId:     edbInfoId,
+				EdbCode:       nowEdbInfo.EdbCode,
+				DataTime:      v.DataTime,
+				Value:         v.Value,
+				Status:        1,
+				CreateTime:    time.Now(),
+				ModifyTime:    time.Now(),
+				DataTimestamp: timestamp,
+			}
+			addDataList = append(addDataList, edbDataZjpj)
+		}
+	}
+
+	//第二个指标数据
+	{
+		var condition string
+		var pars []interface{}
+
+		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
+			//删除之前的B指标关联关系
+			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+			_, err = to.Raw(sql, edbInfoId, existItemB.FromEdbInfoId).Exec()
+			if err != nil {
+				err = errors.New("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
+				return
+			}
+
+			//删除历史拼接日期之前所有的B指标数据
+			sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time >= ?`
+			_, err = to.Raw(sql, edbInfoId, nowEdbInfo.CalculateFormula).Exec()
+			if err != nil {
+				err = errors.New("删除历史拼接日期之后的数据失败,Err:" + err.Error())
+				return
+			}
+
+			//第二个指标的数据列表
+			condition = " AND data_time >= ?  AND edb_info_id=? "
+			pars = append(pars, reqFormulaDate, secondEdbInfo.EdbInfoId)
+			tmpSecondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
+			if tmpErr != nil {
+				return edbInfoId, tmpErr
+			}
+			secondDataList = tmpSecondDataList
+
+			//添加新的指标关系
+			{
+				calculateMappingItem := new(EdbInfoCalculateMapping)
+				calculateMappingItem.CreateTime = time.Now()
+				calculateMappingItem.ModifyTime = time.Now()
+				calculateMappingItem.Sort = 1
+				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
+				calculateMappingItem.EdbInfoId = edbInfoId
+				calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
+				calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
+				calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
+				calculateMappingItem.FromSource = secondEdbInfo.Source
+				calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
+				calculateMappingItem.FromTag = "B"
+				calculateMappingItem.Source = nowEdbInfo.Source
+				calculateMappingItem.SourceName = nowEdbInfo.SourceName
+				_, err = to.Insert(calculateMappingItem)
+				if err != nil {
+					return
+				}
+			}
+		} else {
+			if req.Formula != nowEdbInfo.CalculateFormula {
+				//获取第二个指标的数据列表
+				condition += " AND data_time >= ?  AND data_time < ? AND edb_info_id=? "
+				pars = append(pars, reqFormulaDate, nowFormulaDate, secondEdbInfo.EdbInfoId)
+
+				tmpSecondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
+				if tmpErr != nil {
+					return edbInfoId, tmpErr
+				}
+				secondDataList = tmpSecondDataList
+			}
+		}
+
+		//待插入数据
+		for _, v := range secondDataList {
+			//时间戳
+			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
+			timestamp := currentDate.UnixNano() / 1e6
+
+			edbDataZjpj := &EdbDataCalculateZjpj{
+				EdbInfoId:     edbInfoId,
+				EdbCode:       nowEdbInfo.EdbCode,
+				DataTime:      v.DataTime,
+				Value:         v.Value,
+				Status:        1,
+				CreateTime:    time.Now(),
+				ModifyTime:    time.Now(),
+				DataTimestamp: timestamp,
+			}
+			addDataList = append(addDataList, edbDataZjpj)
+		}
+	}
+
+	//数据入库
+	tmpAddDataList := make([]*EdbDataCalculateZjpj, 0)
+	for _, v := range addDataList {
+		tmpAddDataList = append(tmpAddDataList, v)
+
+		if len(tmpAddDataList) >= 200 {
+			_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+			if tmpErr != nil {
+				err = tmpErr
+				return
+			}
+			//重新初始化需要加入的数据切片
+			tmpAddDataList = make([]*EdbDataCalculateZjpj, 0)
+		}
+	}
+	//最后如果还有需要新增的数据,那么就统一入库
+	if len(tmpAddDataList) > 0 {
+		_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+		if tmpErr != nil {
+			err = tmpErr
+			return
+		}
+	}
+
+	return
+}

+ 10 - 0
models/data_manage/predict_edb_conf.go

@@ -187,3 +187,13 @@ func GetPredictEdbConfListById(edbInfoId int) (items []*PredictEdbConf, err erro
 	_, err = o.Raw(sql, edbInfoId).QueryRows(&items)
 	return
 }
+
+// GetGroupPredictEdbBySourceEdbInfoId 根据来源指标id获取配置
+func GetGroupPredictEdbBySourceEdbInfoId(sourceEdbInfoId int) (items []*EdbInfo, err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` SELECT a.* FROM edb_info AS a 
+     JOIN predict_edb_conf AS b  on a.edb_info_id = b.predict_edb_info_id
+          WHERE b.source_edb_info_id=? group by a.edb_info_id`
+	_, err = o.Raw(sql, sourceEdbInfoId).QueryRows(&items)
+	return
+}

+ 4 - 18
models/db.go

@@ -75,9 +75,6 @@ func init() {
 
 	initChart()
 
-	// 上海指标服务 数据表
-	initShEdbData()
-
 	// 指标服务 数据表
 	initEdbData()
 
@@ -112,18 +109,16 @@ func initSystem() {
 func initReport() {
 	orm.RegisterModel(
 		new(Report),
-		new(ResearchReport),                      //日报、周报信息
 		new(ChartPermissionSearchKeyWordMapping), //报告分类权限表
 		new(ReportChapter),                       // 报告章节表
 		new(ReportChapterTicker),                 // 晨报章节ticker
 		new(ReportChapterTypePermission),         // 晨周报章节类型权限表
 		new(YbPcSuncode),
 		new(YbSuncodePars),
-		new(ReportAuthor),                  //报告作者
-		new(ClassifyMenu),                  // 报告分类-子目录表
-		new(ClassifyMenuRelation),          // 报告分类-子目录关联表
-		new(ChartPermissionChapterMapping), // 权限mapping表
-		new(ReportChapterType),             // 报告章节类型表
+		new(ReportAuthor),         //报告作者
+		new(ClassifyMenu),         // 报告分类-子目录表
+		new(ClassifyMenuRelation), // 报告分类-子目录关联表
+		new(ReportChapterType),    // 报告章节类型表
 	)
 }
 
@@ -142,15 +137,6 @@ func initChart() {
 	)
 }
 
-// initShEdbData 上海服务器指标 数据表
-func initShEdbData() {
-	orm.RegisterModel(
-		new(Edbdata),
-		new(EdbdataDeleteRecord),
-		new(Edbinfo), //edb库的edbinfo表
-	)
-}
-
 // initEdbData 指标服务 数据表
 func initEdbData() {
 	orm.RegisterModel(

+ 0 - 275
models/report_chapter_type.go

@@ -3,7 +3,6 @@ package models
 import (
 	"eta/eta_mobile/utils"
 	"github.com/beego/beego/v2/client/orm"
-	"github.com/rdlucklib/rdluck_tools/paging"
 	"time"
 )
 
@@ -32,53 +31,6 @@ type ReportChapterType struct {
 	YbBottomIcon           string    `description:"研报小程序详情底部icon"`
 }
 
-func (item *ReportChapterType) Create() (err error) {
-	o := orm.NewOrm()
-	id, err := o.Insert(item)
-	if err != nil {
-		return
-	}
-	item.ReportChapterTypeId = int(id)
-	return
-}
-
-func (item *ReportChapterType) Update(cols []string) (err error) {
-	o := orm.NewOrm()
-	_, err = o.Update(item, cols...)
-	return
-}
-
-// DeleteReportChapterType 删除章节类型及相关权限
-func DeleteReportChapterType(typeId int, reportType string) (err error) {
-	o := orm.NewOrm()
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	// 删除章节类型
-	sql := `DELETE FROM report_chapter_type WHERE report_chapter_type_id = ? LIMIT 1`
-	_, err = to.Raw(sql, typeId).Exec()
-
-	// 删除章节类型权限
-	sql = `DELETE FROM report_chapter_type_permission WHERE report_chapter_type_id = ?`
-	_, err = to.Raw(sql, typeId).Exec()
-
-	// 周报-删除实际权限
-	if reportType == utils.REPORT_TYPE_WEEK {
-		sql = `DELETE FROM chart_permission_chapter_mapping WHERE report_chapter_type_id = ? AND research_type = ?`
-		_, err = to.Raw(sql, typeId, reportType).Exec()
-	}
-	return
-}
-
 // GetReportChapterTypeById 获取章节类型
 func GetReportChapterTypeById(reportChapterTypeId int) (item *ReportChapterType, err error) {
 	o := orm.NewOrm()
@@ -111,15 +63,6 @@ func GetAllReportChapterTypeListByResearchType(researchType string) (list []*Rep
 	return
 }
 
-// GetAllReportChapterTypeList 通过传入的条件获取所有的章节类型列表
-func GetAllReportChapterTypeList(condition string, pars []interface{}) (list []*ReportChapterType, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM report_chapter_type WHERE 1=1 `
-	sql += condition
-	_, err = o.Raw(sql, pars).QueryRows(&list)
-	return
-}
-
 // GetEnableReportChapterTypeList 获取未暂停的章节类型列表
 func GetEnableReportChapterTypeList(researchType string) (list []*ReportChapterType, err error) {
 	o := orm.NewOrm()
@@ -142,133 +85,6 @@ func GetEnableReportChapterTypeList(researchType string) (list []*ReportChapterT
 	return
 }
 
-// 晨报周报暂停时间
-type DayWeekReportPauseTime struct {
-	ResearchType   string `description:"报告类型 day; week;"`
-	PauseStartTime string `description:"暂停开始时间"`
-	PauseEndTime   string `description:"暂停结束时间"`
-}
-
-// GetDayWeekReportPauseTimeList 获取晨报周报暂停时间
-func GetDayWeekReportPauseTimeList() (list []*DayWeekReportPauseTime, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT research_type, MAX(a.pause_start_time) AS pause_start_time, MAX(a.pause_end_time) AS pause_end_time FROM report_chapter_type AS a WHERE a.is_set = 1 GROUP BY a.research_type`
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-// SetDayWeekReportUpdateRuleReq 设置章节类型的暂停时间请求体
-type SetDayWeekReportUpdateRuleReq struct {
-	ResearchType string                    `description:"报告类型 day; week;"`
-	List         []DayWeekReportUpdateRule `description:"暂停规则"`
-}
-
-type DayWeekReportUpdateRule struct {
-	ReportChapterTypeId int    `description:"章节类型ID"`
-	PauseStartTime      string `description:"暂停开始时间"`
-	PauseEndTime        string `description:"暂停结束时间"`
-}
-
-// SetDayWeekReportEnableUpdateRuleReq 设置章节类型的永久暂停请求体
-type SetDayWeekReportEnableUpdateRuleReq struct {
-	DayReportChapterTypeId  string `description:"章节类型ID 英文逗号拼接"`
-	WeekReportChapterTypeId string `description:"章节类型ID 英文逗号拼接"`
-}
-
-// ResetDayWeekReportUpdateRule 重置章节类型的暂停时间
-func ResetDayWeekReportUpdateRule(researchType string) (err error) {
-	o := orm.NewOrm()
-	sql := ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 WHERE research_type = ?`
-	_, err = o.Raw(sql, researchType).Exec()
-	return
-}
-
-// SetDayWeekReportUpdateRule 设置章节类型的暂停时间
-func SetDayWeekReportUpdateRule(researchType string, list []DayWeekReportUpdateRule) (err error) {
-	o := orm.NewOrm()
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	// 先将所有品种的状态变更为启用
-	sql := ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 WHERE research_type = ?`
-	_, err = to.Raw(sql, researchType).Exec()
-	if err != nil {
-		return
-	}
-	for _, v := range list {
-		// 时间异常的话,给过滤
-		if v.PauseStartTime == `` || v.PauseEndTime == `` {
-			continue
-		}
-		tmpSql := ` UPDATE report_chapter_type SET pause_start_time = ?, pause_end_time = ?, is_set = 1 WHERE research_type = ? AND report_chapter_type_id = ? `
-		_, err = to.Raw(tmpSql, v.PauseStartTime, v.PauseEndTime, researchType, v.ReportChapterTypeId).Exec()
-		if err != nil {
-			return
-		}
-	}
-
-	return
-}
-
-// SetDayWeekReportEnableUpdateRule 设置章节类型的禁用状态
-func SetDayWeekReportEnableUpdateRule(dayReportChapterTypeIdList, weekReportChapterTypeIdList []string) (err error) {
-	o := orm.NewOrm()
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-	{
-		researchType := `day`
-		// 先将所有品种的状态变更为启用
-		sql := ` UPDATE report_chapter_type SET enabled = 1 WHERE research_type = ?`
-		_, err = to.Raw(sql, researchType).Exec()
-		if err != nil {
-			return
-		}
-
-		// 然后将需要的品种的状态变更为禁用
-		num := len(dayReportChapterTypeIdList)
-		if num > 0 {
-			sql = ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 , enabled = 0 WHERE research_type = ? AND report_chapter_type_id IN (` + utils.GetOrmInReplace(num) + `) `
-			_, err = to.Raw(sql, researchType, dayReportChapterTypeIdList).Exec()
-		}
-	}
-
-	{
-		researchType := `week`
-		// 先将所有品种的状态变更为启用
-		sql := ` UPDATE report_chapter_type SET enabled = 1 WHERE research_type = ?`
-		_, err = to.Raw(sql, researchType).Exec()
-		if err != nil {
-			return
-		}
-
-		// 然后将需要的品种的状态变更为禁用
-		num := len(weekReportChapterTypeIdList)
-		if num > 0 {
-			sql = ` UPDATE report_chapter_type SET pause_start_time = null, pause_end_time = null, is_set = 0 , enabled = 0 WHERE research_type = ? AND report_chapter_type_id IN (` + utils.GetOrmInReplace(num) + `) `
-			_, err = to.Raw(sql, researchType, weekReportChapterTypeIdList).Exec()
-		}
-	}
-	return
-}
-
 // StopUpdateReportChapterTypeResp 停止更新的报告分类列表
 type StopUpdateReportChapterTypeResp struct {
 	StopDay     []*ReportChapterType `description:"暂时停更晨报"`
@@ -292,94 +108,3 @@ func GetDisableUpdateReportChapterTypeListByResearchType() (list []*ReportChapte
 	_, err = o.Raw(sql).QueryRows(&list)
 	return
 }
-
-// UpdateReportChapterTypeResp 停止更新的报告分类列表
-type UpdateReportChapterTypeResp struct {
-	Day  []*ReportChapterType `description:"所有晨报品种"`
-	Week []*ReportChapterType `description:"所有周报品种"`
-}
-
-type ReportChapterTypePageListResp struct {
-	List   []*ReportChapterTypeListItem
-	Paging *paging.PagingItem `description:"分页数据"`
-}
-
-// GetReportChapterTypeCount 获取章节类型总数
-func GetReportChapterTypeCount(condition string, pars []interface{}) (count int, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT COUNT(1) FROM report_chapter_type WHERE 1 = 1 `
-	sql += condition
-	err = o.Raw(sql, pars).QueryRow(&count)
-	return
-}
-
-// GetReportChapterTypeList 获取章节类型列表
-func GetReportChapterTypePageList(condition string, pars []interface{}, startSize, pageSize int) (list []*ReportChapterType, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM report_chapter_type WHERE 1 = 1 `
-	sql += condition
-	sql += ` ORDER BY sort ASC, created_time DESC`
-	sql += ` LIMIT ?,?`
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
-	return
-}
-
-// ReportChapterTypeListItem 章节类型列表信息
-type ReportChapterTypeListItem struct {
-	ReportChapterTypeId   int    `description:"报告章节类型id"`
-	ReportChapterTypeName string `description:"报告章节类型名称"`
-	Sort                  int    `description:"排序字段"`
-	CreatedTime           string `description:"创建时间"`
-	ResearchType          string `description:"研报类型"`
-	SelectedImage         string `description:"选中时的图片"`
-	UnselectedImage       string `description:"没选中时的图片"`
-	WordsImage            string `description:"带字的icon"`
-	EditImgUrl            string `description:"管理后台编辑时选用的图"`
-	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`
-}
-
-// ReportChapterTypeAddReq 新增章节类型请求体
-type ReportChapterTypeAddReq struct {
-	ReportChapterTypeName string `description:"报告章节类型名称"`
-	Sort                  int    `description:"排序字段"`
-	ResearchType          string `description:"研报类型"`
-	SelectedImage         string `description:"选中时的icon"`
-	UnselectedImage       string `description:"未选中时的icon"`
-	WordsImage            string `description:"带字的icon"`
-	EditImgUrl            string `description:"管理后台编辑时选用的图"`
-	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`
-}
-
-// ReportChapterTypeEditReq 编辑章节类型请求体
-type ReportChapterTypeEditReq struct {
-	ReportChapterTypeId   int    `description:"报告章节类型id"`
-	ReportChapterTypeName string `description:"报告章节类型名称"`
-	Sort                  int    `description:"排序字段"`
-	ResearchType          string `description:"研报类型"`
-	SelectedImage         string `description:"选中时的icon"`
-	UnselectedImage       string `description:"未选中时的icon"`
-	WordsImage            string `description:"带字的icon"`
-	EditImgUrl            string `description:"管理后台编辑时选用的图"`
-	IsShow                int    `description:"显示隐藏: 1-显示; 0-隐藏"`
-}
-
-// ReportChapterTypeDelReq 删除章节类型请求体
-type ReportChapterTypeDelReq struct {
-	ReportChapterTypeId int `description:"报告章节类型id"`
-}
-
-// ReportChapterTypeAuthSettingReq 章节类型权限配置请求体
-type ReportChapterTypeAuthSettingReq struct {
-	ReportChapterTypeId   int   `description:"章节类型ID"`
-	ChartPermissionIdList []int `description:"权限id数组"`
-}
-
-// GetReportChapterTypeByCondition 获取章节类型
-func GetReportChapterTypeByCondition(condition string, pars []interface{}) (item *ReportChapterType, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM report_chapter_type WHERE 1 = 1 `
-	sql += condition
-	sql += ` LIMIT 1`
-	err = o.Raw(sql, pars).QueryRow(&item)
-	return
-}

+ 0 - 58
models/report_chapter_type_permission.go

@@ -1,7 +1,6 @@
 package models
 
 import (
-	"eta/eta_mobile/utils"
 	"github.com/beego/beego/v2/client/orm"
 	"time"
 )
@@ -16,13 +15,6 @@ type ReportChapterTypePermission struct {
 	CreatedTime           time.Time `description:"创建时间"`
 }
 
-// AddChapterTypePermission 新增章节类型权限
-func AddChapterTypePermission(item *ReportChapterTypePermission) (lastId int64, err error) {
-	o := orm.NewOrm()
-	lastId, err = o.Insert(item)
-	return
-}
-
 // GetChapterTypePermissionByTypeIdAndResearchType 根据章节类型ID及研报类型获取章节类型权限列表
 func GetChapterTypePermissionByTypeIdAndResearchType(typeId int, researchType string) (list []*ReportChapterTypePermission, err error) {
 	o := orm.NewOrm()
@@ -30,53 +22,3 @@ func GetChapterTypePermissionByTypeIdAndResearchType(typeId int, researchType st
 	_, err = o.Raw(sql, typeId, researchType).QueryRows(&list)
 	return
 }
-
-// SetReportChapterTypePermission 设置报告章节类型权限
-func SetReportChapterTypePermission(chapterTypeId int, researchType string, newPermissions []*ReportChapterTypePermission, newWeekPermissions []*ChartPermissionChapterMapping) (err error) {
-	o := orm.NewOrm()
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	// 删除原章节类型权限
-	sql := `DELETE FROM report_chapter_type_permission WHERE report_chapter_type_id = ? AND research_type = ?`
-	_, err = to.Raw(sql, chapterTypeId, researchType).Exec()
-	if err != nil {
-		return
-	}
-
-	// 新增章节类型权限
-	if len(newPermissions) > 0 {
-		_, err = to.InsertMulti(len(newPermissions), newPermissions)
-		if err != nil {
-			return
-		}
-	}
-
-	// 周报章节调整chart_permission_chapter_mapping表
-	if researchType == utils.REPORT_TYPE_WEEK {
-		// 删除原权限
-		sql = `DELETE FROM chart_permission_chapter_mapping WHERE report_chapter_type_id = ? AND research_type = ?`
-		_, err = to.Raw(sql, chapterTypeId, researchType).Exec()
-		if err != nil {
-			return
-		}
-
-		// 新增权限
-		if len(newWeekPermissions) > 0 {
-			_, err = to.InsertMulti(len(newWeekPermissions), newWeekPermissions)
-			if err != nil {
-				return
-			}
-		}
-	}
-	return
-}

+ 0 - 302
models/research_report.go

@@ -1,302 +0,0 @@
-package models
-
-import (
-	"eta/eta_mobile/utils"
-	"fmt"
-	"github.com/beego/beego/v2/client/orm"
-	"strconv"
-	"time"
-)
-
-// ResearchReport 研究报告表(晨报、周报等)结构体
-type ResearchReport struct {
-	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`
-	ResearchReportName  string    `description:"研究报告名称"`
-	ResearchReportTitle string    `description:"研究报告标题"`
-	ResearchReportImg   string    `description:"报告缩略图URL"`
-	ResearchReportDate  time.Time `description:"报告日期"`
-	Type                string    `description:"报告类型,枚举值:day 晨报  week 周报 twoweek双周报 month 月报;默认:day"`
-	Author              string    `description:"作者"`
-	ReportVariety       string    `description:"研究报告的品种,双周报和月报有标识"`
-	IsHasMenu           int8      `description:"报告是否含有目录"`
-	IsSendedMsg         int8      `description:"是否发送过模板消息"`
-	Periods             int       `description:"期数"`
-	Status              string    `description:"状态,draft:草稿,"`
-	Enabled             int8      `description:"报告状态"`
-	CreatedTime         string    `description:"创建时间"`
-	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
-	Viewers             int       `description:"H5观看用户数"`
-}
-
-// GetResearchReportListByIds 根据报告id集合获取报告数据列表
-func GetResearchReportListByIds(researchReportIds string) (list []*ResearchReport, err error) {
-	if researchReportIds == "" {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `select * from research_report where research_report_id in (` + researchReportIds + `)`
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-// Update 更新数据
-func (researchReport *ResearchReport) Update(updateCols []string) (err error) {
-	o := orm.NewOrm()
-	_, err = o.Update(researchReport, updateCols...)
-	return
-}
-
-type ResearchReportList struct {
-	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`
-	ResearchReportName  string    `description:"研究报告名称"`
-	ResearchReportTitle string    `description:"研究报告标题"`
-	ResearchReportImg   string    `description:"报告缩略图URL"`
-	ResearchReportDate  time.Time `description:"报告日期"`
-	Type                string    `description:"报告类型,枚举值:day 晨报  week 周报 twoweek双周报 month 月报;默认:day"`
-	Author              string    `description:"作者"`
-	ReportVariety       string    `description:"研究报告的品种,双周报和月报有标识"`
-	IsHasMenu           int8      `description:"报告是否含有目录"`
-	IsSendedMsg         int8      `description:"是否发送过模板消息"`
-	Periods             int       `description:"期数"`
-	Status              string    `description:"状态,draft:草稿,"`
-	Enabled             int8      `description:"报告状态"`
-	CreatedTime         string    `description:"创建时间"`
-	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
-	Viewers             int       `description:"H5观看用户数"`
-	LinkUrl             string    `description:"报告阅读地址"`
-}
-
-// GetResearchReportList 获取报告列表
-func GetResearchReportList(condition string, pars []interface{}, startSize, pageSize int) (total int, list []*ResearchReportList, err error) {
-	o := orm.NewOrm()
-
-	sql := `select * from research_report where enabled = 1 `
-	sql += condition
-	sql += ` order by research_report_date desc,created_time desc `
-
-	totalSql := `select count(1) total from (` + sql + `) z `
-	err = o.Raw(totalSql, pars).QueryRow(&total)
-	if err != nil {
-		return
-	}
-	sql += ` LIMIT ?,? `
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
-
-	return
-}
-
-// 获取今年报告
-func GetMigrateReportList() (list []*ResearchReport, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT
-				*
-			FROM
-				research_report AS a
-			WHERE
-				a.enabled = 1
-			AND a.status = "report"
-			AND a.research_report_date >= "2022-01-01"
-			ORDER BY a.research_report_date ASC `
-	_, err = o.Raw(sql).QueryRows(&list)
-
-	return
-}
-
-// ResearchReport 研究报告表(晨报、周报等)结构体
-type ResearchReportType struct {
-	ResearchReportTypeId    int       `orm:"column(research_report_type_id);pk" description:"报告章节ID"`
-	ResearchReportId        int       `description:"报告ID"`
-	TypeId                  int       `description:"分类ID"`
-	Edit                    int       `description:"是否编辑过"`
-	Trend                   string    `description:"趋势观点"`
-	ResearchReportTypeTitle string    `description:"报告标题"`
-	CreatedTime             string    `description:"创建时间"`
-	LastUpdatedTime         time.Time `description:"最近一次更新时间"`
-}
-
-type ResearchReportTypeContent struct {
-	ResearchReportTypeContentId int       `orm:"column(research_report_type_content_id);pk" description:"章节内容ID"`
-	ResearchReportTypeId        int       `description:"报告章节ID"`
-	Sort                        int       `description:"排序"`
-	ContentType                 string    `description:"内容分类类型"`
-	Content                     string    `description:"内容"`
-	ImgUrl                      string    `description:"图片路径"`
-	CreatedTime                 time.Time `description:"创建时间"`
-	LastUpdatedTime             time.Time `description:"最近一次更新时间"`
-}
-
-type ResearchReportTypeTicker struct {
-	ResearchReportTypeTickerId int       `orm:"column(research_report_type_ticker_id);pk" description:"章节tickerID"`
-	ResearchReportTypeId       int       `description:"报告章节ID"`
-	Sort                       int       `description:"排序"`
-	Ticker                     string    `description:"指标的ticker"`
-	CreatedTime                time.Time `description:"创建时间"`
-	LastUpdatedTime            time.Time `description:"最近一次更新时间"`
-}
-
-func GetResearchReportTypeList(researchReportId int) (list []*ResearchReportType, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type WHERE research_report_id = ? ORDER BY created_time ASC `
-	_, err = o.Raw(sql, researchReportId).QueryRows(&list)
-	return
-}
-
-func GetResearchReportTypeListByReportIds(reportIds string) (list []*ResearchReportType, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type WHERE research_report_id IN (` + reportIds + `) ORDER BY created_time ASC,research_report_type_id ASC `
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-func GetResearchReportTypeContentList(researchReportTypeId int) (list []*ResearchReportTypeContent, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type_content WHERE research_report_type_id = ? ORDER BY sort ASC `
-	_, err = o.Raw(sql, researchReportTypeId).QueryRows(&list)
-	return
-}
-
-func GetResearchReportTypeContentListByReportTypeIds(reportTypeIds string) (list []*ResearchReportTypeContent, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type_content WHERE research_report_type_id IN (` + reportTypeIds + `) ORDER BY research_report_type_id ASC,sort ASC `
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-func GetResearchReportTypeTickerList(researchReportTypeId int) (list []*ResearchReportTypeTicker, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type_ticker WHERE research_report_type_id = ? ORDER BY sort ASC `
-	_, err = o.Raw(sql, researchReportTypeId).QueryRows(&list)
-	return
-}
-
-func GetResearchReportTypeTickerListByReportTypeIds(reportTypeIds string) (list []*ResearchReportTypeTicker, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM research_report_type_ticker WHERE research_report_type_id IN (` + reportTypeIds + `) ORDER BY research_report_type_id ASC,sort ASC `
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-type CreateDayWeekReport struct {
-	Report      *Report
-	ChapterList []*CreateDayWeekReportChapter
-}
-
-type CreateDayWeekReportChapter struct {
-	Chapter    *ReportChapter
-	TickerList []*ReportChapterTicker
-}
-
-// 新增迁移晨周报
-func CreateMigrateNewDayWeekReport(newDayWeekReport *CreateDayWeekReport) (newReportId int, err error) {
-	o := orm.NewOrmUsingDB("rddp")
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	// 新增报告
-	reportId, err := to.Insert(newDayWeekReport.Report)
-	if err != nil {
-		fmt.Println("InsertReportErr:" + err.Error())
-		return
-	}
-	// 新增章节
-	for _, chapter := range newDayWeekReport.ChapterList {
-		chapter.Chapter.ReportId = int(reportId)
-		lastChapterId, tmpErr := to.Insert(chapter.Chapter)
-		if tmpErr != nil {
-			err = tmpErr
-			return
-		}
-		// 新增晨报ticker
-		for _, ticker := range chapter.TickerList {
-			ticker.ReportChapterId = int(lastChapterId)
-			if _, tmpErr = to.Insert(ticker); tmpErr != nil {
-				err = tmpErr
-				return
-			}
-		}
-	}
-	// 修改报告code
-	reportCode := utils.MD5(strconv.Itoa(int(reportId)))
-	sql := `UPDATE report SET report_code = ? WHERE id = ? `
-	if _, err = to.Raw(sql, reportCode, reportId).Exec(); err != nil {
-		fmt.Println("UpdateReportCodeErr:" + err.Error())
-	}
-	newReportId = int(reportId)
-
-	return
-}
-
-// 新增迁移其他报告
-func CreateMigrateNewOtherReport(reportInfo *Report, mappingList []*ChartPermissionChapterMapping) (newReportId int, err error) {
-	o := orm.NewOrmUsingDB("rddp")
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	// 新增报告
-	reportId, err := to.Insert(reportInfo)
-	if err != nil {
-		fmt.Println("InsertReportErr:" + err.Error())
-		return
-	}
-	// 修改报告code
-	reportCode := utils.MD5(strconv.Itoa(int(reportId)))
-	sql := `UPDATE report SET report_code = ? WHERE id = ? `
-	if _, err = to.Raw(sql, reportCode, reportId).Exec(); err != nil {
-		fmt.Println("UpdateReportCodeErr:" + err.Error())
-		return
-	}
-
-	// 新增权限
-	newReportId = int(reportId)
-	if len(mappingList) > 0 {
-		r := orm.NewOrm()
-		for _, mapping := range mappingList {
-			sql := ` INSERT INTO chart_permission_chapter_mapping (chart_permission_id, report_chapter_type_id,research_type) VALUES(?,?,?) `
-			if _, err = r.Raw(sql, mapping.ChartPermissionId, newReportId, "rddp").Exec(); err != nil {
-				fmt.Println("InsertChartPermissionErr:" + err.Error())
-				return
-			}
-		}
-	}
-
-	return
-}
-
-type ChartPermissionChapterMapping struct {
-	Id                  int    `orm:"column(id);pk"`
-	ChartPermissionId   int    `description:"权限ID"`
-	ReportChapterTypeId int    `description:"report_chapter_type表主键id或research_report表主键id或tactic表主键id"`
-	ResearchType        string `description:"报告类型 week;two_week;tactic;month;other;rddp; "`
-}
-
-func GetChapterPermissionMappingByCondition(reportChapterTypeId int, researchType string) (list []*ChartPermissionChapterMapping, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM chart_permission_chapter_mapping WHERE report_chapter_type_id = ? AND research_type = ? `
-	_, err = o.Raw(sql, reportChapterTypeId, researchType).QueryRows(&list)
-	return
-}
-
-func GetChapterPermissionMappingByResearchReportIds(researchReportIds string) (list []*ChartPermissionChapterMapping, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM chart_permission_chapter_mapping WHERE report_chapter_type_id IN (` + researchReportIds + `) AND research_type != "rddp" ORDER BY report_chapter_type_id ASC `
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}

+ 0 - 376
models/system/sys_admin.go

@@ -1,9 +1,7 @@
 package system
 
 import (
-	"fmt"
 	"github.com/beego/beego/v2/client/orm"
-	"github.com/rdlucklib/rdluck_tools/paging"
 	"strings"
 	"time"
 )
@@ -42,87 +40,6 @@ type AdminItem struct {
 	EmployeeId              string `description:"员工工号(钉钉/每刻报销)"`
 }
 
-func GetSysuserList(condition string, pars []interface{}, startSize, pageSize int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	sql += `ORDER BY created_time DESC LIMIT ?,?`
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func GetSysuserListCount(condition string, pars []interface{}) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(1) AS count FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	err = o.Raw(sql, pars).QueryRow(&count)
-	return
-}
-
-type AdminRespItem struct {
-	AdminId                 int    `description:"系统用户id"`
-	AdminName               string `description:"系统用户名称"`
-	RealName                string `description:"系统用户姓名"`
-	Password                string
-	LastUpdatedPasswordTime string `json:"-"`
-	Enabled                 int    `description:"1:有效,0:禁用"`
-	Email                   string `description:"系统用户邮箱"`
-	LastLoginTime           string
-	CreatedTime             time.Time
-	LastUpdatedTime         string
-	Role                    string `description:"系统用户角色"`
-	Mobile                  string `description:"手机号"`
-	RoleType                int    `description:"角色类型:1需要录入指标,0:不需要"`
-	RoleId                  int    `description:"角色id"`
-	RoleName                string `description:"角色名称"`
-	RoleTypeCode            string `description:"角色编码"`
-	DepartmentId            int    `description:"部门id"`
-	DepartmentName          string `json:"-" description:"部门名称"`
-	parentId                int    `description:"父级id"`
-	GroupId                 int    `description:"分组id"`
-	GroupName               string `json:"-" description:"分组名称"`
-	Authority               int    `description:"管理权限,0:无,1:部门负责人,2:小组负责人,或者ficc销售主管,4:ficc销售组长"`
-	Position                string `description:"职位"`
-	DepartmentGroup         string `description:"部门分组"`
-	LabelVal                int    `description:"标签:1:超级管理员,2:管理员,3:部门经理,4:组长,5:ficc销售主管"`
-}
-
-type SysuserListResp struct {
-	List   []*AdminItem
-	Paging *paging.PagingItem `description:"分页数据"`
-}
-
-type SysuserAddReq struct {
-	AdminName    string `description:"系统用户名称"`
-	AdminAvatar  string `description:"用户头像"`
-	RealName     string `description:"系统用户姓名"`
-	Password     string `description:"密码"`
-	Mobile       string `description:"手机号"`
-	RoleId       int    `description:"角色id"`
-	DepartmentId int    `description:"部门id"`
-	GroupId      int    `description:"分组id"`
-	TeamId       int    `description:"小组id"`
-	//Authority    int    `description:"管理权限,0:无,1:部门负责人,2:小组负责人"`
-	Position         string `description:"职位"`
-	ResearchGroupIds string `description:"研究方向分组IDs"`
-	Province         string `description:"省"`
-	ProvinceCode     string `description:"省编码"`
-	City             string `description:"市"`
-	CityCode         string `description:"市编码"`
-	EmployeeId       string `description:"员工工号(钉钉/每刻报销)"`
-}
-
-func GetSysAdminCount(adminName string) (count int, err error) {
-	sql := `SELECT COUNT(1) AS count FROM admin WHERE admin_name=? `
-	o := orm.NewOrm()
-	err = o.Raw(sql, adminName).QueryRow(&count)
-	return
-}
-
 func GetSysAdminByName(adminName string) (item *Admin, err error) {
 	sql := `SELECT * FROM admin WHERE admin_name=? `
 	o := orm.NewOrm()
@@ -137,193 +54,6 @@ func GetSysAdminById(adminId int) (item *Admin, err error) {
 	return
 }
 
-func AddAdmin(item *Admin) (err error) {
-	o := orm.NewOrm()
-	adminId, err := o.Insert(item)
-	item.AdminId = int(adminId)
-	return
-}
-
-type SysuserEditReq struct {
-	AdminId      int    `description:"系统用户id"`
-	AdminName    string `description:"系统用户名称"`
-	AdminAvatar  string `description:"用户头像"`
-	RealName     string `description:"系统用户姓名"`
-	Password     string `description:"密码"`
-	Mobile       string `description:"手机号"`
-	RoleId       int    `description:"角色id"`
-	DepartmentId int    `description:"部门id"`
-	GroupId      int    `description:"分组id"`
-	TeamId       int    `description:"小组id"`
-	Enabled      int    `description:"1:有效,0:禁用"`
-	//Authority    int    `description:"管理权限,0:无,1:部门负责人,2:小组负责人"`
-	Position         string `description:"职位"`
-	ResearchGroupIds string `description:"研究方向分组IDs"`
-	Province         string `description:"省"`
-	ProvinceCode     string `description:"省编码"`
-	City             string `description:"市"`
-	CityCode         string `description:"市编码"`
-	EmployeeId       string `description:"员工工号(钉钉/每刻报销)"`
-}
-
-// 用户状态编辑
-type SysuserEditEnabledReq struct {
-	AdminId int `description:"系统用户id"`
-	Enabled int `description:"1:有效,0:禁用"`
-}
-
-func EditAdmin(item *Admin) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE admin
-			SET
-			  admin_name= ?,
-			  real_name = ?,
-			  password = ?,
-			  last_updated_password_time = NOW(),
-			  email = ?,
-			  last_updated_time = NOW(),
-			  mobile = ?,
-			  role_type = ?,
-			  role_id = ?,
-			  role_name = ?,
-			  department_id = ?,
-			  department_name = ?,
-			  group_id = ?,
-			  group_name = ?,
-			  authority = ?,
-			  position = ?,
-			  role_type_code=?,
-			  enabled=?,
-			  admin_avatar = ?,
-			  province=?,
-			  province_code=?,
-			  city=?,
-			  city_code=?,
-			  employee_id = ?
-			WHERE admin_id = ? `
-	_, err = o.Raw(sql, item.AdminName, item.RealName, item.Password, item.Email, item.Mobile, item.RoleType, item.RoleId, item.RoleName, item.DepartmentId, item.DepartmentName,
-		item.GroupId, item.GroupName, item.Authority, item.Position, item.RoleTypeCode, item.Enabled, item.AdminAvatar, item.Province, item.ProvinceCode, item.City, item.CityCode, item.EmployeeId, item.AdminId).Exec()
-	return
-}
-
-// 变更状态
-func EditAdminEnabled(item *Admin) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE admin
-			SET
-			  last_updated_time = NOW(),enabled=? WHERE admin_id = ? `
-	_, err = o.Raw(sql, item.Enabled, item.AdminId).Exec()
-	return
-}
-
-// DisableAdmin 禁用用户
-func DisableAdmin(adminId int) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE admin
-			SET
-			  last_updated_time = NOW(),disable_time=now(),enabled=0 WHERE admin_id = ? `
-	_, err = o.Raw(sql, adminId).Exec()
-	return
-}
-
-type SysuserDeleteReq struct {
-	AdminId int `description:"系统用户id"`
-}
-
-func DeleteSysuser(adminId int) (err error) {
-	sql := `DELETE FROM admin WHERE admin_id=? `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, adminId).Exec()
-	return
-}
-
-// GetSysAdminCountByMobile 查询系统中是否存在该手机号(如果有传入用户id,那么排除该用户)
-func GetSysAdminCountByMobile(mobile string, adminId int) (count int, err error) {
-	sql := `SELECT COUNT(1) AS count FROM admin WHERE mobile=? `
-	if adminId > 0 {
-		sql += ` AND admin_id != ` + fmt.Sprint(adminId)
-	}
-	o := orm.NewOrm()
-	err = o.Raw(sql, mobile).QueryRow(&count)
-	return
-}
-
-func GetSysUserItems(condition string, pars []interface{}) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	sql += `ORDER BY last_updated_time DESC `
-	_, err = o.Raw(sql, pars).QueryRows(&items)
-	return
-}
-
-func GetSysUserItemsOrderByCreated(condition string, pars []interface{}) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` ORDER BY created_time DESC `
-	_, err = o.Raw(sql, pars).QueryRows(&items)
-	return
-}
-func GetSysUserItemsList(condition string, pars []interface{}, startSize, pageSize int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` ORDER BY created_time DESC limit ?,?`
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
-	return
-}
-func GetSysUserItemsTotal(condition string, pars []interface{}) (total int64, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(*) FROM admin WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	err = o.Raw(sql, pars).QueryRow(&total)
-	return
-}
-
-// GetGroupSysUserList 根据分组id获取系统用户列表
-func GetGroupSysUserList(groupId int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE group_id=? ORDER BY created_time DESC `
-	_, err = o.Raw(sql, groupId).QueryRows(&items)
-	return
-}
-
-// GetDepartmentGroupSysUserList 根据部门id和分组id获取系统用户列表
-func GetDepartmentGroupSysUserList(departmentId, groupId int, roleTypeCodes string) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE department_id = ? and group_id=? and enabled=1 `
-	if roleTypeCodes != "" {
-		sql += ` and role_type_code in (` + roleTypeCodes + `) `
-	}
-	sql += ` ORDER BY created_time asc `
-	_, err = o.Raw(sql, departmentId, groupId).QueryRows(&items)
-	return
-}
-
-// GetGrooupsysUserList 根据大组id和小组id获取系统用户列表
-func GetGrooupsysUserList(groupId int, roleTypeCodes string, enabled int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE group_id = ? `
-	if roleTypeCodes != "" {
-		sql += ` and role_type_code in (` + roleTypeCodes + `) `
-	}
-	if enabled >= 0 {
-		sql += fmt.Sprint(` AND enabled=`, enabled, ` `)
-	}
-	sql += ` ORDER BY created_time asc `
-	_, err = o.Raw(sql, groupId).QueryRows(&items)
-	return
-}
-
 // GetSysAdminByIdSlice 根据账户id列表获取账户信息列表
 func GetSysAdminByIdSlice(adminIdList []string) (items []*Admin, err error) {
 	if len(adminIdList) <= 0 {
@@ -335,115 +65,9 @@ func GetSysAdminByIdSlice(adminIdList []string) (items []*Admin, err error) {
 	return
 }
 
-// GetTeamSysUserList 根据小组id获取系统用户列表
-func GetTeamSysUserList(teamId, enabled int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE group_id=? `
-	if enabled >= 0 {
-		sql += fmt.Sprint(` AND enabled=`, enabled, ` `)
-	}
-	sql += ` ORDER BY created_time DESC `
-	_, err = o.Raw(sql, teamId).QueryRows(&items)
-	return
-}
-
-// GetTeamSysUserList 根据小组id获取系统用户列表
-func GetTeamSysUserListByIds(ids string) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE group_id IN (` + ids + `) ORDER BY created_time DESC `
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-func GetGroupIdByParentId(groupId int) (items []*string, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT group_id FROM sys_group WHERE parent_id=? ORDER BY create_time DESC `
-	_, err = o.Raw(sql, groupId).QueryRows(&items)
-	return
-}
-
-// GetSysUserByParentIdGroupId 查询主管下的所有组员
-func GetSysUserByParentIdGroupId(groupId int) (items []*AdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `select real_name, role_id, role_type_code, group_id, admin_id from admin where group_id in (SELECT group_id from sys_group where parent_id=?) OR group_id=?`
-	_, err = o.Raw(sql, groupId, groupId).QueryRows(&items)
-	return
-}
 func GetAdminByGroupId(groupId int) (items []*AdminItem, err error) {
 	o := orm.NewOrm()
 	sql := `SELECT * FROM admin WHERE group_id=? ORDER BY created_time DESC`
 	_, err = o.Raw(sql, groupId).QueryRows(&items)
 	return
 }
-
-// GetSysAdminByIds 根据主键集合获取管理员信息
-func GetSysAdminByIds(adminIds string) (items []*Admin, err error) {
-	if adminIds == "" {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT * FROM admin WHERE admin_id IN (` + adminIds + `)`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-type OpenIdList struct {
-	OpenId  string
-	AdminId int
-}
-
-// GetAdminOpenIdListByMobile 根据手机号获取用户的openid列表
-func GetAdminOpenIdListByMobile(mobile string) (items []*OpenIdList, err error) {
-	sql := `SELECT admin_id, open_id FROM admin 
-          WHERE open_id != "" and mobile=? `
-	_, err = orm.NewOrm().Raw(sql, mobile).QueryRows(&items)
-	return
-}
-
-// ResearcherAdminAndUser 研究员admin信息及wx_user信息
-type ResearcherAdminAndUser struct {
-	UserId    int    `description:"用户ID"`
-	UserName  string `description:"用户名称"`
-	AdminId   int    `description:"管理员ID"`
-	AdminName string `description:"管理员姓名"`
-	OpenId    string `description:"openid"`
-}
-
-// GetResearcherAdminAndWxUserByAdminId 通过adminId获取研究员admin及user信息
-func GetResearcherAdminAndWxUserByAdminId(adminId int) (item *ResearcherAdminAndUser, err error) {
-	sql := `SELECT
-				a.admin_id,
-				a.real_name AS admin_name,
-				a.open_id,
-				b.user_id,
-				b.real_name AS user_name
-			FROM
-				admin AS a
-			JOIN wx_user AS b ON a.mobile = b.mobile
-			WHERE
-				a.admin_id = ? AND a.open_id != ""`
-	err = orm.NewOrm().Raw(sql, adminId).QueryRow(&item)
-	return
-}
-
-// 获取本组的销售ID
-func GetSelleridWhichGroup(companyId, productId int) (adminId string, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT
-			GROUP_CONCAT( DISTINCT admin_id SEPARATOR ',' ) AS adminId
-			FROM
-			admin
-			WHERE
-			group_id IN (
-			SELECT
-			a.group_id
-			FROM
-			company_product AS a
-			INNER JOIN admin AS b ON a.seller_id = b.admin_id
-			WHERE
-			a.company_id = ?
-			AND a.product_id = ?
-)`
-	err = o.Raw(sql, companyId, productId).QueryRow(&adminId)
-	return
-}

+ 0 - 226
models/system/sys_role_admin.go

@@ -1,7 +1,6 @@
 package system
 
 import (
-	"eta/eta_mobile/utils"
 	"github.com/beego/beego/v2/client/orm"
 	"time"
 )
@@ -13,25 +12,6 @@ type SysRoleAdmin struct {
 	CreateTime time.Time `orm:"column(create_time);" description:"创建时间"`
 }
 
-type RoleAdminItem struct {
-	SysRoleAdminId  int    `description:"管理员账号和角色映射表id"`
-	AdminId         int    `description:"系统用户id"`
-	AdminName       string `description:"系统用户名称"`
-	RealName        string `description:"系统用户姓名"`
-	Enabled         int    `description:"1:有效,0:禁用"`
-	Mobile          string `description:"手机号"`
-	RoleId          int    `description:"角色Id"`
-	RoleTypeCode    string `description:"角色编码"`
-	DepartmentId    int    `description:"部门id"`
-	DepartmentName  string `description:"部门名称"`
-	DepartmentGroup string `description:"部门分组"`
-	TeamId          int    `description:"小组id"`
-	GroupId         int    `description:"分组id"`
-	GroupName       string `description:"分组名称"`
-	Authority       int    `description:"管理权限,0:无,1:部门负责人,2:小组负责人,或者ficc销售主管,4:ficc销售组长"`
-	LabelVal        int    `description:"标签:1:超级管理员,2:管理员,3:部门经理,4:组长,5:ficc销售主管"`
-}
-
 func (sa *SysRoleAdmin) TableName() string {
 	return "sys_role_admin"
 }
@@ -42,209 +22,3 @@ func GetRoleIdsByAdminId(adminId int) (items []*SysRoleAdmin, err error) {
 	_, err = orm.NewOrm().Raw(sql, adminId).QueryRows(&items)
 	return
 }
-
-// GetRoleIdsByAdminIdRoleId 根据管理员账号和角色查询
-func GetRoleIdsByAdminIdRoleId(adminId int, roleId int) (item *SysRoleAdmin, err error) {
-	sql := `SELECT * from sys_role_admin where admin_id = ? and role_id=?`
-	err = orm.NewOrm().Raw(sql, adminId, roleId).QueryRow(&item)
-	return
-}
-
-// GetRoleAdminList 查询对应角色绑定的管理员列表
-func GetRoleAdminList(condition string, pars []interface{}, startSize, pageSize int) (list []*RoleAdminItem, err error) {
-	sql := `SELECT
-	s.id as sys_role_admin_id,
-	a.admin_id,
-	a.admin_name,
-	a.real_name,
-	a.mobile,
-	a.department_id,
-	a.department_name,
-	a.enabled,
-	a.role_id,
-	a.role_type_code ,
-	a.group_id,
-	a.authority,
-	a.group_name
-FROM
-	sys_role_admin s
-	INNER JOIN admin a ON s.admin_id = a.admin_id 
-where 1=1`
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` ORDER BY s.id DESC limit ?, ?`
-	_, err = orm.NewOrm().Raw(sql, pars, startSize, pageSize).QueryRows(&list)
-	return
-}
-
-// GetRoleAdminListTotal 查询对应角色绑定的管理员列表总数
-func GetRoleAdminListTotal(condition string, pars []interface{}) (total int64, err error) {
-	sql := `SELECT
-	count(*)
-FROM
-	sys_role_admin s
-	INNER JOIN admin a ON s.admin_id = a.admin_id 
-where 1=1`
-	if condition != "" {
-		sql += condition
-	}
-	err = orm.NewOrm().Raw(sql, pars).QueryRow(&total)
-	return
-}
-
-// CheckRoleAdminByAdminIds 判断是否已经绑定过该角色
-func CheckRoleAdminByAdminIds(adminIds string, roleId int) (list []*SysRoleAdmin, err error) {
-	sql := `SELECT
-	s.*
-FROM
-	sys_role_admin s
-	LEFT JOIN admin a ON s.admin_id = a.admin_id 
-where s.role_id=? and s.admin_id in (` + adminIds + `)`
-	_, err = orm.NewOrm().Raw(sql, roleId).QueryRows(&list)
-	return
-}
-
-// AddRoleAdminBatch 批量新增留言版管理员
-func AddRoleAdminBatch(admins []*SysRoleAdmin) (err error) {
-	o := orm.NewOrm()
-	_, err = o.InsertMulti(len(admins), admins)
-	return
-}
-
-// DeleteRoleAdmin 删除管理员和角色的绑定
-func DeleteRoleAdmin(SysRoleAdminId int) (err error) {
-	sql := `DELETE FROM sys_role_admin WHERE id=? `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, SysRoleAdminId).Exec()
-	return
-}
-
-// GetRoleAdminById 根据ID查询绑定记录
-func GetRoleAdminById(SysRoleAdminId int) (item *SysRoleAdmin, err error) {
-	sql := `SELECT
-	*
-FROM
-	sys_role_admin 
-where id=?`
-	err = orm.NewOrm().Raw(sql, SysRoleAdminId).QueryRow(&item)
-	return
-}
-
-// GetEnglishAuthRoleAdminList 查询英文权限管理员列表
-func GetEnglishAuthRoleAdminList(condition string, pars []interface{}, startSize, pageSize int) (total int, list []*RoleAdminItem, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT
-				s.id as sys_role_admin_id,
-				a.admin_id,
-				a.admin_name,
-				a.real_name,
-				a.mobile,
-				a.department_id,
-				a.department_name,
-				a.enabled,
-				a.role_id,
-				a.role_type_code ,
-				a.group_id,
-				a.authority,
-				a.group_name
-			FROM
-				sys_role_admin AS s
-			JOIN sys_role AS r ON s.role_id = r.role_id
-			JOIN admin AS a ON s.admin_id = a.admin_id
-			WHERE
-				1 = 1 `
-	sql += condition
-	sql += ` GROUP BY s.admin_id `
-
-	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
-	if err = o.Raw(totalSQl, pars).QueryRow(&total); err != nil {
-		return
-	}
-
-	sql += ` ORDER BY s.create_time DESC,s.admin_id ASC LIMIT ?,? `
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
-	return
-}
-
-// DeleteRoleAdminByAdminIdAndRoleIds 通过管理员ID及角色IDs删除绑定
-func DeleteRoleAdminByAdminIdAndRoleIds(adminId int, roleIds []int) (err error) {
-	if len(roleIds) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `DELETE FROM sys_role_admin WHERE admin_id = ? AND role_id IN (` + utils.GetOrmInReplace(len(roleIds)) + `) `
-	_, err = o.Raw(sql, adminId, roleIds).Exec()
-	return
-}
-
-// CheckEnglishAuthRoleAdminByAdminIds 通过管理员IDs判断是否已经绑定过英文权限角色
-func CheckEnglishAuthRoleAdminByAdminIds(adminIds []int, roleCodes []string) (list []*SysRoleAdmin, err error) {
-	if len(adminIds) == 0 || len(roleCodes) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT
-				s.*
-			FROM
-				sys_role_admin AS s
-			JOIN sys_role AS r ON s.role_id = r.role_id
-			JOIN admin AS a ON s.admin_id = a.admin_id
-			WHERE
-				s.admin_id IN (` + utils.GetOrmInReplace(len(adminIds)) + `) AND r.role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)
-			GROUP BY
-				s.admin_id`
-	_, err = o.Raw(sql, adminIds, roleCodes).QueryRows(&list)
-	return
-}
-
-// EnglishAuthRoleDetail 英文权限角色详情
-type EnglishAuthRoleDetail struct {
-	AdminId      int    `description:"用户ID"`
-	RoleTypeCode string `description:"角色类型编码"`
-}
-
-// GetAdminEnglishAuthRoleDetail 获取用户英文权限详情
-func GetAdminEnglishAuthRoleDetail(adminId int, roleCodes []string) (list []*EnglishAuthRoleDetail, err error) {
-	if len(roleCodes) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT
-				s.admin_id, r.role_type_code
-			FROM
-				sys_role_admin AS s
-			JOIN sys_role AS r ON s.role_id = r.role_id
-			JOIN admin AS a ON s.admin_id = a.admin_id
-			WHERE
-				s.admin_id = ? AND r.role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)`
-	_, err = o.Raw(sql, adminId, roleCodes).QueryRows(&list)
-	return
-}
-
-// EditEnglishAuthRoleAdmin 编辑管理员英文权限
-func EditEnglishAuthRoleAdmin(adminId int, englishRoleIds []int, roleAdmins []*SysRoleAdmin) (err error) {
-	o := orm.NewOrm()
-	tx, e := o.Begin()
-	if e != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = tx.Rollback()
-		} else {
-			_ = tx.Commit()
-		}
-	}()
-
-	// 删除原绑定关系
-	sql := `DELETE FROM sys_role_admin WHERE admin_id = ? AND role_id IN (` + utils.GetOrmInReplace(len(englishRoleIds)) + `)`
-	_, err = tx.Raw(sql, adminId, englishRoleIds).Exec()
-	if err != nil {
-		return
-	}
-
-	// 新增绑定关系
-	_, err = o.InsertMulti(len(roleAdmins), roleAdmins)
-	return
-}

+ 0 - 106
models/system/sys_user.go

@@ -86,100 +86,6 @@ func GetSysUserById(sysUserId int) (item *Admin, err error) {
 	return
 }
 
-// 根据权限code获取系统用户列表
-func GetAdminListByRoleCode(roleTypeCode string) (items []*Admin, err error) {
-	sql := `SELECT * FROM admin WHERE role_type_code=? and enabled=1 `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, roleTypeCode).QueryRows(&items)
-	return
-}
-
-// 根据权限id获取系统用户列表
-func GetAdminListByRoleId(roleId string) (items []*Admin, err error) {
-	sql := `SELECT * FROM admin WHERE role_id=? and enabled=1 `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, roleId).QueryRows(&items)
-	return
-}
-
-// GetAdminListByIds 根据用户id字符串获取系统用户列表
-func GetAdminListByIds(ids string) (items []*Admin, err error) {
-	sql := `SELECT * FROM admin WHERE admin_id in (` + ids + `) and enabled=1 `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-func ModifyPwd(sysUserId int, newPwd string) (err error) {
-	sql := `UPDATE admin SET password=?,last_updated_time=NOW() WHERE admin_id=? `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, newPwd, sysUserId).Exec()
-	return
-}
-
-type ModifyPwdReq struct {
-	OldPwd string `description:"旧密码"`
-	NewPwd string `description:"新密码"`
-}
-
-func GetAdminList() (items []*Admin, err error) {
-	sql := `SELECT * FROM admin`
-	o := orm.NewOrm()
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetSysUserByMobile 根据手机号获取管理信息
-//func GetSysUserByMobile(mobile string) (item *Admin, err error) {
-//	sql := `SELECT * FROM admin WHERE mobile = ? LIMIT 1`
-//	o := orm.NewOrm()
-//	err = o.Raw(sql, mobile).QueryRow(&item)
-//	return
-//}
-
-// 通过用户姓名跟身份获取管理员信息
-func CheckSysUserByName(userName, roleTypeCode string) (item *Admin, err error) {
-	sql := ` SELECT a.*  FROM admin AS a WHERE a.real_name=? AND a.role_type_code=? LIMIT 1`
-	o := orm.NewOrm()
-	err = o.Raw(sql, userName, roleTypeCode).QueryRow(&item)
-	return
-}
-
-// GetAdminListByGroupId 根据分组id获取系统用户列表
-func GetAdminListByGroupId(groupId int) (items []*Admin, err error) {
-	sql := `SELECT * FROM admin WHERE group_id=? and enabled=1 `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, groupId).QueryRows(&items)
-	return
-}
-
-// AdminWxUserRelation 管理员-微信用户关联
-type AdminWxUserRelation struct {
-	AdminId   int    `json:"admin_id"`
-	AdminName string `json:"admin_name"`
-	RealName  string `json:"real_name"`
-	UserId    int    `json:"user_id"`
-}
-
-// GetAdminWxUserRelationByWxUserIds 通过微信用户及平台获取后台关联信息
-func GetAdminWxUserRelationByWxUserIds(platform int, userIds []int) (list []*AdminWxUserRelation, err error) {
-	userLen := len(userIds)
-	if userLen == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT
-				ad.admin_id, ad.admin_name, ad.real_name, wu.user_id
-			FROM
-				admin AS ad
-			JOIN wx_user AS wu ON ad.mobile = wu.mobile
-			JOIN user_record AS ur ON wu.user_id = ur.user_id AND ur.create_platform = ?
-			WHERE
-				wu.user_id IN (` + utils.GetOrmInReplace(userLen) + `)`
-	_, err = o.Raw(sql, platform, userIds).QueryRows(&list)
-	return
-}
-
 // GetAdminListByIdList 根据用户id列表获取系统用户列表
 func GetAdminListByIdList(idList []int) (items []*Admin, err error) {
 	lenNum := len(idList)
@@ -192,18 +98,6 @@ func GetAdminListByIdList(idList []int) (items []*Admin, err error) {
 	return
 }
 
-// GetAdminListByIdList 根据用户id列表获取系统用户列表
-func GetAdminListByIdListWithoutEnable(idList []int) (items []*Admin, err error) {
-	lenNum := len(idList)
-	if lenNum <= 0 {
-		return
-	}
-	sql := `SELECT * FROM admin WHERE admin_id in (` + utils.GetOrmInReplace(lenNum) + `) `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, idList).QueryRows(&items)
-	return
-}
-
 // GetSysUserByMobile 手机号获取用户
 func GetSysUserByMobile(mobile string) (item *Admin, err error) {
 	o := orm.NewOrm()

+ 0 - 1417
models/target.go

@@ -1,141 +1,9 @@
 package models
 
 import (
-	"eta/eta_mobile/utils"
-	"fmt"
 	"github.com/beego/beego/v2/client/orm"
-	"github.com/rdlucklib/rdluck_tools/paging"
-	"sort"
-	"strconv"
-	"strings"
-	"time"
 )
 
-type DataList struct {
-	TradeCode    string  `orm:"column(TRADE_CODE)" description:"指标编码"`
-	SecName      string  `orm:"column(SEC_NAME)" description:"指标名称"`
-	Unit         string  `orm:"column(UNIT)" description:"单位"`
-	Remark       string  `orm:"column(REMARK)" description:"备注"`
-	Frequency    string  `description:"频度"`
-	ClassifyId   int     `description:"分类id"`
-	ClassifyName string  `description:"分类名称"`
-	Dt           string  `orm:"column(DT)" description:"录入日期"`
-	Close        float64 `orm:"column(CLOSE)" description:"录入值"`
-	ModifyTime   string  `description:"修改时间"`
-}
-
-type DataListResp struct {
-	List   []*DataList
-	Paging *paging.PagingItem `description:"分页数据"`
-}
-
-func GetDataList(condition string, pars []interface{}, startSize, pageSize int) (items []*DataList, err error) {
-	sql := `select a.TRADE_CODE,a.SEC_NAME,a.UNIT,a.frequency,a.classify_id,b.classify_name,c.DT,c.CLOSE,c.modify_time FROM edbdata AS c
-                inner join edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE
-                left join edbdata_classify AS b ON a.classify_id=b.classify_id
-                where left(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` order by c.DT desc limit ?,? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func GetDataListCount(condition string, pars []interface{}) (count int, err error) {
-	sql := ` select count(1) as count FROM edbdata AS c
-                    inner join edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE    
-                    left join edbdata_classify AS b ON a.classify_id=b.classify_id
-                    where left(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0 `
-	if condition != "" {
-		sql += condition
-	}
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, pars).QueryRow(&count)
-	return
-}
-
-type DataAddReq struct {
-	TradeCode  string `description:"指标唯一编码"`
-	CreateDate string `description:"创建日期"`
-	Close      string `description:"录入值"`
-}
-
-type Edbdata struct {
-	TradeCode  string    `orm:"column(TRADE_CODE);pk" description:"指标编码"`
-	Dt         string    `orm:"column(DT)" description:"日期"`
-	Close      string    `orm:"column(CLOSE)" description:"值"`
-	ModifyTime time.Time `orm:"column(modify_time)" description:"修改时间"`
-}
-
-func GetDataInfo(tradeCode, creteDate string) (item *Edbdata, err error) {
-	sql := " SELECT * FROM edbdata WHERE TRADE_CODE=? AND DT=? "
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode, creteDate).QueryRow(&item)
-	return
-}
-
-func AddEdbdata(item *Edbdata) (lastId int64, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	lastId, err = o.Insert(item)
-	return
-}
-
-type DataEditReq struct {
-	TradeCode     string      `description:"指标唯一编码"`
-	CreateDate    string      `description:"创建日期"`
-	Close         interface{} `description:"录入值"`
-	OldCreateDate string      `description:"旧的录入日期"`
-}
-
-// BatchDataEditReq 批量修改指标
-type BatchDataEditReq struct {
-	OldCreateDate string        `description:"旧的录入日期"`
-	CreateDate    string        `description:"新的录入日期"`
-	List          []DataEditReq `description:"需要修改的数据"`
-}
-
-// 编辑数据
-func EditEdbdata(item *Edbdata) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ` UPDATE edbdata SET CLOSE = ?,modify_time=NOW() WHERE TRADE_CODE = ? AND DT = ? `
-	_, err = o.Raw(sql, item.Close, item.TradeCode, item.Dt).Exec()
-	return
-}
-
-type EdbdataDeleteRecord struct {
-	Id         int       `orm:"column(id);pk"`
-	TradeCode  string    `orm:"column(TRADE_CODE)" description:"指标编码"`
-	Dt         string    `orm:"column(DT)" description:"日期"`
-	Close      string    `orm:"column(CLOSE)" description:"值"`
-	ModifyTime time.Time `orm:"column(modify_time)" description:"修改时间"`
-	CreateTime time.Time
-	SysUserId  int
-}
-
-func AddEdbdataDeleteRecord(item *EdbdataDeleteRecord) (lastId int64, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	lastId, err = o.Insert(item)
-	return
-}
-
-// DeleteEdbData 根据指标code和日期删除数据
-func DeleteEdbData(tradeCode, dt string) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ` DELETE FROM edbdata WHERE TRADE_CODE = ? AND DT = ? `
-	_, err = o.Raw(sql, tradeCode, dt).Exec()
-	return
-}
-
-// DeleteAllEdbData 根据指标code删除数据
-func DeleteAllEdbData(tradeCode string) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ` DELETE FROM edbdata WHERE TRADE_CODE = ? `
-	_, err = o.Raw(sql, tradeCode).Exec()
-	return
-}
-
 type Edbinfo struct {
 	TradeCode    string `orm:"column(TRADE_CODE);pk" description:"指标code"`
 	SecName      string `orm:"column(SEC_NAME);" description:"指标名称"`
@@ -151,1294 +19,9 @@ type Edbinfo struct {
 	Mobile       string `description:"录入者手机号"`
 }
 
-func GetEdbinfoListCount(condition string, pars []interface{}, mobile string, roleType int) (count int, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ``
-	if mobile != "" && roleType == 1 {
-		sql = `SELECT COUNT(1) AS count FROM edbinfo AS a 
-             INNER JOIN edbinfo_user AS c ON a.TRADE_CODE=c.TRADE_CODE AND c.mobile=?
-             WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-
-		if condition != "" {
-			sql += condition
-		}
-		err = o.Raw(sql, mobile, pars).QueryRow(&count)
-	} else {
-		sql := `SELECT COUNT(1) AS count FROM edbinfo AS a WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-
-		if condition != "" {
-			sql += condition
-		}
-		err = o.Raw(sql, pars).QueryRow(&count)
-	}
-	return
-}
-
-func GetEdbinfoList(condition string, pars []interface{}, startSize, pageSize int, mobile string, roleType int) (items []*Edbinfo, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ``
-	if mobile != "" && roleType == 1 {
-		sql = ` SELECT DISTINCT a.*,b.classify_name FROM edbinfo AS a
-                    LEFT JOIN edbdata_classify AS b ON a.classify_id=b.classify_id
-                    INNER JOIN edbinfo_user AS c ON a.TRADE_CODE=c.TRADE_CODE AND c.mobile=?
-                    WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-		if condition != "" {
-			sql += condition
-		}
-		sql += ` ORDER BY a.create_date DESC LIMIT ?,? `
-		_, err = o.Raw(sql, mobile, pars, startSize, pageSize).QueryRows(&items)
-	} else {
-		sql = `SELECT DISTINCT a.*,b.classify_name FROM edbinfo AS a
-                     LEFT JOIN edbdata_classify AS b on a.classify_id=b.classify_id
-                     WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-		if condition != "" {
-			sql += condition
-		}
-		sql += ` ORDER BY a.create_date DESC LIMIT ?,? `
-		_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
-	}
-	return
-}
-
-// EdbParamsInfo 指标数据结构体
-type EdbParamsInfo struct {
-	Unit      string `orm:"column(UNIT);" description:"单位"`
-	Frequency string `orm:"column(frequency);" description:"单位"`
-}
-
-// GetEdbUnitList 获取指标单位
-func GetEdbUnitList() (items []*EdbParamsInfo, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT UNIT from edbinfo group by UNIT`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetEdbFrequencyList 获取指标频度
-func GetEdbFrequencyList(classifyId, userId int) (items []*EdbParamsInfo, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT frequency from edbinfo a 
-join edbdata b on a.TRADE_CODE=b.TRADE_CODE
- where classify_id = ? `
-	if userId > 0 {
-		sql += ` and a.user_id = ` + fmt.Sprint(userId) + ` `
-	}
-	sql += ` group by a.frequency`
-	_, err = o.Raw(sql, classifyId).QueryRows(&items)
-	return
-}
-
-type TargetListResp struct {
-	List   []*Edbinfo
-	Paging *paging.PagingItem `description:"分页数据"`
-}
-
-type EdbinfoAddReq struct {
-	SecName    string `description:"指标名称"`
-	Unit       string `description:"单位"`
-	Frequency  string `description:"频度"`
-	ClassifyId int    `description:"分类id"`
-	NoticeTime string `description:"通知时间"`
-}
-
-// GetMaxTradeCode 获取指标最大trade_code
-func GetMaxTradeCode() (max_trade_code string, err error) {
-	sql := " SELECT MAX(TRADE_CODE) AS max_trade_code FROM edbinfo WHERE LEFT(TRADE_CODE,1)='W' AND TRADE_CODE not like '%index%'"
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql).QueryRow(&max_trade_code)
-	if (err != nil && err.Error() == utils.ErrNoRow()) || max_trade_code == `` {
-		max_trade_code = "W00"
-	}
-	return
-}
-
-func GetEdbinfoBySecName(secName string) (item *Edbinfo, err error) {
-	sql := `SELECT * FROM edbinfo WHERE SEC_NAME=? AND left(TRADE_CODE,1)='W' AND REMARK='手动' `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, secName).QueryRow(&item)
-	return
-}
-
 func GetEdbinfoByTradeCode(tradeCode string) (item *Edbinfo, err error) {
 	sql := `SELECT * FROM edbinfo WHERE TRADE_CODE=? `
 	o := orm.NewOrmUsingDB("edb")
 	err = o.Raw(sql, tradeCode).QueryRow(&item)
 	return
 }
-
-func AddEdbinfo(tradeCode, secName, unit, remark, frequency, noticeTime string, classifyId int, userId int) (err error) {
-	sql := `INSERT INTO edbinfo(TRADE_CODE, SEC_NAME,UNIT, REMARK,frequency, classify_id,notice_time,user_id,create_date) 
-			VALUES(?,?,?,?,?,?,?,?,now()) `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, tradeCode, secName, unit, remark, frequency, classifyId, noticeTime, userId).Exec()
-	return
-}
-
-func AddEdbinfoUser(tradeCode, mobile string) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `INSERT INTO edbinfo_user(TRADE_CODE, mobile) VALUES (?,?)`
-	_, err = o.Raw(sql, tradeCode, mobile).Exec()
-	return
-}
-
-type EdbinfoEditReq struct {
-	TradeCode  string `description:"指标code"`
-	SecName    string `description:"指标名称"`
-	Unit       string `description:"单位"`
-	Frequency  string `description:"频度"`
-	ClassifyId int    `description:"分类id"`
-	NoticeTime string `description:"通知时间"`
-}
-
-func EditEdbinfo(tradeCode, secName, unit, frequency, noticeTime string, classifyId int) (err error) {
-	sql := `UPDATE edbinfo SET SEC_NAME= ?, UNIT = ?,classify_id=?,frequency=?,notice_time=?,create_date=NOW() WHERE TRADE_CODE=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, secName, unit, classifyId, frequency, noticeTime, tradeCode).Exec()
-	return
-}
-
-func SearchTargetEntry(classifyId int, keyWord string) (items []*Edbinfo, err error) {
-	where := ""
-	if keyWord != "" {
-		where = `AND SEC_NAME LIKE '%` + keyWord + `%'`
-	}
-	sql := `SELECT * FROM edbinfo WHERE LEFT(TRADE_CODE,1)='W' AND REMARK='手动' AND classify_id>0 AND classify_id=? `
-	sql += where
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, classifyId).QueryRows(&items)
-	return
-}
-
-type SearchTargetListResp struct {
-	List []*Edbinfo
-}
-
-type EdbdataClassify struct {
-	ClassifyId   int
-	ClassifyName string
-	ParentId     int
-	EdbInfoTotal int
-}
-
-func GetEdbdataClassifyByClassifyName(classifyName string) (item *EdbdataClassify, err error) {
-	sql := `SELECT * FROM edbdata_classify WHERE classify_name=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, classifyName).QueryRow(&item)
-	return
-}
-
-type EdbdataClassifyList struct {
-	ClassifyId   int
-	ClassifyName string
-	ParentId     int
-	Child        []*EdbdataClassify
-}
-
-func GetEdbdataClassify(userId int64) (items []*EdbdataClassifyList, err error) {
-	var newItems []*EdbdataClassifyList
-	o := orm.NewOrmUsingDB("edb")
-	sql := ` SELECT classify_id,classify_name,parent_id FROM edbdata_classify WHERE parent_id=0 `
-	_, err = o.Raw(sql).QueryRows(&newItems)
-	if err != nil {
-		return
-	}
-	classifyLen := len(newItems)
-
-	for i := 0; i < classifyLen; i++ {
-		var childItems []*EdbdataClassify
-		parentId := newItems[i].ClassifyId
-		childSql := ``
-		if userId > 0 {
-			userClassifyList, _ := GetManualUserClassify(int(userId))
-			var userIdArr []string
-			for _, v := range userClassifyList {
-				userIdArr = append(userIdArr, strconv.Itoa(v.ClassifyId))
-			}
-
-			userIdStr := strings.Join(userIdArr, ",")
-			if userIdStr != "" {
-				childSql = "SELECT a.classify_id,a.classify_name,a.parent_id FROM edbdata_classify AS a WHERE a.is_show=1 and a.classify_id IN(" + userIdStr + ") AND parent_id=? ORDER BY a.create_time ASC "
-				_, err = o.Raw(childSql, parentId).QueryRows(&childItems)
-			}
-		} else {
-			childSql = "SELECT classify_id,classify_name,parent_id FROM edbdata_classify WHERE is_show=1 and parent_id=? ORDER BY create_time ASC "
-			_, err = o.Raw(childSql, parentId).QueryRows(&childItems)
-		}
-		if err != nil {
-			return
-		}
-		newItems[i].Child = childItems
-	}
-	for _, v := range newItems {
-		childLen := len(v.Child)
-		if childLen > 0 {
-			items = append(items, v)
-		}
-	}
-	return
-}
-
-type ManualUserClassify struct {
-	ManualUserClassifyId int `orm:"column(manual_user_classify_id);pk"`
-	AdminId              int
-	ClassifyId           int
-	CreateTime           time.Time
-}
-
-func GetManualUserClassify(sysUserId int) (list []*ManualUserClassify, err error) {
-	o := orm.NewOrmUsingDB("data")
-	sql := `SELECT * FROM manual_user_classify WHERE admin_id=? `
-	_, err = o.Raw(sql, sysUserId).QueryRows(&list)
-	return
-}
-
-type EdbdataClassifyResp struct {
-	List []*EdbdataClassifyList
-}
-
-func GetTargetBySecName(secName string) (item *Edbinfo, err error) {
-	sql := `SELECT * FROM edbinfo WHERE SEC_NAME=? AND left(TRADE_CODE,1)='W' AND REMARK='手动' `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, secName).QueryRow(&item)
-	return
-}
-
-// 更新指标数据信息
-func (edbinfo *Edbinfo) Update(cols []string) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Update(edbinfo, cols...)
-	return
-}
-
-func ModifyTargetClassifyId(tradeCode string, classifyId int) (err error) {
-	sql := `UPDATE edbinfo SET classify_id=? WHERE TRADE_CODE=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, classifyId, tradeCode).Exec()
-	return
-}
-
-func GetTargetsDataCount(tradeCode, dt string) (count int, err error) {
-	sql := `SELECT COUNT(1) AS count FROM edbdata WHERE TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode, dt).QueryRow(&count)
-	return
-}
-
-// GetTargetsDataList 根据code获取指标数据列表
-func GetTargetsDataList(tradeCode string) (items []*Edbdata, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT * FROM edbdata WHERE TRADE_CODE=? ORDER BY DT ASC `
-	_, err = o.Raw(sql, tradeCode).QueryRows(&items)
-	return
-}
-
-func GetTargetsData(tradeCode, dt string) (item *Edbdata, err error) {
-	sql := `SELECT * FROM edbdata WHERE TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode, dt).QueryRow(&item)
-	return
-}
-
-func ModifyTargetsDataByImport(tradeCode, dt, close string) (err error) {
-	sql := `UPDATE  edbdata SET CLOSE=?,modify_time=NOW() WHERE  TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, close, tradeCode, dt).Exec()
-	return
-}
-
-func AddTargetsDataByImport(tradeCode, dt, close string) (err error) {
-	sql := `INSERT INTO edbdata(TRADE_CODE, DT,CLOSE, modify_time)VALUES(?,?,?,NOW()) `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, tradeCode, dt, close).Exec()
-	return
-}
-
-type EdbdataImportResp struct {
-	Status       int
-	Msg          string
-	SuccessCount int
-	FailCount    int
-}
-
-//func GetFailList(sysUserId int) (items []*EdbdataImportFail, err error) {
-//	o := orm.NewOrmUsingDB("edb")
-//	sql := ` SELECT * FROM edbdata_import_fail WHERE sys_user_id=? `
-//	_, err = o.Raw(sql, sysUserId).QueryRows(&items)
-//	return
-//}
-
-type DataListForExport struct {
-	TradeCode    string `orm:"column(TRADE_CODE)" description:"指标code"`
-	SecName      string `orm:"column(SEC_NAME)" description:"指标名称"`
-	Unit         string `orm:"column(UNIT)" description:"单位"`
-	Frequency    string `description:"频度"`
-	ClassifyId   int    `description:"分类id"`
-	NoticeTime   string `description:"通知时间"`
-	ClassifyName string
-	Dt           string  `orm:"column(DT)" description:"日期"`
-	Close        float64 `orm:"column(CLOSE)" description:"值"`
-}
-
-func GetDataListForExport(startDate, endDate, frequency, keyWord string, classifyId int) (items []*DataListForExport, err error) {
-	where := ``
-	var pars []interface{}
-	if keyWord != "" {
-		where = ` AND SEC_NAME LIKE '%` + keyWord + `%`
-	}
-	if startDate != "" {
-		where += ` AND create_date>=? `
-		pars = append(pars, startDate)
-	}
-	if endDate != "" {
-		where += ` AND create_date<=? `
-		pars = append(pars, endDate)
-	}
-	if frequency != "" {
-		where += ` AND frequency=? `
-		pars = append(pars, frequency)
-	}
-	if classifyId > 0 {
-		where += ` AND classify_id=? `
-		pars = append(pars, classifyId)
-	}
-
-	sql := ` SELECT a.TRADE_CODE,a.SEC_NAME,a.UNIT,a.frequency,a.classify_id,b.classify_name,c.DT,c.CLOSE FROM edbdata AS c
-                INNER JOIN edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE
-                LEFT JOIN edbdata_classify AS b ON a.classify_id=b.classify_id
-                WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0 `
-	if where != "" {
-		sql += where
-	}
-	sql = sql + " ORDER BY c.DT DESC "
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, pars).QueryRows(&items)
-	return
-}
-
-type DataDeleteReq struct {
-	TradeCode  string `description:"指标唯一编码"`
-	CreateDate string `description:"数据录入日期"`
-}
-
-func DataDelete(tradeCode, createDate, close string, modifyTime time.Time, sysUserId int) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-	recordSql := ` INSERT INTO edbdata_delete_record(TRADE_CODE,DT,CLOSE,modify_time,create_time,sys_user_id) 
-                 VALUES(?,?,?,?,?,?)`
-	_, err = to.Raw(recordSql, tradeCode, createDate, close, modifyTime, time.Now(), sysUserId).Exec()
-	sql := ` DELETE FROM edbdata WHERE TRADE_CODE = ? AND DT = ? `
-	_, err = to.Raw(sql, tradeCode, createDate).Exec()
-	return
-}
-
-func GetTargetInfoCount(tradeCode string) (count int, err error) {
-	sql := ` SELECT COUNT(1) AS count FROM edbdata AS c
-           INNER JOIN edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE
-           WHERE a.TRADE_CODE=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode).QueryRow(&count)
-	return
-}
-
-type TargetDeleteReq struct {
-	TradeCode string `description:"指标唯一编码"`
-}
-
-func TargetDelete(tradeCode string) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-
-	sql := " DELETE FROM edbinfo WHERE TRADE_CODE = ? "
-	_, err = to.Raw(sql, tradeCode).Exec()
-
-	sql = " DELETE FROM edbdata WHERE TRADE_CODE = ? "
-	_, err = to.Raw(sql, tradeCode).Exec()
-
-	return
-}
-
-type Researcher struct {
-	AdminId     int    `description:"系统用户id"`
-	AdminName   string `description:"系统用户名称"`
-	RealName    string `description:"系统用户姓名"`
-	Role        string `description:"系统用户角色"`
-	Mobile      string `description:"手机号"`
-	TargetCount int    `description:"指标数量"`
-}
-
-type ResearcherListResp struct {
-	List []*Researcher
-}
-
-func GetResearcherEntry() (items []*Researcher, err error) {
-	sql := ` SELECT admin_id,admin_name,real_name,mobile,0 as target_count FROM admin WHERE role_type=1 `
-	o := orm.NewOrm()
-	_, err = o.Raw(sql).QueryRows(&items)
-	researchLen := len(items)
-	edbO := orm.NewOrmUsingDB("edb")
-	for i := 0; i < researchLen; i++ {
-		var count int
-		mobile := items[i].Mobile
-		sqlCount := ` SELECT COUNT(DISTINCT a.TRADE_CODE) AS count FROM  edbinfo_user AS a
-            INNER JOIN edbinfo AS b ON a.TRADE_CODE=b.TRADE_CODE
-            WHERE a.mobile=? AND LEFT(b.TRADE_CODE,1)='W' AND b.REMARK='手动' AND b.classify_id>0 `
-		err = edbO.Raw(sqlCount, mobile).QueryRow(&count)
-		items[i].TargetCount = count
-	}
-	return
-}
-
-func GetResearcherEntryByMobile(mobile string) (items []*Researcher, err error) {
-	sql := ` SELECT admin_id,admin_name,real_name,mobile,0 as target_count FROM admin WHERE  role_type=1 `
-	if mobile != "" {
-		sql += ` AND mobile IN(` + mobile + `)`
-	}
-	o := orm.NewOrm()
-	_, err = o.Raw(sql).QueryRows(&items)
-	researchLen := len(items)
-	edbO := orm.NewOrmUsingDB("edb")
-	for i := 0; i < researchLen; i++ {
-		var count int
-		mobile := items[i].Mobile
-		sqlCount := ` SELECT COUNT(DISTINCT a.TRADE_CODE) AS count FROM  edbinfo_user AS a
-            INNER JOIN edbinfo AS b ON a.TRADE_CODE=b.TRADE_CODE
-            WHERE a.mobile=? AND LEFT(b.TRADE_CODE,1)='W' AND b.REMARK='手动' AND b.classify_id>0 `
-		err = edbO.Raw(sqlCount, mobile).QueryRow(&count)
-		items[i].TargetCount = count
-	}
-	return
-}
-
-type EdbinfoItems struct {
-	TradeCode    string `orm:"column(TRADE_CODE);pk" description:"指标code"`
-	SecName      string `orm:"column(SEC_NAME);" description:"指标名称"`
-	Unit         string `orm:"column(UNIT);" description:"单位"`
-	Remark       string `orm:"column(REMARK);" description:"备注"`
-	Frequency    string `description:"频度"`
-	ClassifyId   int    `description:"分类id"`
-	ClassifyName string `description:"分类名称"`
-	CreateDate   string `description:"创建时间"`
-	UserId       int    `description:"录入用户id"`
-	NoticeTime   string `description:"通知时间"`
-	Mobile       string `description:"录入者手机号"`
-	ModifyDate   string `description:"待更新日期"`
-	Status       string `description:"状态:未完成/完成"`
-}
-
-type TargetItemsResp struct {
-	List SortEdbInfo
-}
-
-type SortEdbInfo []EdbinfoItems
-
-func GetTargetItems(mobile string, classifyId int) (lastItems SortEdbInfo, err error) {
-	var items []*EdbinfoItems
-	o := orm.NewOrmUsingDB("edb")
-	//sql := ` SELECT *,'' modify_date,'' status FROM edbinfo AS a WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0 `
-
-	sql := ` SELECT *,'' modify_date,'' STATUS FROM edbinfo AS a 
-            WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0
-             `
-	if classifyId > 0 {
-		sql += ` AND a.classify_id=` + strconv.Itoa(classifyId) + ``
-	}
-	sql += ` GROUP BY a.TRADE_CODE `
-
-	//if classifyId > 0 {
-	//	sql = ` SELECT *,'' modify_date,'' status FROM edbinfo AS a
-	//        WHERE a.classify_id=` + strconv.Itoa(classifyId) + ` AND LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0
-	//         GROUP BY a.TRADE_CODE `
-	//}
-
-	sql = sql + ` ORDER BY CONVERT(a.SEC_NAME USING gbk )  COLLATE gbk_chinese_ci ASC `
-	_, err = o.Raw(sql).QueryRows(&items)
-	if err != nil {
-		return
-	}
-	itemsLen := len(items)
-	nowWeek := time.Now().Weekday().String()
-
-	fmt.Println(nowWeek)
-	finishEdbInfo := SortEdbInfo{}
-	unFinishEdbInfo := SortEdbInfo{}
-
-	for i := 0; i < itemsLen; i++ {
-		noticeTime := items[i].NoticeTime
-		frequency := items[i].Frequency
-		tradeCode := items[i].TradeCode
-		if noticeTime != "" {
-			if frequency == "周度" {
-				noticeArr := strings.Split(noticeTime, " ")
-				noticeWeek := noticeArr[0]
-				fmt.Println(noticeWeek)
-				addDay := 0
-
-				if nowWeek == "Sunday" {
-					if noticeWeek == "周日" {
-						addDay = 0
-					} else if noticeWeek == "周一" {
-						addDay = 1
-					} else if noticeWeek == "周二" {
-						addDay = 2
-					} else if noticeWeek == "周三" {
-						addDay = 3
-					} else if noticeWeek == "周四" {
-						addDay = 4
-					} else if noticeWeek == "周五" {
-						addDay = 5
-					} else if noticeWeek == "周六" {
-						addDay = 6
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Monday" {
-					if noticeWeek == "周日" {
-						addDay = 6
-					} else if noticeWeek == "周一" {
-						addDay = 0
-					} else if noticeWeek == "周二" {
-						addDay = 1
-					} else if noticeWeek == "周三" {
-						addDay = 2
-					} else if noticeWeek == "周四" {
-						addDay = 3
-					} else if noticeWeek == "周五" {
-						addDay = 4
-					} else if noticeWeek == "周六" {
-						addDay = 5
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Tuesday" {
-					if noticeWeek == "周日" {
-						addDay = 5
-					} else if noticeWeek == "周一" {
-						addDay = 6
-					} else if noticeWeek == "周二" {
-						addDay = 0
-					} else if noticeWeek == "周三" {
-						addDay = 1
-					} else if noticeWeek == "周四" {
-						addDay = 2
-					} else if noticeWeek == "周五" {
-						addDay = 3
-					} else if noticeWeek == "周六" {
-						addDay = 4
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Wednesday" {
-					if noticeWeek == "周日" {
-						addDay = 4
-					} else if noticeWeek == "周一" {
-						addDay = 5
-					} else if noticeWeek == "周二" {
-						addDay = 6
-					} else if noticeWeek == "周三" {
-						addDay = 0
-					} else if noticeWeek == "周四" {
-						addDay = 1
-					} else if noticeWeek == "周五" {
-						addDay = 2
-					} else if noticeWeek == "周六" {
-						addDay = 3
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Thursday" {
-					if noticeWeek == "周日" {
-						addDay = 3
-					} else if noticeWeek == "周一" {
-						addDay = 4
-					} else if noticeWeek == "周二" {
-						addDay = 5
-					} else if noticeWeek == "周三" {
-						addDay = 6
-					} else if noticeWeek == "周四" {
-						addDay = 0
-					} else if noticeWeek == "周五" {
-						addDay = 1
-					} else if noticeWeek == "周六" {
-						addDay = 2
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Friday" {
-					if noticeWeek == "周日" {
-						addDay = 2
-					} else if noticeWeek == "周一" {
-						addDay = 3
-					} else if noticeWeek == "周二" {
-						addDay = 4
-					} else if noticeWeek == "周三" {
-						addDay = 5
-					} else if noticeWeek == "周四" {
-						addDay = 6
-					} else if noticeWeek == "周五" {
-						addDay = 0
-					} else if noticeWeek == "周六" {
-						addDay = 1
-					} else {
-						addDay = 0
-					}
-				} else if nowWeek == "Saturday" {
-					if noticeWeek == "周日" {
-						addDay = 1
-					} else if noticeWeek == "周一" {
-						addDay = 2
-					} else if noticeWeek == "周二" {
-						addDay = 3
-					} else if noticeWeek == "周三" {
-						addDay = 4
-					} else if noticeWeek == "周四" {
-						addDay = 5
-					} else if noticeWeek == "周五" {
-						addDay = 6
-					} else if noticeWeek == "周六" {
-						addDay = 0
-					} else {
-						addDay = 0
-					}
-				}
-
-				modifyDate := time.Now().AddDate(0, 0, addDay)
-				modifyDateStr := modifyDate.Format(utils.FormatDate)
-				items[i].ModifyDate = modifyDateStr
-
-				modifyDateEndStr := modifyDate.AddDate(0, 0, -7).Format(utils.FormatDate)
-
-				fmt.Println("addDay:", addDay)
-				fmt.Println("modifyDateEndStr:", modifyDateEndStr)
-
-				count := 0
-				sqlCount := ` SELECT COUNT(1) AS num FROM edbdata WHERE TRADE_CODE=? AND DT >= ? AND DT <= ? `
-				err = o.Raw(sqlCount, tradeCode, modifyDateEndStr, modifyDateStr).QueryRow(&count)
-				if err != nil {
-					return nil, err
-				}
-				if count > 0 {
-					items[i].Status = "完成"
-					finishEdbInfo = append(finishEdbInfo, *items[i])
-				} else {
-					items[i].Status = "未完成"
-					unFinishEdbInfo = append(unFinishEdbInfo, *items[i])
-				}
-			} else if frequency == "日度" {
-				items[i].Status = "完成"
-				finishEdbInfo = append(finishEdbInfo, *items[i])
-			} else if frequency == "月度" {
-				myYear := time.Now().Year()
-				myMonth := time.Now().Format("01")
-				startDate, endDate := utils.GetMonthStartAndEnd(strconv.Itoa(myYear), myMonth)
-				count := 0
-				sqlCount := ` SELECT COUNT(1) AS num FROM edbdata WHERE TRADE_CODE=? AND DT >= ? AND DT <= ? `
-				err = o.Raw(sqlCount, tradeCode, startDate, endDate).QueryRow(&count)
-				if err != nil {
-					return nil, err
-				}
-				if noticeTime != "" {
-					var modifyDateStr string
-					strArr := strings.Split(noticeTime, "日")
-					myYear := time.Now().Year()
-					myMonth := time.Now().Format("01")
-					modifyDateStr = strconv.Itoa(myYear) + "-" + myMonth + "-" + strArr[0]
-					items[i].ModifyDate = modifyDateStr
-				}
-				if count > 0 {
-					items[i].Status = "完成"
-					finishEdbInfo = append(finishEdbInfo, *items[i])
-				} else {
-					items[i].Status = "未完成"
-					unFinishEdbInfo = append(unFinishEdbInfo, *items[i])
-				}
-			} else {
-				items[i].Status = "完成"
-				finishEdbInfo = append(finishEdbInfo, *items[i])
-			}
-		} else {
-			if frequency == "月度" {
-				myYear := time.Now().Year()
-				myMonth := time.Now().Format("01")
-				startDate, endDate := utils.GetMonthStartAndEnd(strconv.Itoa(myYear), myMonth)
-				count := 0
-				sqlCount := ` SELECT COUNT(1) AS num FROM edbdata WHERE TRADE_CODE=? AND DT >= ? AND DT <= ? `
-				err = o.Raw(sqlCount, tradeCode, startDate, endDate).QueryRow(&count)
-				if err != nil {
-					return nil, err
-				}
-				if count > 0 {
-					items[i].Status = "完成"
-					finishEdbInfo = append(finishEdbInfo, *items[i])
-				} else {
-					items[i].Status = "未完成"
-					unFinishEdbInfo = append(unFinishEdbInfo, *items[i])
-				}
-			} else {
-				items[i].Status = "完成"
-				finishEdbInfo = append(finishEdbInfo, *items[i])
-			}
-		}
-	}
-	sort.Sort(SortByModifyDate{finishEdbInfo})
-	sort.Sort(SortByModifyDate{unFinishEdbInfo})
-	lastItems = append(lastItems, unFinishEdbInfo...)
-	lastItems = append(lastItems, finishEdbInfo...)
-	return
-}
-
-// 获取此 slice 的长度
-func (p SortEdbInfo) Len() int { return len(p) }
-
-// 根据元素的状态降序排序
-func (p SortEdbInfo) Less(i, j int) bool {
-	return p[i].Status > p[j].Status
-}
-
-// 交换数据
-func (p SortEdbInfo) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-
-// 嵌套结构体  将继承 SortEdbInfo 的所有属性和方法
-// 所以相当于SortByName 也实现了 Len() 和 Swap() 方法
-type SortByStatus struct{ SortEdbInfo }
-
-// 根据元素的姓名长度降序排序 (此处按照自己的业务逻辑写)
-func (p SortByStatus) Less(i, j int) bool {
-	return len(p.SortEdbInfo[i].Status) > len(p.SortEdbInfo[j].Status)
-}
-
-type SortByModifyDate struct{ SortEdbInfo }
-
-// 根据元素的年龄降序排序 (此处按照自己的业务逻辑写)
-func (p SortByModifyDate) Less(i, j int) bool {
-	return p.SortEdbInfo[i].ModifyDate > p.SortEdbInfo[j].ModifyDate
-}
-
-type DataCheckResp struct {
-	Status int    `description:"状态:1:该日期已存在数据,是否确认修改?,0:数据不存在"`
-	Close  string `description:"值"`
-}
-
-type TargetCheckResp struct {
-	Status int `description:"状态:1:该指标有关联数据,请先删除数据,0:指标不存在关联数据,可直接删除"`
-}
-
-type EdbdataExportList struct {
-	TradeCode    string `orm:"column(TRADE_CODE);" description:"指标code"`
-	SecName      string `orm:"column(SEC_NAME);" description:"指标名称"`
-	Unit         string `orm:"column(UNIT);" description:"单位"`
-	Remark       string `orm:"column(REMARK);" description:"备注"`
-	Frequency    string `description:"频度"`
-	ClassifyId   int    `description:"分类id"`
-	ClassifyName string `description:"分类名称"`
-	CreateDate   string `description:"创建时间"`
-	Dt           string `orm:"column(Dt);" description:"最新一次录入时间"`
-}
-
-func GetEdbdataSecName(condition string, pars []interface{}) (items []*EdbdataExportList, err error) {
-	//sql := `SELECT a.TRADE_CODE,a.SEC_NAME,a.frequency,a.UNIT,MAX(c.DT) AS Dt
-	//	        FROM edbdata AS c
-	//	        INNER JOIN edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE
-	//	        INNER JOIN edbinfo_user AS d ON a.TRADE_CODE=d.TRADE_CODE
-	//	        LEFT JOIN edbdata_classify AS b ON a.classify_id=b.classify_id
-	//	        WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-	sql := `SELECT a.TRADE_CODE,a.SEC_NAME,a.frequency,a.UNIT,MAX(c.DT) AS Dt,b.classify_name
-		        FROM edbdata AS c
-		        INNER JOIN edbinfo AS a ON a.TRADE_CODE=c.TRADE_CODE
-		        LEFT JOIN edbdata_classify AS b ON a.classify_id=b.classify_id
-		        WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0`
-	if condition != "" {
-		sql += condition
-	}
-	sql += " GROUP BY a.TRADE_CODE ORDER BY a.TRADE_CODE ASC "
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, pars).QueryRows(&items)
-	return
-}
-
-func GetEdbDataFrequency(classifyId int) (items []*string, err error) {
-	sql := `SELECT DISTINCT frequency FROM edbinfo where classify_id=? AND frequency IS NOT NULL ORDER BY FIELD(frequency,'日度','周度','月度','季度','半年度','年度') `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, classifyId).QueryRows(&items)
-	return
-}
-
-func GetEdbDataFrequencyByKeyord(keyword string) (items []*string, err error) {
-	sql := `SELECT DISTINCT frequency FROM edbinfo where SEC_NAME=? ORDER BY FIELD(frequency,'日度','周度','月度','季度','半年度','年度') `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, keyword).QueryRows(&items)
-	return
-}
-
-type EdbdataList struct {
-	Dt string `orm:"column(DT);" description:"录入时间"`
-}
-
-func GetEdbdataList(tradeCode string) (items []*EdbdataList, err error) {
-	sql := ` SELECT  DT FROM edbdata WHERE TRADE_CODE IN(` + tradeCode + `)  GROUP BY DT ORDER BY DT DESC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-type EdbdataItem struct {
-	TradeCode string  `orm:"column(TRADE_CODE);" description:"指标code"`
-	Dt        string  `orm:"column(DT);" description:"最新一次录入时间"`
-	Close     float64 `orm:"column(CLOSE);" description:"值"`
-}
-
-func GetEdbdataValueByTradeCode(tradeCode, dt string) (item *EdbdataItem, err error) {
-	sql := ` SELECT  TRADE_CODE,DT,CLOSE FROM edbdata WHERE TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode, dt).QueryRow(&item)
-	return
-}
-
-func GetEdbdataAllByTradeCode(tradeCode string) (items []*EdbdataItem, err error) {
-	sql := ` SELECT * FROM edbdata WHERE TRADE_CODE=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, tradeCode).QueryRows(&items)
-	return
-}
-
-func GetEdbdataClassifyByParentId(parentId int) (items []*EdbdataClassify, err error) {
-	sql := ` SELECT * FROM edbdata_classify WHERE parent_id=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, parentId).QueryRows(&items)
-	return
-}
-
-type LzPriceClassify struct {
-	ProductName string
-}
-
-func GetLzPriceClassify() (items []*LzPriceClassify, err error) {
-	sql := ` SELECT product_name  FROM longzhongpriceinfo GROUP BY product_name ORDER BY product_name DESC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-type Longzhongpriceinfo struct {
-	LongzhongpriceinfoId int `orm:"column(longzhongpriceinfo_id);pk"`
-	Standard             string
-	ModelName            string
-	Unit                 string
-	AreaName             string
-	PriceType            string
-	Memo                 string
-	PriceId              string
-	ProductName          string
-	InfoType             string
-	InfoTypeRemark       string
-	MarketName           string
-	ManufactureName      string
-}
-
-func GetLongzhongpriceinfoByClassifyName(productName string) (items []*Longzhongpriceinfo, err error) {
-	sql := `SELECT * FROM longzhongpriceinfo WHERE product_name=? ORDER BY longzhongpriceinfo_id ASC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, productName).QueryRows(&items)
-	return
-}
-
-func GetLongzhongPriceDataMaxCount(productName string) (count int, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT MAX(t.num) AS count FROM (
-				SELECT COUNT(1) AS num  FROM longzhongpriceinfo AS a
-				INNER JOIN longzhongpricedata AS b ON a.longzhongpriceinfo_id=b.longzhongpriceinfo_id
-				WHERE a.product_name=?
-				GROUP BY a.product_name
-			)AS t `
-	err = o.Raw(sql, productName).QueryRow(&count)
-	return
-}
-
-type LongzhongpricedataItems struct {
-	LongzhongpricedataId int `orm:"column(longzhongpricedata_id);pk"`
-	LongzhongpriceinfoId int
-	PriceDate            string
-	Memo                 string
-	Price                float64
-	CnyPrice             float64
-	ZsyPrice             float64
-	ZshPrice             float64
-	LowPrice             float64
-	HighPrice            float64
-	RisePrice            float64
-	TonPrice             float64
-	PriceType            string
-	UpdateDate           string
-}
-
-func GetLongzhongPriceDataById(lzPriceInfoId int) (items []*LongzhongpricedataItems, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := ` SELECT DISTINCT a.longzhongpriceinfo_id,a.price_date,a.memo,a.price,a.cny_price,a.zsy_price,a.zsh_price,a.low_price,a.high_price,a.rise_price,a.ton_price,a.price_type,a.update_date  
-			 FROM longzhongpricedata AS a
-			 WHERE longzhongpriceinfo_id=? ORDER BY price_date DESC `
-	_, err = o.Raw(sql, lzPriceInfoId).QueryRows(&items)
-	return
-}
-
-func GetLzSurveyClassify() (items []*LzPriceClassify, err error) {
-	sql := ` SELECT breed_name AS product_name  FROM longzhong_survey_product GROUP BY breed_name ORDER BY breed_name DESC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-type LongzhongSurveyProduct struct {
-	SurveyProductId      int `orm:"column(survey_product_id);pk"`
-	ProjectQuotaId       int64
-	BreedId              string
-	BreedName            string
-	QuotaId              string
-	QuotaName            string
-	UnitId               string
-	UnitName             string
-	SampleType           int64
-	SampleId             string
-	SampleName           string
-	DeviceId             string
-	Device               string
-	ProductCraftId       string
-	ProductCraft         string
-	ProductLine          string
-	InputMode            int64
-	Frequency            int64
-	InputValue           string
-	TaskShouldFinishTime int
-	CustomId             string
-	CustomType           int64
-	Custom               string
-	QuotaSampleId        int64
-	StartDate            string
-	EndDate              string
-	LzCode               string
-}
-
-func GetLongzhongSurveyProductByClassifyName(productName string) (items []*LongzhongSurveyProduct, err error) {
-	sql := `SELECT * FROM longzhong_survey_product WHERE breed_name=? ORDER BY survey_product_id ASC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, productName).QueryRows(&items)
-	return
-}
-
-func GetLzSurveyProductByNameAndFrequency(productName string, frequency int) (items []*LongzhongSurveyProduct, err error) {
-
-	sql := `SELECT * FROM longzhong_survey_product WHERE breed_name=? AND frequency=? ORDER BY survey_product_id ASC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, productName, frequency).QueryRows(&items)
-	return
-}
-
-func GetExportLzSurveyProductByBreedIds(breedIds []string) (items []*LongzhongSurveyProduct, err error) {
-	if len(breedIds) == 0 {
-		return
-	}
-	field := ` survey_product_id, breed_id, breed_name, sample_name, custom, quota_name, lz_code, frequency, unit_name, end_date, input_value `
-	sql := `SELECT ` + field + ` FROM longzhong_survey_product WHERE breed_id IN (` + utils.GetOrmInReplace(len(breedIds)) + `) ORDER BY breed_id ASC, frequency ASC, survey_product_id ASC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, breedIds).QueryRows(&items)
-	return
-}
-
-func GetLzFrequency(productName string) (items []*int, err error) {
-	sql := `SELECT DISTINCT frequency FROM longzhong_survey_product WHERE breed_name=? ORDER BY frequency`
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, productName).QueryRows(&items)
-	return
-}
-
-// EdbInfoItem
-type EdbInfoItem struct {
-	TradeCode    string     `orm:"column(TRADE_CODE);pk" description:"指标code"`
-	SecName      string     `orm:"column(SEC_NAME);" description:"指标名称"`
-	Unit         string     `orm:"column(UNIT);" description:"单位"`
-	Remark       string     `orm:"column(REMARK);" description:"备注"`
-	Frequency    string     `description:"频度"`
-	ClassifyId   int        `description:"分类id"`
-	ClassifyName string     `description:"分类名称"`
-	CreateDate   string     `description:"创建时间"`
-	UserId       int        `description:"录入用户id"`
-	NoticeTime   string     `description:"通知时间"`
-	Mobile       string     `description:"录入者手机号"`
-	ModifyDate   string     `description:"待更新日期"`
-	Status       string     `description:"状态:未完成/完成"`
-	DataList     []*Edbdata `description:"指标数据列表"`
-}
-
-// GetTargetItemList 获取指标列表数据
-func GetTargetItemList(classifyId, edbShowType int, frequency, keyword, tradeCode string, classifyIdStrList []string) (items []*EdbInfoItem, err error) {
-	o := orm.NewOrmUsingDB("edb")
-
-	sql := ` SELECT a.*,'' modify_date,'' STATUS FROM edbinfo AS a `
-	if edbShowType != 0 {
-		sql = ` SELECT a.*,b.DT,'' modify_date,'' STATUS FROM edbinfo AS a 
-left join edbdata b on a.TRADE_CODE=b.TRADE_CODE `
-	}
-	sql += ` WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id>0 `
-
-	//如果没有分类id集合列表,那么就没有数据了,不用往下执行了,直接返回好了
-	if len(classifyIdStrList) <= 0 {
-		return
-	}
-	if len(classifyIdStrList) > 0 {
-		sql += ` AND a.classify_id in (` + strings.Join(classifyIdStrList, ",") + `)  `
-	}
-	if classifyId > 0 {
-		sql += ` AND a.classify_id=` + strconv.Itoa(classifyId) + ` `
-	}
-	//频度
-	if frequency != "" {
-		sql += ` AND a.frequency="` + frequency + `" `
-	}
-	//关键字
-	if keyword != "" {
-		sql += ` AND (a.SEC_NAME like "%` + keyword + `%"  or a.TRADE_CODE like "%` + keyword + `%" )`
-	}
-	//指定指标
-	if tradeCode != "" {
-		sql += ` AND a.TRADE_CODE = "` + tradeCode + `" `
-	}
-	//指标里面是否有数据
-	switch edbShowType {
-	case 1:
-		sql += ` AND b.CLOSE is not null `
-	case 2:
-		sql += ` AND b.CLOSE is null `
-	}
-	sql += ` GROUP BY a.TRADE_CODE `
-
-	sql = sql + ` ORDER BY CONVERT(a.SEC_NAME USING gbk )  COLLATE gbk_chinese_ci ASC `
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-
-}
-
-// GetLzItemList 模糊查询隆众数据库指标列表
-//func GetLzItemList(keyword string) (items []*data_manage.LongzhongSurveyProduct, err error) {
-//	o := orm.NewOrmUsingDB("edb")
-//
-//	sql := "SELECT * FROM longzhong_survey_product WHERE CONCAT(sample_name,breed_name,custom,quota_name,lz_code) LIKE '%" + keyword + "%'"
-//	_, err = o.Raw(sql).QueryRows(&items)
-//	return
-//
-//}
-
-type lzSurveyData struct {
-	DataTime   string `orm:"column(data_time)" description:"日期"`
-	InputValue string `orm:"column(input_value)" description:"值"`
-}
-
-// GetLzItemListByCode 根据code查询隆众数据列表
-func GetLzItemListByCode(lzCode string) (items []*lzSurveyData, err error) {
-	o := orm.NewOrmUsingDB("edb")
-
-	sql := "SELECT * FROM longzhong_survey_data WHERE survey_product_id=? GROUP BY data_time DESC"
-	_, err = o.Raw(sql, lzCode).QueryRows(&items)
-	return
-}
-
-// GetEdbDataListByCodes 通过指标ID获取所有数据
-func GetEdbDataListByCodes(tradeCode string) (items []*Edbdata, err error) {
-	sql := ` SELECT  TRADE_CODE,DT,round(CLOSE,4) CLOSE,modify_time  FROM edbdata WHERE TRADE_CODE IN(` + tradeCode + `)  GROUP BY TRADE_CODE,DT ORDER BY DT DESC `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// TargetItemListResp 指标数据结构体
-type TargetItemListResp struct {
-	List          []*EdbInfoItem
-	FrequencyList []string
-}
-
-// BatchDataDeleteReq 批量删除某日的指标数据请求结构体
-type BatchDataDeleteReq struct {
-	CreateDate    string   `description:"创建日期"`
-	TradeCodeList []string `description:"指标唯一编码列表"`
-}
-
-// BatchDeleteEdbDataByDate 批量删除某日的指标数据
-func BatchDeleteEdbDataByDate(tradeCodes, dt string, opUserId int) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	var list []*Edbdata
-	sql := ` select * FROM edbdata WHERE TRADE_CODE in  (` + tradeCodes + `) AND DT = ? `
-	_, err = o.Raw(sql, dt).QueryRows(&list)
-	if err != nil {
-		return
-	}
-	deleteRecordList := make([]*EdbdataDeleteRecord, 0)
-	for _, edbDataInfo := range list {
-		deleteRecord := &EdbdataDeleteRecord{
-			TradeCode:  edbDataInfo.TradeCode,
-			Dt:         edbDataInfo.Dt,
-			Close:      edbDataInfo.Close,
-			ModifyTime: time.Now(),
-			CreateTime: time.Now(),
-			SysUserId:  opUserId,
-		}
-		deleteRecordList = append(deleteRecordList, deleteRecord)
-	}
-	if len(deleteRecordList) > 0 {
-		_, tmpErr := o.InsertMulti(len(deleteRecordList), deleteRecordList)
-		if tmpErr != nil {
-			err = tmpErr
-			return
-		}
-	}
-	sql = ` DELETE FROM edbdata WHERE TRADE_CODE in  (` + tradeCodes + `) AND DT = ? `
-	_, err = o.Raw(sql, dt).Exec()
-	return
-}
-
-// BatchDeleteEdbData 批量删除指标数据
-func BatchDeleteEdbData(tradeCode string, opUserId int) (err error) {
-	o := orm.NewOrmUsingDB("edb")
-	var list []*Edbdata
-	sql := ` select * FROM edbdata WHERE TRADE_CODE =  ? `
-	_, err = o.Raw(sql, tradeCode).QueryRows(&list)
-	if err != nil {
-		return
-	}
-	deleteRecordList := make([]*EdbdataDeleteRecord, 0)
-	for _, edbDataInfo := range list {
-		deleteRecord := &EdbdataDeleteRecord{
-			TradeCode:  edbDataInfo.TradeCode,
-			Dt:         edbDataInfo.Dt,
-			Close:      edbDataInfo.Close,
-			ModifyTime: time.Now(),
-			CreateTime: time.Now(),
-			SysUserId:  opUserId,
-		}
-		deleteRecordList = append(deleteRecordList, deleteRecord)
-	}
-	_, err = o.InsertMulti(len(deleteRecordList), deleteRecordList)
-	if err != nil {
-		return
-	}
-	sql = ` DELETE FROM edbdata WHERE TRADE_CODE  = ? `
-	_, err = o.Raw(sql, tradeCode).Exec()
-	return
-}
-
-// GetEdbInfoCountByClassifyId 根据指标分类id获取当前分类下的指标数量
-func GetEdbInfoCountByClassifyId(classifyId int) (count int, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT COUNT(1) AS count FROM ( SELECT a.*,b.CLOSE FROM edbinfo AS a 
-             INNER JOIN edbdata AS b ON a.TRADE_CODE=b.TRADE_CODE
-             WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' AND a.classify_id=? group by a.TRADE_CODE) d `
-	err = o.Raw(sql, classifyId).QueryRow(&count)
-	return
-}
-
-// EdbInfoGroupCount 指标分类id获取当前分类下的指标数量
-type EdbInfoGroupCount struct {
-	Count      int
-	ClassifyId int
-}
-
-// GetEdbInfoGroupCountByClassifyIds 根据指标分类id获取当前分类下的指标数量
-func GetEdbInfoGroupCountByClassifyIds(classifyIds string) (list []*EdbInfoGroupCount, err error) {
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT COUNT(1) AS count,classify_id FROM ( SELECT a.*,b.CLOSE FROM edbinfo AS a 
-             INNER JOIN edbdata AS b ON a.TRADE_CODE=b.TRADE_CODE
-             WHERE LEFT(a.TRADE_CODE,1)='W' AND a.REMARK='手动' and a.classify_id in (` + classifyIds + `) group by a.TRADE_CODE) d 
-						 GROUP BY classify_id `
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}
-
-//// GetExcelData 获取excel样式数据
-//func GetExcelData() (list []*data_manage.ExcelStyle, err error) {
-//	o := orm.NewOrmUsingDB("edb")
-//	sql := `SELECT * FROM excel_style `
-//	_, err = o.Raw(sql).QueryRows(&list)
-//	return
-//}
-//
-//// AddExcelData 添加excel样式数据
-//func AddExcelData(item *data_manage.ExcelStyle) (id int64, err error) {
-//	o := orm.NewOrmUsingDB("edb")
-//	id, err = o.Insert(item)
-//	return
-//}
-
-type EdbdataFloat struct {
-	TradeCode  string    `orm:"column(TRADE_CODE);pk" description:"指标编码"`
-	Dt         string    `orm:"column(DT)" description:"日期"`
-	Close      float64   `orm:"column(CLOSE)" description:"值"`
-	ModifyTime time.Time `orm:"column(modify_time)" description:"修改时间"`
-}
-
-func GetTargetsDataFloat(tradeCode, dt string) (item *EdbdataFloat, err error) {
-	sql := `SELECT * FROM edbdata WHERE TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	err = o.Raw(sql, tradeCode, dt).QueryRow(&item)
-	return
-}
-
-func ModifyEdbinfo(tradeCode, unit, frequency string, classifyId int) (err error) {
-	sql := `UPDATE edbinfo SET UNIT = ?,frequency=?, classify_id=?, create_date=NOW() WHERE TRADE_CODE=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, unit, frequency, classifyId, tradeCode).Exec()
-	return
-}
-
-func DeleteTargetsDataByImport(tradeCode, dt string) (err error) {
-	sql := `DELETE FROM edbdata WHERE TRADE_CODE=? AND DT=? `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql, tradeCode, dt).Exec()
-	return
-}
-
-// GetEdbinfoListByCodeListGroupByUserId 根据指标code列表、用户分组获取指标信息
-func GetEdbinfoListByCodeListGroupByUserId(edbCodeList []string) (items []*Edbinfo, err error) {
-	num := len(edbCodeList)
-	if num <= 0 {
-		return
-	}
-	o := orm.NewOrmUsingDB("edb")
-	sql := `SELECT * FROM edbinfo WHERE TRADE_CODE in (` + utils.GetOrmInReplace(num) + `) GROUP BY user_id `
-	_, err = o.Raw(sql, edbCodeList).QueryRows(&items)
-	return
-}
-
-// ModifyEdbinfoUserIdByCodeList 根据指标code列表修改创建人
-func ModifyEdbinfoUserIdByCodeList(edbCodeList []string, userId int) (err error) {
-	num := len(edbCodeList)
-	if num <= 0 {
-		return
-	}
-	o := orm.NewOrmUsingDB("edb")
-	sql := `UPDATE edbinfo SET user_id=? WHERE TRADE_CODE in (` + utils.GetOrmInReplace(num) + `) `
-	_, err = o.Raw(sql, userId, edbCodeList).Exec()
-	return
-}
-
-func GetEdbInfoAdminList() (list []int, err error) {
-	sql := `SELECT user_id FROM edbinfo GROUP BY user_id `
-	o := orm.NewOrmUsingDB("edb")
-	_, err = o.Raw(sql).QueryRows(&list)
-	return
-}

+ 0 - 426
models/user_view_history.go

@@ -1,435 +1,9 @@
 package models
 
 import (
-	"eta/eta_mobile/utils"
 	"github.com/beego/beego/v2/client/orm"
-	"time"
 )
 
-type UserViewHistory struct {
-	ViewHistoryId        int       `orm:"column(id);pk"`
-	UserId               int       `description:"用户id"`
-	Mobile               string    `description:"手机号"`
-	Email                string    `description:"邮箱"`
-	RealName             string    `description:"用户实际姓名"`
-	CompanyName          string    `description:"公司名称"`
-	ViewTitle            string    `description:"访问标题"`
-	ViewPage             string    `description:"访问页面"`
-	ReportChapterModule  string    `description:"访问核心观点或者图文逻辑"`
-	CreatedTime          string    `description:"创建时间"`
-	LastUpdatedTime      time.Time `description:"访问历史类型,weekly_report 周报,pdf;默认值:weekly_report"`
-	ResearchReportId     int       `description:"研报id"`
-	ResearchReportTypeId int       `description:"报告章节id,为0时表示查看目录或者首页"`
-}
-
-// 根据用户id字符串获取用户的浏览数
-type UserViewTotalSlice struct {
-	UserId      int       `description:"用户id"`
-	Total       int       `description:"总阅读数"`
-	CreatedTime time.Time `description:"用户浏览时间"`
-}
-
-func GetCountUserViewHistoryByUserIds(userIds string) (items []*UserViewTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(1) total,user_id,max(created_time) as created_time FROM user_view_history WHERE user_id in (` + userIds + `) group by user_id`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-	//return items2,err
-}
-
-// 根据用户手机号字符串获取用户的浏览数
-type UserViewMobileTotalSlice struct {
-	Mobile      string    `description:"用户手机号"`
-	Total       int       `description:"总阅读数"`
-	CreatedTime time.Time `description:"用户浏览时间"`
-}
-
-func GetCountUserViewHistoryByMobiles(mobiles string) (items []*UserViewMobileTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(1) total,mobile,max(created_time) as created_time FROM user_view_history WHERE mobile in (` + mobiles + `) group by mobile`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// 根据用户id字符串获取用户的浏览数
-type UserViewEmailTotalSlice struct {
-	Email       string    `description:"用户邮箱"`
-	Total       int       `description:"总阅读数"`
-	CreatedTime time.Time `description:"用户浏览时间"`
-}
-
-func GetCountUserViewHistoryByEmails(emails string) (items []*UserViewEmailTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(1) total,email,max(created_time) as created_time FROM user_view_history WHERE email in (` + emails + `) group by email`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-	//return items2,err
-}
-
-func GetCountCygxArticleHistoryRecordByMobiles(mobiles string) (items []*UserViewMobileTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(1) total,h.mobile,max(h.create_time) as created_time FROM cygx_article_history_record_all  AS h  INNER JOIN cygx_article  AS art  ON  art.article_id = h.article_id  WHERE h.mobile in (` + mobiles + `) AND h.is_del = 0  AND h.company_id != 16 group by h.mobile`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-func GetCountCygxArticleHistoryRecordByEmails(emails string) (items []*UserViewEmailTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT count(1) total,h.email,max(h.create_time) as created_time FROM cygx_article_history_record_all AS h  INNER JOIN cygx_article  AS art  ON  art.article_id = h.article_id  WHERE h.email in (` + emails + `) AND h.is_del = 0 AND h.company_id != 16 group by email`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// CompanyLastViewSlice 根据手机号获取客户的最新浏览时间
-type CompanyLastViewSlice struct {
-	CompanyId int       `description:"客户id"`
-	ViewTime  time.Time `description:"用户浏览时间"`
-}
-
-// GetLastUserViewHistoryByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastUserViewHistoryByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.created_time) view_time
-FROM
-	wx_user a
-	JOIN user_view_history b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and b.created_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastUserViewHistoryByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastUserViewHistoryByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	//	sql := `SELECT
-	//	a.company_id ,max(b.created_time) view_time
-	//FROM
-	//	wx_user a
-	//	JOIN user_view_history b ON a.email = b.email
-	//WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""  and b.created_time>=?  GROUP BY company_id`
-
-	sql := `SELECT
-	a.company_id ,max(b.created_time) view_time FROM wx_user a
-	JOIN user_view_history b ON a.email = b.email 
-WHERE b.email !="" and b.mobile=""  and b.created_time>=?  GROUP BY company_id`
-
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastAdvisoryArticleViewRecordByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastAdvisoryArticleViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN advisory_user_chart_article_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and b.create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastAdvisoryArticleViewRecordByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastAdvisoryArticleViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN advisory_user_chart_article_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""  and b.create_time>=?  GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastCygxArticleViewRecordByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastCygxArticleViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	o := orm.NewOrm()
-	//dataName := ""
-	//if utils.RunMode == "debug" {
-	//	dataName = "test_v2_hongze_rddp"
-	//} else {
-	//	dataName = "hongze_rddp"
-	//}
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN cygx_article_history_record_newpv b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" GROUP BY company_id`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetLastCygxArticleViewRecordByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastCygxArticleViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN cygx_article_history_record_newpv b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""   GROUP BY company_id`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetLastReportViewRecordByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastReportViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and b.create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastReportViewRecordByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastReportViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-	sql := `SELECT	a.company_id ,max(b.create_time) view_time FROM wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""   and b.create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastUserViewStatisticsByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastUserViewStatisticsByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.last_view_time) view_time
-FROM
-	wx_user a
-	JOIN user_view_statistics b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and a.mobile !="" and b.mobile !="" and b.date<=? GROUP BY a.company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetLastUserViewStatisticsByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastUserViewStatisticsByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,max(b.last_view_time) view_time
-FROM
-	wx_user a
-	JOIN user_view_statistics b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and a.email !="" and b.email !="" and a.mobile="" and b.mobile="" and b.date<=? GROUP BY a.company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// CompanyViewTotalSlice 获取客户的浏览次数
-type CompanyViewTotalSlice struct {
-	CompanyId int `description:"客户id"`
-	ViewTotal int `description:"用户浏览次数"`
-}
-
-// GetCountUserViewHistoryByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetCountUserViewHistoryByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,count(1) view_total FROM 	wx_user a
-	JOIN user_view_history b ON a.mobile = b.mobile 
-WHERE 	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and b.created_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetCountUserViewHistoryByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetCountUserViewHistoryByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	//	sql := `SELECT
-	//	a.company_id ,count(1) view_total
-	//FROM
-	//	wx_user a
-	//	JOIN user_view_history b ON a.email = b.email
-	//WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""  and b.created_time>=? GROUP BY company_id`
-
-	sql := `SELECT a.company_id ,count(1) view_total FROM wx_user a 
-JOIN user_view_history b ON a.email = b.email 
-WHERE  b.email !="" and b.mobile=""  and b.created_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetCountAdvisoryArticleViewRecordByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetCountAdvisoryArticleViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN advisory_user_chart_article_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetCountAdvisoryArticleViewRecordByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetCountAdvisoryArticleViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN advisory_user_chart_article_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetCountCygxArticleViewRecordByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetCountCygxArticleViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	o := orm.NewOrm()
-	//dataName := ""
-	//if utils.RunMode == "debug" {
-	//	dataName = "test_v2_hongze_rddp"
-	//} else {
-	//	dataName = "hongze_rddp"
-	//}
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN cygx_article_history_record_newpv b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" GROUP BY company_id`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetCountCygxArticleViewRecordByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetCountCygxArticleViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN cygx_article_history_record_newpv b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile="" GROUP BY company_id`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
-// GetCountReportViewRecordByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetCountReportViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetCountReportViewRecordByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetCountReportViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-	sql := `SELECT	a.company_id ,count(1) view_total FROM wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetUserViewStatisticsByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetUserViewStatisticsByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,sum(b.view_num) view_total
-FROM
-	wx_user a
-	JOIN user_view_statistics b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and a.mobile !="" and b.mobile !="" and date<=? GROUP BY a.company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// GetUserViewStatisticsByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetUserViewStatisticsByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	sql := `SELECT
-	a.company_id ,sum(b.view_num) view_total
-FROM
-	wx_user a
-	JOIN user_view_statistics b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and a.email !="" and b.email !="" and a.mobile="" and b.mobile="" and date<=? GROUP BY a.company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
-	return
-}
-
-// UserViewStatisticsInfo 根据用户手机号字符串获取用户的浏览数和最晚阅读次数
-type UserViewStatisticsInfo struct {
-	Mobile       string    `description:"用户手机号"`
-	Total        int       `description:"总阅读数"`
-	LastViewTime time.Time `description:"用户浏览时间"`
-}
-
-// GetUserViewStatisticsByMobile 根据手机号获取联系人的浏览次数
-func GetUserViewStatisticsByMobile(mobile string) (item *UserViewStatisticsInfo, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT mobile,sum(view_num) total,max(last_view_time) last_view_time FROM  user_view_statistics  WHERE mobile = ? `
-	err = o.Raw(sql, mobile).QueryRow(&item)
-	return
-}
-
 type ResearchReportViewPUV struct {
 	ResearchReportId int
 	Pv               int

+ 0 - 444
models/wechat_send_msg.go

@@ -1,248 +1,9 @@
 package models
 
 import (
-	"eta/eta_mobile/utils"
 	"github.com/beego/beego/v2/client/orm"
-	"strings"
 )
 
-type OpenIdList struct {
-	OpenId string
-	UserId int
-}
-
-func GetOpenIdList() (items []*OpenIdList, err error) {
-	//openIdstr := WxUsersGet()
-	//sql:=` SELECT DISTINCT open_id FROM wx_user AS wu
-	//      INNER JOIN company AS c ON c.company_id = wu.company_id
-	//      INNER JOIN company_product AS d ON c.company_id=d.company_id
-	//      WHERE wu.open_id IS NOT NULL AND  d.status IN('正式','试用','永续') `
-	sql := `SELECT DISTINCT ur.open_id,wu.user_id FROM wx_user AS wu 
-          INNER JOIN company AS c ON c.company_id = wu.company_id 
-          INNER JOIN company_product AS d ON c.company_id=d.company_id
-		INNER join user_record  as ur on wu.user_id=ur.user_id
-          WHERE ur.open_id != "" AND ur.subscribe=1 and ur.create_platform=1 AND  d.status IN('正式','试用','永续') `
-	//if openIdstr != "" {
-	//	sql += ` AND ur.open_id in (` + openIdstr + `) `
-	//}
-	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
-	return
-}
-
-func GetOpenIdListByMobile(mobile string) (items []*OpenIdList, err error) {
-	//openIdstr := WxUsersGet()
-	sql := `SELECT DISTINCT ur.open_id,wu.user_id FROM wx_user AS wu 
-          INNER JOIN company AS c ON c.company_id = wu.company_id 
-          INNER join user_record  as ur on wu.user_id=ur.user_id
-          WHERE ur.open_id != "" AND ur.subscribe=1 and ur.create_platform=1 AND wu.mobile=? `
-	//if openIdstr != "" {
-	//	sql += ` AND ur.open_id in (` + openIdstr + `) `
-	//}
-	_, err = orm.NewOrm().Raw(sql, mobile).QueryRows(&items)
-	return
-}
-
-// 获取预约活动的用户的openID
-func GetActivityOpenIdList(activityId int) (items []*OpenIdList, err error) {
-	sql := `SELECT DISTINCT cr.open_id,u.user_id
-			FROM
-			cygx_my_schedule AS m
-			INNER JOIN user_record AS u ON u.bind_account = m.mobile 
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			WHERE m.activity_id = ? AND u.create_platform = 4 `
-	_, err = orm.NewOrm().Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取预约活动的用户的openID测试环境
-func GetActivityOpenIdListByDeBug(activityId int) (items []*OpenIdList, err error) {
-	sql := `SELECT
-			u.open_id,
-			u.user_id 
-		FROM
-			cygx_my_schedule AS s
-			INNER JOIN wx_user AS wx ON wx.user_id = s.user_id
-			INNER JOIN user_record AS u ON u.bind_account = wx.mobile
-			INNER JOIN company_product AS p ON p.company_id = wx.company_id 
-		WHERE
-			s.activity_id = ? 
-			AND u.create_platform = 1 
-			AND p.STATUS IN ( '正式', '试用', '永续' ) 
-		GROUP BY
-			u.open_id`
-	_, err = orm.NewOrm().Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取预约活动的用户的openID
-func GetActivitySpecialOpenIdList() (items []*OpenIdList, err error) {
-	sql := `SELECT DISTINCT cr.open_id,u.user_id
-			FROM
-			cygx_user_follow_special AS m
-			INNER JOIN user_record AS u ON u.bind_account = m.mobile 
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			WHERE  u.create_platform = 4 `
-	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
-	return
-}
-
-// 获取预约活动的用户的openID测试环境
-func GetActivitySpecialOpenIdListByDeBug() (items []*OpenIdList, err error) {
-	sql := `SELECT
-			u.open_id,
-			u.user_id 
-		FROM
-			cygx_user_follow_special AS s
-			INNER JOIN wx_user AS wx ON wx.user_id = s.user_id
-			INNER JOIN user_record AS u ON u.bind_account = wx.mobile
-			INNER JOIN company_product AS p ON p.company_id = wx.company_id 
-		WHERE
-			u.create_platform = 1 
-			AND p.STATUS IN ( '正式', '试用', '永续' ) 
-		GROUP BY
-			u.open_id`
-	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
-	return
-}
-
-// 获取关注作者的用户的openID
-func GetFollowDepartmentOpenIdList(departmentId int) (items []*OpenIdList, err error) {
-	sql := `SELECT cr.open_id,u.user_id
-			FROM
-				cygx_article_department_follow AS f
-				INNER JOIN user_record AS u ON u.bind_account = f.mobile
-				INNER JOIN wx_user AS wx ON wx.user_id = f.user_id
-				INNER JOIN company_product AS p ON p.company_id = wx.company_id 
-				INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			WHERE
-				f.department_id = ?
-				AND u.create_platform = 4 
-				AND f.type = 1 
-				AND p.status IN ('正式','试用','永续')
-			GROUP BY
-				cr.open_id `
-	_, err = orm.NewOrm().Raw(sql, departmentId).QueryRows(&items)
-	return
-}
-
-// 获取关注作者的用户的openID测试环境
-func GetFollowDepartmentOpenIdListByDeBug(departmentId int) (items []*OpenIdList, err error) {
-	sql := `SELECT
-			u.open_id,
-			u.user_id 
-		FROM
-			cygx_article_department_follow AS f
-			INNER JOIN wx_user AS wx ON wx.user_id = f.user_id
-			INNER JOIN user_record AS u ON u.bind_account = wx.mobile
-			INNER JOIN company_product AS p ON p.company_id = wx.company_id
-		WHERE
-			f.department_id = ? 
-			AND u.create_platform = 1
-			AND f.type = 1 
-			AND p.STATUS IN ( '正式', '试用', '永续' ) 
-		GROUP BY
-			u.open_id`
-	_, err = orm.NewOrm().Raw(sql, departmentId).QueryRows(&items)
-	return
-}
-
-// 获取关注产业的用户的openID
-func GetFollowindustrialOpenIdList(industrialManagementId int) (items []*OpenIdList, err error) {
-	sql := `SELECT cr.open_id,u.user_id
-			FROM
-			cygx_industry_fllow AS f
-			INNER JOIN wx_user AS wx ON wx.user_id = f.user_id
-			INNER JOIN user_record AS u ON u.bind_account = wx.mobile 
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			WHERE
-			f.industrial_management_id = ? 
-			AND u.create_platform = 4 
-			AND f.type = 1 GROUP BY cr.open_id `
-	_, err = orm.NewOrm().Raw(sql, industrialManagementId).QueryRows(&items)
-	return
-}
-
-// 获取关注产业的用户的openID 测试环境
-func GetFollowindustrialOpenIdListByDeBug(industrialManagementId int) (items []*OpenIdList, err error) {
-	sql := `SELECT
-			u.open_id,
-			u.user_id 
-		FROM
-			cygx_industry_fllow AS f
-			INNER JOIN wx_user AS wx ON wx.user_id = f.user_id
-			INNER JOIN user_record AS u ON u.bind_account = wx.mobile
-		WHERE
-			f.industrial_management_id = ? 
-			AND u.create_platform = 1 
-			AND u.bind_account != ""
-			AND f.type = 1 
-		GROUP BY
-			u.open_id`
-	_, err = orm.NewOrm().Raw(sql, industrialManagementId).QueryRows(&items)
-	return
-}
-
-// GetUserOpenidListByUserIds 根据用户id字符串集合来获取他的openid列表集合
-func GetUserOpenidListByUserIds(userIdStr []string) (list []*OpenIdList, err error) {
-	if len(userIdStr) <= 0 {
-		return
-	}
-	sql := `SELECT open_id,u.user_id FROM user_record WHERE user_id in (` + strings.Join(userIdStr, ",") + `) and create_platform = 1`
-	_, err = orm.NewOrm().Raw(sql).QueryRows(&list)
-	return
-}
-
-func GetAdminOpenIdByMobile(mobile string) (items []*OpenIdList, err error) {
-	sql := `SELECT DISTINCT ur.open_id,wu.user_id FROM wx_user AS wu 
-          INNER JOIN company AS c ON c.company_id = wu.company_id 
-          INNER join user_record  as ur on wu.user_id=ur.user_id
-          WHERE ur.open_id != "" and ur.create_platform=1 AND wu.mobile=? `
-	_, err = orm.NewOrm().Raw(sql, mobile).QueryRows(&items)
-	return
-}
-
-// 根据手机号获取用户的openid查研观向小助手专用
-func GetUserRecordListByMobile(platform int, bindAccount string) (items []*OpenIdList, err error) {
-	var sql string
-	if utils.RunMode == "release" {
-		sql = `SELECT cr.open_id FROM user_record  as u 
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			WHERE create_platform=? AND bind_account IN (` + bindAccount + `)`
-	} else {
-		platform = 1
-		sql = `SELECT open_id FROM	user_record  WHERE create_platform =? AND bind_account IN (` + bindAccount + `)`
-	}
-	_, err = orm.NewOrm().Raw(sql, platform).QueryRows(&items)
-	return
-}
-
-// 获取单个用户openid
-func GetCompanyDetailByIdGroup(platform int, bindAccount string) (item *OpenIdList, err error) {
-	o := orm.NewOrm()
-	var sql string
-	sql = `SELECT cr.open_id,wu.user_id FROM user_record  as u 
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id 
-			INNER JOIN wx_user AS wu ON wu.mobile = u.bind_account 
-			WHERE create_platform=? AND u.bind_account = ?`
-	err = o.Raw(sql, platform, bindAccount).QueryRow(&item)
-	return
-}
-
-// 获取小助手所有的用户的openid
-func GetCygxUserAllOpneid() (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT
-			cr.open_id,
-			r.user_id 
-		FROM
-			user_record AS r
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = r.union_id 
-		WHERE
-			r.create_platform = 4`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
 func GetOpenIdArr() (items []string, err error) {
 	sql := ` SELECT DISTINCT ur.open_id FROM wx_user AS wu 
           INNER JOIN company AS c ON c.company_id = wu.company_id 
@@ -254,182 +15,6 @@ func GetOpenIdArr() (items []string, err error) {
 	return
 }
 
-// 获取预约活动的用户的openID测试环境
-func GetActivitySpecialOpenIdListMobile(condition string, pars []interface{}) (items []*OpenIdList, err error) {
-	sql := `SELECT
-			cr.open_id,
-			u.user_id
-		FROM
-			company_report_permission AS p
-			INNER JOIN wx_user AS u ON u.company_id = p.company_id
-			INNER JOIN user_record AS r ON r.user_id = u.user_id
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = r.union_id 
-		WHERE
-			 r.create_platform = 4  AND p.STATUS IN ('正式','试用','永续')  ` + condition + ` GROUP BY cr.open_id`
-	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&items)
-	return
-}
-
-// 获取所有关注了该产业用户的openid
-func GetCygxUserIndustryFllowOpneid(IndustrialManagementId int) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT
-			cr.open_id,
-			r.user_id 
-		FROM
-			user_record AS r
-			INNER JOIN cygx_user_record AS cr ON cr.union_id = r.union_id 
-			INNER join cygx_industry_fllow  as cf on cf.user_id = r.user_id 
-		WHERE
-			r.create_platform = 4
-			AND cf.industrial_management_id = ?`
-	_, err = o.Raw(sql, IndustrialManagementId).QueryRows(&items)
-	return
-}
-
-// 获取所有关注了该产业用户的openid
-func GetCygxUserIndustryFllowOpneidByActivityIds(activityId int) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	cr.open_id,
-	r.user_id 
-FROM
-	cygx_industrial_activity_group_management AS agm
-	INNER JOIN cygx_industry_fllow AS f ON f.industrial_management_id = agm.industrial_management_id
-	INNER JOIN user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-WHERE
-	agm.activity_id = ? 
-	AND cr.union_id = r.union_id 
-	AND r.create_platform = 4 
-	AND r.user_id = f.user_id;`
-	_, err = o.Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取所有关注了该产业永续客户的openid
-func GetCygxForeverUserIndustryFllowOpneidByActivityIds(activityId int) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	cr.open_id,
-	r.user_id 
-FROM
-	cygx_industrial_activity_group_management AS agm
-	INNER JOIN cygx_industry_fllow AS f ON f.industrial_management_id = agm.industrial_management_id
-	INNER JOIN user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-	INNER JOIN wx_user AS wx ON wx.user_id = r.user_id 
-	INNER JOIN company_product AS p ON p.company_id = wx.company_id 
-WHERE
-	agm.activity_id = ? 
-	AND cr.union_id = r.union_id 
-	AND r.create_platform = 4 
-	AND r.user_id = f.user_id
-	AND p.status = "永续";`
-	_, err = o.Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取所有关注了该产业试用客户的openid
-func GetCygxTryOutUserIndustryFllowOpneidByActivityIds(activityId int) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	cr.open_id,
-	r.user_id 
-FROM
-	cygx_industrial_activity_group_management AS agm
-	INNER JOIN cygx_industry_fllow AS f ON f.industrial_management_id = agm.industrial_management_id
-	INNER JOIN user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-	INNER JOIN wx_user AS wx ON wx.user_id = r.user_id 
-	INNER JOIN company_product AS p ON p.company_id = wx.company_id 
-WHERE
-	agm.activity_id = ? 
-	AND cr.union_id = r.union_id 
-	AND r.create_platform = 4 
-	AND r.user_id = f.user_id
-	AND p.status = "试用";`
-	_, err = o.Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取所有关注了该产业用户的companyIds
-func GetCygxIndustryFollowCompanyIdsByActivityId(activityId int) (item *string, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	GROUP_CONCAT( DISTINCT f.company_id SEPARATOR ',' ) AS company_ids
-FROM
-	cygx_industrial_activity_group_management AS agm
-	INNER JOIN cygx_industry_fllow AS f ON f.industrial_management_id = agm.industrial_management_id
-	INNER JOIN user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-WHERE
-	agm.activity_id = ? 
-	AND r.create_platform = 4 
-	AND r.user_id = f.user_id;`
-	err = o.Raw(sql, activityId).QueryRow(&item)
-	return
-}
-
-// 获取所有关注了该产业用户的openidBy公司id
-func GetCygxUserIndustryFllowOpneidByActivityIdAndCompanyIds(activityId int, companyIds string) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	cr.open_id,
-	r.user_id 
-FROM
-	cygx_industrial_activity_group_management AS agm
-	INNER JOIN cygx_industry_fllow AS f ON f.industrial_management_id = agm.industrial_management_id
-	INNER JOIN user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-WHERE
-	agm.activity_id = ? 
-	AND cr.union_id = r.union_id 
-	AND r.create_platform = 4 
-	AND r.user_id = f.user_id
-	AND f.company_id IN (` + companyIds + `);`
-	_, err = o.Raw(sql, activityId).QueryRows(&items)
-	return
-}
-
-// 获取所有互动过的用户id
-func GetCygxInteractiveUserByActivityId(activityId int) (items []*int, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT user_id FROM cygx_activity_signup WHERE activity_id =? AND fail_type = 0
-UNION ALL
-SELECT user_id FROM cygx_activity_appointment WHERE activity_id = ?
-UNION ALL
-SELECT user_id FROM cygx_activity_meeting_reminder WHERE activity_id = ?
-UNION ALL
-SELECT user_id FROM cygx_activity_help_ask  WHERE activity_id = ? `
-	_, err = o.Raw(sql, activityId, activityId, activityId, activityId).QueryRows(&items)
-	return
-}
-
-// 获取所有用户的openid
-func GetCygxUserOpneidByUserIds(userIds string) (items []*OpenIdList, err error) {
-	o := orm.NewOrm()
-	sql := `			
-SELECT
-	cr.open_id,
-	r.user_id 
-FROM
-	user_record AS r
-	INNER JOIN cygx_user_record AS cr 
-WHERE
-	cr.union_id = r.union_id 
-	AND r.create_platform = 4 
-	AND r.user_id IN (` + userIds + `);`
-	_, err = o.Raw(sql).QueryRows(&items)
-	return
-}
-
 func GetOpenIdArrByClassifyNameSecond(classifyNameSecond string) (items []string, err error) {
 	sql := ` SELECT DISTINCT ur.open_id FROM wx_user AS wu 
 			INNER JOIN company AS c ON c.company_id = wu.company_id 
@@ -445,32 +30,3 @@ func GetOpenIdArrByClassifyNameSecond(classifyNameSecond string) (items []string
 	_, err = orm.NewOrm().Raw(sql, classifyNameSecond).QueryRows(&items)
 	return
 }
-
-func GetOpenIdArrByChartPermissionIds(chartPermissionIds string) (items []string, err error) {
-	sql := ` SELECT DISTINCT ur.open_id FROM wx_user AS wu 
-INNER JOIN company AS c ON c.company_id = wu.company_id 
-INNER JOIN company_product AS d ON c.company_id=d.company_id
-INNER JOIN user_record  AS ur ON wu.user_id=ur.user_id
-INNER JOIN company_report_permission AS e ON d.company_id=e.company_id
-INNER JOIN chart_permission AS f ON e.chart_permission_id=f.chart_permission_id
-WHERE ur.open_id != "" AND ur.subscribe=1 AND ur.create_platform=1 AND  d.status IN('正式','试用','永续')
-AND f.chart_permission_id IN(` + chartPermissionIds + `)
-ORDER BY FIELD(c.company_id, 16) DESC, ur.user_record_id ASC  `
-	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
-	return
-}
-
-func GetOpenIdArrByVarietyTag(varietyTagId int) (items []string, err error) {
-	sql := ` SELECT DISTINCT ur.open_id FROM wx_user AS wu 
-INNER JOIN company AS c ON c.company_id = wu.company_id 
-INNER JOIN company_product AS d ON c.company_id=d.company_id
-INNER JOIN user_record  AS ur ON wu.user_id=ur.user_id
-INNER JOIN company_report_permission AS e ON d.company_id=e.company_id
-INNER JOIN chart_permission AS f ON e.chart_permission_id=f.chart_permission_id
-INNER JOIN variety_tag AS g ON f.chart_permission_id=g.chart_permission_id
-WHERE ur.open_id != "" AND ur.subscribe=1 AND ur.create_platform=1 AND  d.status IN('正式','试用','永续')
-AND g.variety_tag_id=?
-ORDER BY FIELD(c.company_id, 16) DESC, ur.user_record_id ASC  `
-	_, err = orm.NewOrm().Raw(sql, varietyTagId).QueryRows(&items)
-	return
-}

+ 72 - 0
routers/commentsRouter.go

@@ -349,6 +349,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateBatchEdit",
+            Router: `/edb_info/calculate/batch/edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
         beego.ControllerComments{
             Method: "CalculateBatchReset",
@@ -358,6 +367,60 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateBatchSave",
+            Router: `/edb_info/calculate/batch/save`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "BatchCalculateBatchSave",
+            Router: `/edb_info/calculate/batch/save/batch`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateComputeCorrelation",
+            Router: `/edb_info/calculate/compute_correlation`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateDetail",
+            Router: `/edb_info/calculate/detail`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateEdit",
+            Router: `/edb_info/calculate/edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "CalculateSave",
+            Router: `/edb_info/calculate/save`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
         beego.ControllerComments{
             Method: "EdbInfoData",
@@ -385,6 +448,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:ChartInfoController"],
+        beego.ControllerComments{
+            Method: "EdbInfoReplace",
+            Router: `/edb_info/replace`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:EdbClassifyController"] = append(beego.GlobalControllerRouter["eta/eta_mobile/controllers/data_manage:EdbClassifyController"],
         beego.ControllerComments{
             Method: "AddEdbClassify",

+ 89 - 0
services/data/base_edb_lib.go

@@ -3,6 +3,7 @@ package data
 import (
 	"encoding/json"
 	"eta/eta_mobile/models"
+	"eta/eta_mobile/models/data_manage"
 	"eta/eta_mobile/utils"
 	"fmt"
 	"io/ioutil"
@@ -74,6 +75,17 @@ func AddEdbData(source int, edbCode string) (resp *models.BaseResponse, err erro
 	return
 }
 
+type AddPredictEdbDataResponse struct {
+	Ret         int
+	Msg         string
+	ErrMsg      string
+	ErrCode     string
+	Data        data_manage.AddEdbInfoResp
+	Success     bool `description:"true 执行成功,false 执行失败"`
+	IsSendEmail bool `json:"-" description:"true 发送邮件,false 不发送邮件"`
+	IsAddLog    bool `json:"-" description:"true 新增操作日志,false 不新增操作日志" `
+}
+
 // RefreshEdbData 刷新指标数据
 func RefreshEdbData(edbInfoId, source int, edbCode, startDate string) (resp *models.BaseResponse, err error) {
 	param := make(map[string]interface{})
@@ -163,6 +175,68 @@ func RefreshPredictEdbCalculateData(edbInfoId int, edbCode, startDate string) (r
 	return
 }
 
+// AddEdbCalculateData 新增 累计值转月-同比值-同差等计算新增
+func AddEdbCalculateData(edbInfoCalculateBatchSaveReqStr string) (resp *AddPredictEdbDataResponse, err error) {
+	_, resultByte, err := postAddEdbData(edbInfoCalculateBatchSaveReqStr, "calculate/add")
+	err = json.Unmarshal(resultByte, &resp)
+	if err != nil {
+		return
+	}
+	return
+}
+
+// EditEdbCalculateData 编辑 累计值转月-同比值-同差等计算新增
+func EditEdbCalculateData(edbInfoCalculateBatchSaveReqStr string) (resp *AddPredictEdbDataResponse, err error) {
+	_, resultByte, err := postAddEdbData(edbInfoCalculateBatchSaveReqStr, "calculate/edit")
+	err = json.Unmarshal(resultByte, &resp)
+	if err != nil {
+		return
+	}
+	return
+}
+
+// BatchSaveEdbCalculateData 新增 累计值转月-同比值-同差等计算新增
+func BatchSaveEdbCalculateData(edbInfoCalculateBatchSaveReqStr string) (resp *AddPredictEdbDataResponse, err error) {
+	_, resultByte, err := postAddEdbData(edbInfoCalculateBatchSaveReqStr, "calculate/batch/save")
+	err = json.Unmarshal(resultByte, &resp)
+	if err != nil {
+		return
+	}
+	return
+}
+
+// BatchEditEdbCalculateData 编辑 累计值转月-同比值-同差等计算新增
+func BatchEditEdbCalculateData(edbInfoCalculateBatchSaveReqStr string) (resp *AddPredictEdbDataResponse, err error) {
+	_, resultByte, err := postAddEdbData(edbInfoCalculateBatchSaveReqStr, "calculate/batch/edit")
+	err = json.Unmarshal(resultByte, &resp)
+	if err != nil {
+		return
+	}
+	return
+}
+
+// CalculateComputeCorrelationResp 拟合残差计算相关性的值返回
+type CalculateComputeCorrelationResp struct {
+	Ret         int
+	Msg         string
+	ErrMsg      string
+	ErrCode     string
+	Data        float64
+	Success     bool `description:"true 执行成功,false 执行失败"`
+	IsSendEmail bool `json:"-" description:"true 发送邮件,false 不发送邮件"`
+	IsAddLog    bool `json:"-" description:"true 新增操作日志,false 不新增操作日志" `
+}
+
+// CalculateComputeCorrelation 拟合残差计算相关性的值
+func CalculateComputeCorrelation(edbInfoCalculateBatchSaveReqStr string) (resp *CalculateComputeCorrelationResp, err error) {
+	_, resultByte, err := postAddEdbData(edbInfoCalculateBatchSaveReqStr, "calculate/compute_correlation")
+	err = json.Unmarshal(resultByte, &resp)
+	if err != nil {
+		return
+	}
+	return
+}
+
 // postRefreshEdbData 刷新指标数据
 func postRefreshEdbData(param map[string]interface{}, urlStr string) (resp *models.BaseResponse, err error) {
 	postUrl := utils.EDB_LIB_URL + urlStr
@@ -182,6 +256,21 @@ func postRefreshEdbData(param map[string]interface{}, urlStr string) (resp *mode
 	return resp, nil
 }
 
+// postAddEdbData 新增指标数据
+func postAddEdbData(paramStr string, urlStr string) (resp *models.BaseResponse, result []byte, err error) {
+	postUrl := utils.EDB_LIB_URL + urlStr
+	result, err = HttpPost(postUrl, paramStr, "application/json")
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(result, &resp)
+	if err != nil {
+		return
+	}
+
+	return
+}
+
 func HttpPost(url, postData string, params ...string) ([]byte, error) {
 	body := ioutil.NopCloser(strings.NewReader(postData))
 	client := &http.Client{}

+ 0 - 114
services/data/edb_data.go

@@ -2,7 +2,6 @@ package data
 
 import (
 	"errors"
-	"eta/eta_mobile/models"
 	"eta/eta_mobile/models/data_manage"
 	"eta/eta_mobile/utils"
 	"fmt"
@@ -10,71 +9,6 @@ import (
 	"time"
 )
 
-// EdbDataEdit 指标数据修改
-type EdbDataEdit struct {
-	OldCreateDate string `description:"旧的录入日期"`
-	CreateDate    string `description:"新的录入日期"`
-	TradeCode     string `description:"指标唯一编码"`
-	Close         string `description:"录入值"`
-}
-
-// BatchEdbData 批量修改指标数据
-func BatchEdbData(oldCreateDate, createDate string, list []EdbDataEdit, opUserId int) (failEdbDataList []EdbDataEdit, err error) {
-	if oldCreateDate == createDate { //修改
-		err = errors.New("开始日期与结束日期一致!")
-		return
-	}
-	for _, newEdbData := range list {
-		edbdata := new(models.Edbdata)
-		edbdata.TradeCode = newEdbData.TradeCode
-		edbdata.Dt = newEdbData.CreateDate
-		edbdata.Close = newEdbData.Close
-		edbdata.ModifyTime = time.Now()
-
-		item, err := models.GetDataInfo(newEdbData.TradeCode, createDate)
-		if err != nil && err.Error() != utils.ErrNoRow() {
-			failEdbDataList = append(failEdbDataList, newEdbData)
-			continue
-		}
-		if item == nil {
-			_, err = models.AddEdbdata(edbdata)
-			if err != nil {
-				failEdbDataList = append(failEdbDataList, newEdbData)
-				continue
-			}
-		} else {
-			err = models.EditEdbdata(edbdata)
-			if err != nil {
-				failEdbDataList = append(failEdbDataList, newEdbData)
-				continue
-			}
-		}
-		oldItem, err := models.GetDataInfo(newEdbData.TradeCode, oldCreateDate)
-		if err != nil && err.Error() != utils.ErrNoRow() {
-			failEdbDataList = append(failEdbDataList, newEdbData)
-			continue
-		}
-		if oldItem != nil {
-			record := new(models.EdbdataDeleteRecord)
-			record.TradeCode = oldItem.TradeCode
-			record.Dt = oldItem.Dt
-			record.Close = oldItem.Close
-			record.ModifyTime = oldItem.ModifyTime
-			record.CreateTime = time.Now()
-			record.SysUserId = opUserId
-			_, err = models.AddEdbdataDeleteRecord(record)
-			if err != nil {
-
-				failEdbDataList = append(failEdbDataList, newEdbData)
-				continue
-			}
-			//删除数据
-			models.DeleteEdbData(newEdbData.TradeCode, newEdbData.OldCreateDate)
-		}
-	}
-	return
-}
-
 // GetEdbDataTbz 获取指标的同比值数据
 func GetEdbDataTbz(edbInfo *data_manage.EdbInfo, tmpDataList []*data_manage.EdbDataList, startDateTime time.Time) (dataList []*data_manage.EdbDataList, minValue, maxValue float64, err error) {
 	dataList = make([]*data_manage.EdbDataList, 0)
@@ -357,51 +291,3 @@ func GetDateData(edbInfo *data_manage.EdbInfo, startDate, endDate string) (item
 
 	return
 }
-
-// GetEdbBeforeAndAfterDateData 获取指标的单个日期的值
-func GetEdbBeforeAndAfterDateData(edbInfo *data_manage.EdbInfo, startDate, endDate string, dataType, num int) (list []*data_manage.EdbDataList, err error) {
-	var dataList []*data_manage.EdbDataList
-	switch edbInfo.EdbInfoType {
-	case 0:
-		dataList, err = data_manage.GetEdbDataList(edbInfo.Source, edbInfo.EdbInfoId, startDate, endDate)
-	case 1:
-		_, dataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(edbInfo.EdbInfoId, startDate, endDate, true)
-	default:
-		err = errors.New(fmt.Sprint("获取失败,指标类型异常", edbInfo.EdbInfoType))
-
-	}
-	if err != nil {
-		return
-	}
-
-	lenDataList := len(dataList)
-	if lenDataList <= 0 {
-		return
-	}
-
-	switch dataType {
-	case 1: // 取前面的数据
-		if lenDataList <= 1 { // 如果只有一个,那么也返回,因为自己不算
-			return
-		}
-		if lenDataList <= num {
-			num = lenDataList - 1
-		}
-
-		for i := num; i >= 0; i-- {
-			list = append(list, dataList[lenDataList-1-i])
-		}
-
-	case 2: // 取后面的数据
-		num = num + 1
-		if lenDataList < num {
-			num = lenDataList
-		}
-
-		for i := 0; i < num; i++ {
-			list = append(list, dataList[i])
-		}
-	}
-
-	return
-}

+ 685 - 0
services/data/edb_info_calculate.go

@@ -0,0 +1,685 @@
+package data
+
+import (
+	"errors"
+	"eta/eta_mobile/models/data_manage"
+	"eta/eta_mobile/utils"
+	"fmt"
+	"github.com/shopspring/decimal"
+	"github.com/yidane/formula"
+	"math"
+	"strconv"
+	"strings"
+	"time"
+)
+
+func CheckFormula(formula string) map[string]string {
+	mathFormula := []string{"MAX", "MIN", "ABS", "ACOS", "ASIN", "CEIL", "MOD", "POW", "ROUND", "SIGN", "SIN", "TAN", "LOG10", "LOG2", "LOG", "LN"}
+
+	str := strings.ToUpper(formula)
+	for _, v := range mathFormula {
+		str = strings.Replace(str, v, "", -1)
+	}
+	str = strings.Replace(str, "(", "", -1)
+	str = strings.Replace(str, ")", "", -1)
+
+	byteMap := make(map[string]string)
+	for i := 0; i < len(str); i++ {
+		byteInt := str[i]
+		if byteInt >= 65 && byteInt <= 90 {
+			byteStr := string(byteInt)
+			if _, ok := byteMap[byteStr]; !ok {
+				byteMap[byteStr] = byteStr
+			}
+		}
+	}
+	return byteMap
+}
+
+// CheckFormula2 校验公式是否正常(比如说除法的分母不能为0之类的,实际上就是用预设的字段数据做一次计算)
+func CheckFormula2(edbInfoArr []*data_manage.EdbInfo, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) (ok bool, err error) {
+	valArr := make(map[int]float64)
+	for _, v := range edbInfoArr {
+		valArr[v.EdbInfoId] = 100
+	}
+	formulaStr = strings.ToUpper(formulaStr)
+	formulaFormStr := ReplaceFormula(edbInfoArr, valArr, formulaMap, formulaStr, edbInfoIdBytes)
+	if formulaFormStr == "" {
+		return
+	}
+	expression := formula.NewExpression(formulaFormStr)
+	_, err = expression.Evaluate()
+	if err != nil {
+	} else {
+		ok = true
+	}
+	return
+}
+
+type CalculateItems struct {
+	EdbInfoId int
+	DataMap   map[string]float64
+}
+
+func Calculate(edbInfoIdArr []*data_manage.EdbInfo, edbInfoId int, edbCode, formulaStr string, edbInfoIdBytes []string) (err error) {
+	defer func() {
+		if err != nil {
+			utils.FileLog.Info("Calculate Err:%s" + err.Error())
+		}
+	}()
+	saveDataMap := make(map[string]map[int]float64)
+	for _, v := range edbInfoIdArr {
+		var condition string
+		var pars []interface{}
+		condition += " AND edb_info_id=? "
+		pars = append(pars, v.EdbInfoId)
+		dataList, err := data_manage.GetEdbDataListAll(condition, pars, v.Source, 1)
+		if err != nil {
+			return err
+		}
+		dataMap := make(map[string]float64)
+		for _, dv := range dataList {
+			if val, ok := saveDataMap[dv.DataTime]; ok {
+				if _, ok := val[v.EdbInfoId]; !ok {
+					val[v.EdbInfoId] = dv.Value
+				}
+			} else {
+				temp := make(map[int]float64)
+				temp[v.EdbInfoId] = dv.Value
+				saveDataMap[dv.DataTime] = temp
+			}
+		}
+		item := new(CalculateItems)
+		item.EdbInfoId = v.EdbInfoId
+		item.DataMap = dataMap
+	}
+	formulaMap := CheckFormula(formulaStr)
+	addSql := ` INSERT INTO edb_data_calculate(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	nowStr := time.Now().Format(utils.FormatDateTime)
+	var isAdd bool
+	for sk, sv := range saveDataMap {
+		formulaStr = strings.ToUpper(formulaStr)
+		formulaFormStr := ReplaceFormula(edbInfoIdArr, sv, formulaMap, formulaStr, edbInfoIdBytes)
+		if formulaStr == "" {
+			return
+		}
+		if formulaFormStr != "" {
+			expression := formula.NewExpression(formulaFormStr)
+			calResult, err := expression.Evaluate()
+			if err != nil {
+				err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+			calVal, err := calResult.Float64()
+			if err != nil {
+				err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+
+			//需要存入的数据
+			{
+				dataTime, _ := time.Parse(utils.FormatDate, sk)
+				timestamp := dataTime.UnixNano() / 1e6
+				timeStr := fmt.Sprintf("%d", timestamp)
+				addSql += "("
+				addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + sk + "'" + "," + utils.SubFloatToString(calVal, 4) + "," + "'" + nowStr + "'" +
+					"," + "'" + nowStr + "'" + "," + "1"
+				addSql += "," + "'" + timeStr + "'"
+				addSql += "),"
+				isAdd = true
+			}
+		} else {
+			fmt.Println("formulaFormStr is empty")
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		data_manage.AddEdbDataCalculateBySql(addSql)
+		if err != nil {
+			fmt.Println("AddEdbDataCalculate Err:" + err.Error())
+			return err
+		}
+	}
+	return
+}
+
+func ReplaceFormula(edbInfoIdArr []*data_manage.EdbInfo, valArr map[int]float64, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) string {
+	funMap := GetFormulaMap()
+	for k, v := range funMap {
+		formulaStr = strings.Replace(formulaStr, k, v, -1)
+	}
+	replaceCount := 0
+	for dk, dv := range edbInfoIdArr {
+		if dk == 0 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				} else {
+					fmt.Println("valArr not found:", valArr, valOk)
+				}
+			} else {
+				fmt.Println("formulaMap not found:", dKey, dk)
+			}
+		}
+		if dk == 1 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				} else {
+					fmt.Println("valArr not found:", valArr, valOk)
+				}
+			} else {
+				fmt.Println("formulaMap not found:", dKey, dk)
+			}
+		}
+		if dk == 2 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 3 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 4 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 5 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 6 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 7 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 8 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 9 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 10 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 11 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 12 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 13 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 14 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 15 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 16 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 17 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 18 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 19 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 20 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 21 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 22 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 23 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 24 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+		if dk == 25 {
+			dKey := edbInfoIdBytes[dk]
+			if _, ok := formulaMap[dKey]; ok { //公式中存在
+				if val, valOk := valArr[dv.EdbInfoId]; valOk { //值存在
+					dvStr := fmt.Sprintf("%v", val)
+					formulaStr = strings.Replace(formulaStr, dKey, dvStr, -1)
+					replaceCount++
+				}
+			}
+		}
+	}
+	for k, v := range funMap {
+		formulaStr = strings.Replace(formulaStr, v, k, -1)
+	}
+	if replaceCount == len(formulaMap) {
+		return formulaStr
+	} else {
+		return ""
+	}
+}
+
+func GetFormulaMap() map[string]string {
+	funMap := make(map[string]string)
+	funMap["MAX"] = "[@@]"
+	funMap["MIN"] = "[@!]"
+	funMap["ABS"] = "[@#]"
+	funMap["CEIL"] = "[@$]"
+	funMap["COS"] = "[@%]"
+	funMap["FLOOR"] = "[@^]"
+	funMap["MOD"] = "[@&]"
+	funMap["POW"] = "[@*]"
+	funMap["ROUND"] = "[@(]"
+	return funMap
+}
+
+// 刷新数据
+func RefreshCalculate(edbInfoIdArr []*data_manage.EdbInfo, edbInfoId int, edbCode, formulaStr, startDate, endDate string, edbInfoIdBytes []string) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("RefreshCalculate:Err " + err.Error())
+			utils.FileLog.Info("Calculate Err:%s" + err.Error())
+		}
+	}()
+	saveDataMap := make(map[string]map[int]float64)
+	for _, v := range edbInfoIdArr {
+		var condition string
+		var pars []interface{}
+		condition += " AND edb_info_id=? "
+		pars = append(pars, v.EdbInfoId)
+		if startDate != "" {
+			condition += " AND data_time>=? "
+			pars = append(pars, startDate)
+		}
+		if endDate != "" {
+			condition += " AND data_time<=? "
+			pars = append(pars, endDate)
+		}
+		dataList, err := data_manage.GetEdbDataListAll(condition, pars, v.Source, 1)
+		if err != nil {
+			return err
+		}
+		dataMap := make(map[string]float64)
+		for _, dv := range dataList {
+			if val, ok := saveDataMap[dv.DataTime]; ok {
+				if _, ok := val[v.EdbInfoId]; !ok {
+					val[v.EdbInfoId] = dv.Value
+				}
+			} else {
+				temp := make(map[int]float64)
+				temp[v.EdbInfoId] = dv.Value
+				saveDataMap[dv.DataTime] = temp
+			}
+		}
+		item := new(CalculateItems)
+		item.EdbInfoId = v.EdbInfoId
+		item.DataMap = dataMap
+	}
+
+	formulaMap := CheckFormula(formulaStr)
+	addSql := ` INSERT INTO edb_data_calculate(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
+	nowStr := time.Now().Format(utils.FormatDateTime)
+	var isAdd bool
+
+	for sk, sv := range saveDataMap {
+		formulaStr = strings.ToUpper(formulaStr)
+		formulaFormStr := ReplaceFormula(edbInfoIdArr, sv, formulaMap, formulaStr, edbInfoIdBytes)
+		if formulaFormStr != "" {
+			utils.FileLog.Info("formulaFormStr:%s", formulaFormStr)
+			expression := formula.NewExpression(formulaFormStr)
+			calResult, err := expression.Evaluate()
+			if err != nil {
+				err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+			calVal, err := calResult.Float64()
+			if err != nil {
+				err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
+				fmt.Println(err)
+				return err
+			}
+
+			count, err := data_manage.GetEdbDataCalculateByCodeAndDate(edbCode, sk)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				return err
+			}
+			if count <= 0 { //需要存入的数据
+				dataTime, _ := time.Parse(utils.FormatDate, sk)
+				timestamp := dataTime.UnixNano() / 1e6
+				timeStr := fmt.Sprintf("%d", timestamp)
+				addSql += "("
+				addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + sk + "'" + "," + utils.SubFloatToString(calVal, 4) + "," + "'" + nowStr + "'" +
+					"," + "'" + nowStr + "'" + "," + "1"
+				addSql += "," + "'" + timeStr + "'"
+				addSql += "),"
+				isAdd = true
+			} else {
+				calVal = utils.FixFloat(calVal, 4)
+				err = data_manage.ModifyEdbDataCalculate(int64(edbInfoId), sk, calVal)
+				if err != nil {
+					return err
+				}
+			}
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		data_manage.AddEdbDataCalculateBySql(addSql)
+		if err != nil {
+			fmt.Println("AddEdbDataCalculate Err:" + err.Error())
+			return err
+		}
+	}
+	return
+}
+
+// 处理整个数据
+func handleDateSaveDataMap(dateList []string, realSaveDataMap, saveDataMap map[string]map[int]float64, edbInfoIdArr []*data_manage.EdbInfo) {
+	for _, date := range dateList {
+		tmpDataMap := realSaveDataMap[date]
+		for _, edbInfo := range edbInfoIdArr {
+			tmpEdbInfoId := edbInfo.EdbInfoId // 当前指标id
+			// 如果该日期不存在该指标数据,那么需要找寻前后日期的数据,进行填补
+			if _, ok := tmpDataMap[tmpEdbInfoId]; !ok {
+				//day := 0
+				//switch edbInfo.Frequency {
+				//case "周度":
+				//	day = 7
+				//case "旬度":
+				//	day = 15
+				//case "月度":
+				//	day = 30
+				//case "季度":
+				//	day = 90
+				//case "年度":
+				//	day = 365
+				//}
+				// 需求池 255 指标运算文案修改,补数据遍历区间修改(2023-3-7 09:37:23修改)
+				day := 35
+				handleDateDataMap(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, day)
+			}
+		}
+	}
+}
+
+// handleDataMap 处理单个日期的数据
+func handleDateDataMap(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId, day int) {
+	currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
+
+	// 后一天
+	nextDateDayStr := currDate.AddDate(0, 0, 1).Format(utils.FormatDate)
+
+	// 前一天
+	preDateDayStr := currDate.AddDate(0, 0, -1).Format(utils.FormatDate)
+
+	for i := 1; i <= day; i++ {
+
+		// 下个日期的数据
+		{
+			if i >= 1 {
+				nextDateDayStr = currDate.AddDate(0, 0, i).Format(utils.FormatDate)
+			}
+			if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
+				if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
+					saveDataMap[date][edbInfoId] = val
+					return
+				}
+			}
+		}
+
+		// 上个日期的数据
+		{
+			if i >= 1 {
+				preDateDayStr = currDate.AddDate(0, 0, -i).Format(utils.FormatDate)
+			}
+			if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
+				if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
+					saveDataMap[date][edbInfoId] = val
+					return
+				}
+			}
+		}
+	}
+}
+
+// handleDataByLinearRegression 插值法补充数据(线性方程式)
+func handleDataByLinearRegression(edbInfoDataList []*data_manage.EdbDataList, handleDataMap map[string]float64) (err error) {
+	if len(edbInfoDataList) < 2 {
+		return
+	}
+
+	var startEdbInfoData *data_manage.EdbDataList
+	for _, v := range edbInfoDataList {
+		handleDataMap[v.DataTime] = v.Value
+
+		// 第一个数据就给过滤了,给后面的试用
+		if startEdbInfoData == nil {
+			startEdbInfoData = v
+			continue
+		}
+
+		// 获取两条数据之间相差的天数
+		startDataTime, _ := time.ParseInLocation(utils.FormatDate, startEdbInfoData.DataTime, time.Local)
+		currDataTime, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
+		betweenHour := int(currDataTime.Sub(startDataTime).Hours())
+		betweenDay := betweenHour / 24
+
+		// 如果相差一天,那么过滤
+		if betweenDay <= 1 {
+			startEdbInfoData = v
+			continue
+		}
+
+		// 生成线性方程式
+		var a, b float64
+		{
+			coordinateData := make([]utils.Coordinate, 0)
+			tmpCoordinate1 := utils.Coordinate{
+				X: 1,
+				Y: startEdbInfoData.Value,
+			}
+			coordinateData = append(coordinateData, tmpCoordinate1)
+			tmpCoordinate2 := utils.Coordinate{
+				X: float64(betweenDay) + 1,
+				Y: v.Value,
+			}
+			coordinateData = append(coordinateData, tmpCoordinate2)
+
+			a, b = utils.GetLinearResult(coordinateData)
+			if math.IsNaN(a) || math.IsNaN(b) {
+				err = errors.New("线性方程公式生成失败")
+				return
+			}
+		}
+
+		// 生成对应的值
+		{
+			for i := 1; i < betweenDay; i++ {
+				tmpDataTime := startDataTime.AddDate(0, 0, i)
+				aDecimal := decimal.NewFromFloat(a)
+				xDecimal := decimal.NewFromInt(int64(i) + 1)
+				bDecimal := decimal.NewFromFloat(b)
+
+				val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).Round(4).Float64()
+				handleDataMap[tmpDataTime.Format(utils.FormatDate)] = val
+			}
+		}
+
+		startEdbInfoData = v
+	}
+
+	return
+}

+ 14 - 0
services/data/predict_edb_info.go

@@ -609,3 +609,17 @@ func GetPredictCalculateDataListByPredictEdbInfo(edbInfo *data_manage.EdbInfo, s
 	dataList, err = data_manage.GetEdbDataList(edbInfo.Source, edbInfo.EdbInfoId, startDate, endDate)
 	return
 }
+
+// ModifyPredictEdbBaseInfoBySourceEdb  根据来源ETA指标修改预测指标的基础信息
+func ModifyPredictEdbBaseInfoBySourceEdb(sourceEDdbInfo *data_manage.EdbInfo) {
+	list, err := data_manage.GetGroupPredictEdbBySourceEdbInfoId(sourceEDdbInfo.EdbInfoId)
+	if err != nil {
+		return
+	}
+	for _, v := range list {
+		v.Frequency = sourceEDdbInfo.Frequency
+		v.Unit = sourceEDdbInfo.Unit
+		v.Update([]string{"Frequency", "Unit"})
+		AddOrEditEdbInfoToEs(v.EdbInfoId)
+	}
+}

+ 67 - 67
services/data/predict_edb_info_rule.go

@@ -853,73 +853,73 @@ func GetChartPredictEdbInfoDataListByRuleSeason(edbInfoId int, yearsList []int,
 }
 
 // handleDataByLinearRegression 插值法补充数据(线性方程式)
-func handleDataByLinearRegression(edbInfoDataList []*data_manage.EdbDataList, handleDataMap map[string]float64) (err error) {
-	if len(edbInfoDataList) < 2 {
-		return
-	}
-
-	var startEdbInfoData *data_manage.EdbDataList
-	for _, v := range edbInfoDataList {
-		handleDataMap[v.DataTime] = v.Value
-
-		// 第一个数据就给过滤了,给后面的试用
-		if startEdbInfoData == nil {
-			startEdbInfoData = v
-			continue
-		}
-
-		// 获取两条数据之间相差的天数
-		startDataTime, _ := time.ParseInLocation(utils.FormatDate, startEdbInfoData.DataTime, time.Local)
-		currDataTime, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
-		betweenHour := int(currDataTime.Sub(startDataTime).Hours())
-		betweenDay := betweenHour / 24
-
-		// 如果相差一天,那么过滤
-		if betweenDay <= 1 {
-			startEdbInfoData = v
-			continue
-		}
-
-		// 生成线性方程式
-		var a, b float64
-		{
-			coordinateData := make([]utils.Coordinate, 0)
-			tmpCoordinate1 := utils.Coordinate{
-				X: 1,
-				Y: startEdbInfoData.Value,
-			}
-			coordinateData = append(coordinateData, tmpCoordinate1)
-			tmpCoordinate2 := utils.Coordinate{
-				X: float64(betweenDay) + 1,
-				Y: v.Value,
-			}
-			coordinateData = append(coordinateData, tmpCoordinate2)
-
-			a, b = utils.GetLinearResult(coordinateData)
-			if math.IsNaN(a) || math.IsNaN(b) {
-				err = errors.New("线性方程公式生成失败")
-				return
-			}
-		}
-
-		// 生成对应的值
-		{
-			for i := 1; i < betweenDay; i++ {
-				tmpDataTime := startDataTime.AddDate(0, 0, i)
-				aDecimal := decimal.NewFromFloat(a)
-				xDecimal := decimal.NewFromInt(int64(i) + 1)
-				bDecimal := decimal.NewFromFloat(b)
-
-				val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).Round(4).Float64()
-				handleDataMap[tmpDataTime.Format(utils.FormatDate)] = val
-			}
-		}
-
-		startEdbInfoData = v
-	}
-
-	return
-}
+//func handleDataByLinearRegression(edbInfoDataList []*data_manage.EdbDataList, handleDataMap map[string]float64) (err error) {
+//	if len(edbInfoDataList) < 2 {
+//		return
+//	}
+//
+//	var startEdbInfoData *data_manage.EdbDataList
+//	for _, v := range edbInfoDataList {
+//		handleDataMap[v.DataTime] = v.Value
+//
+//		// 第一个数据就给过滤了,给后面的试用
+//		if startEdbInfoData == nil {
+//			startEdbInfoData = v
+//			continue
+//		}
+//
+//		// 获取两条数据之间相差的天数
+//		startDataTime, _ := time.ParseInLocation(utils.FormatDate, startEdbInfoData.DataTime, time.Local)
+//		currDataTime, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
+//		betweenHour := int(currDataTime.Sub(startDataTime).Hours())
+//		betweenDay := betweenHour / 24
+//
+//		// 如果相差一天,那么过滤
+//		if betweenDay <= 1 {
+//			startEdbInfoData = v
+//			continue
+//		}
+//
+//		// 生成线性方程式
+//		var a, b float64
+//		{
+//			coordinateData := make([]utils.Coordinate, 0)
+//			tmpCoordinate1 := utils.Coordinate{
+//				X: 1,
+//				Y: startEdbInfoData.Value,
+//			}
+//			coordinateData = append(coordinateData, tmpCoordinate1)
+//			tmpCoordinate2 := utils.Coordinate{
+//				X: float64(betweenDay) + 1,
+//				Y: v.Value,
+//			}
+//			coordinateData = append(coordinateData, tmpCoordinate2)
+//
+//			a, b = utils.GetLinearResult(coordinateData)
+//			if math.IsNaN(a) || math.IsNaN(b) {
+//				err = errors.New("线性方程公式生成失败")
+//				return
+//			}
+//		}
+//
+//		// 生成对应的值
+//		{
+//			for i := 1; i < betweenDay; i++ {
+//				tmpDataTime := startDataTime.AddDate(0, 0, i)
+//				aDecimal := decimal.NewFromFloat(a)
+//				xDecimal := decimal.NewFromInt(int64(i) + 1)
+//				bDecimal := decimal.NewFromFloat(b)
+//
+//				val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).Round(4).Float64()
+//				handleDataMap[tmpDataTime.Format(utils.FormatDate)] = val
+//			}
+//		}
+//
+//		startEdbInfoData = v
+//	}
+//
+//	return
+//}
 
 // MoveAverageConf 移动平均同比规则的配置
 type MoveAverageConf struct {

+ 0 - 11
services/wechat_send_msg.go

@@ -13,17 +13,6 @@ import (
 	"strings"
 )
 
-type SendTemplateResponse struct {
-	Errcode int    `json:"errcode"`
-	Errmsg  string `json:"errmsg"`
-	MsgID   int    `json:"msgid"`
-}
-
-type ClearQuotaResponse struct {
-	Errcode int    `json:"errcode"`
-	Errmsg  string `json:"errmsg"`
-}
-
 // SendMiniProgramReportWxMsg 推送报告微信模板消息-小程序链接
 func SendMiniProgramReportWxMsg(reportId int) (err error) {
 	var msg string