123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- package models
- import (
- "errors"
- "fmt"
- "github.com/beego/beego/v2/client/orm"
- "github.com/shopspring/decimal"
- "hongze/hongze_edb_lib/utils"
- "strconv"
- "strings"
- "time"
- )
- // SavePredictCalculateNszydpjjs 新增/编辑 预测 N数值移动平均计算指标
- func SavePredictCalculateNszydpjjs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- fmt.Println("SavePredictCalculateNszydpjjs,Err:" + err.Error())
- _ = to.Rollback()
- } else {
- _ = to.Commit()
- }
- }()
- var formulaInt int
- formulaInt, _ = strconv.Atoi(formula)
- if formulaInt <= 0 {
- err = errors.New("N值输入错误,请重新输入")
- return
- }
- if reqEdbInfoId <= 0 {
- edbInfo = &EdbInfo{
- //EdbInfoId: 0,
- EdbInfoType: 1,
- SourceName: "预测N数值移动平均计算",
- Source: utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS,
- EdbCode: edbCode,
- EdbName: edbName,
- EdbNameSource: edbName,
- Frequency: frequency,
- Unit: unit,
- //StartDate: "",
- //EndDate: "",
- ClassifyId: classifyId,
- SysUserId: sysUserId,
- SysUserRealName: sysUserRealName,
- UniqueCode: uniqueCode,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- MinValue: 0,
- MaxValue: 0,
- CalculateFormula: formula,
- EdbType: 2,
- Sort: 0,
- MoveType: 0,
- MoveFrequency: "",
- NoUpdate: 0,
- ServerUrl: "",
- EdbNameEn: "",
- UnitEn: "",
- LatestDate: "",
- LatestValue: 0,
- ChartImage: "",
- }
- newEdbInfoId, tmpErr := to.Insert(edbInfo)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- edbInfo.EdbInfoId = int(newEdbInfoId)
- // 添加关联关系
- {
- calculateMappingItem := &EdbInfoCalculateMapping{
- EdbInfoCalculateMappingId: 0,
- EdbInfoId: edbInfo.EdbInfoId,
- Source: edbInfo.Source,
- SourceName: edbInfo.SourceName,
- EdbCode: edbCode,
- FromEdbInfoId: fromEdbInfo.EdbInfoId,
- FromEdbCode: fromEdbInfo.EdbCode,
- FromEdbName: fromEdbInfo.EdbName,
- FromSource: fromEdbInfo.Source,
- FromSourceName: fromEdbInfo.SourceName,
- FromTag: "",
- Sort: 1,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- }
- _, err = to.Insert(calculateMappingItem)
- if err != nil {
- return
- }
- }
- } else {
- edbInfo, err = GetEdbInfoById(reqEdbInfoId)
- if err != nil {
- if err.Error() == utils.ErrNoRow() {
- errMsg = `获取指标信息失败`
- }
- return
- }
- if edbInfo.EdbInfoType != 1 {
- errMsg = `该指标不是预测指标`
- err = errors.New(errMsg)
- return
- }
- latestDateStr = edbInfo.LatestDate
- latestValue = edbInfo.LatestValue
- oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
- edbInfo.EdbName = edbName
- edbInfo.EdbNameSource = edbName
- edbInfo.Frequency = frequency
- edbInfo.Unit = unit
- edbInfo.ClassifyId = classifyId
- edbInfo.CalculateFormula = formula
- edbInfo.ModifyTime = time.Now()
- _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
- if err != nil {
- return
- }
- //判断计算指标是否被更换
- var existCondition string
- var existPars []interface{}
- existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
- existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
- latestDateStr = edbInfo.LatestDate
- latestValue = edbInfo.LatestValue
- count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
- if tmpErr != nil {
- err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
- return
- }
- if count > 0 && oldCalculateFormula == formula { // 指标未被替换,同时N值未修改,无需重新计算
- return
- }
- if count <= 0 {
- // 需要删除原先的 计算指标关联的,基础指标的关联关系
- sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
- _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- // 添加新的关联关系
- {
- calculateMappingItem := &EdbInfoCalculateMapping{
- EdbInfoCalculateMappingId: 0,
- EdbInfoId: edbInfo.EdbInfoId,
- Source: edbInfo.Source,
- SourceName: edbInfo.SourceName,
- EdbCode: edbInfo.EdbCode,
- FromEdbInfoId: fromEdbInfo.EdbInfoId,
- FromEdbCode: fromEdbInfo.EdbCode,
- FromEdbName: fromEdbInfo.EdbName,
- FromSource: fromEdbInfo.Source,
- FromSourceName: fromEdbInfo.SourceName,
- FromTag: "",
- Sort: 1,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- }
- _, err = to.Insert(calculateMappingItem)
- if err != nil {
- return
- }
- }
- }
- // 删除该指标所有的同比数据
- dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS)
- deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
- deleteSql = fmt.Sprintf(deleteSql, dataTableName)
- _, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- }
- latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
- return
- }
- // RefreshAllPredictCalculateNszydpjjs 刷新所有 N数值移动平均计算指标 数据
- func RefreshAllPredictCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- fmt.Println("RefreshAllPredictCalculateNszydpjjs,Err:" + err.Error())
- _ = to.Rollback()
- } else {
- _ = to.Commit()
- }
- }()
- latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfoId, source, formulaInt, fromEdbInfo, edbCode, startDate)
- return
- }
- // refreshAllPredictCalculateNszydpjjs 更新全部N数值移动平均计算
- func refreshAllPredictCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
- edbInfoIdStr := strconv.Itoa(edbInfoId)
- fmt.Println(edbInfoIdStr)
- fmt.Println("refreshAllCalculateNszydpjjs startDate:", startDate)
- // 获取关联指标数据
- existDataList := make([]*EdbData, 0)
- dataTableName := GetEdbDataTableName(source)
- fmt.Println("dataTableName:", dataTableName)
- sql := `SELECT * FROM %s WHERE edb_info_id=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
- existDataMap := make(map[string]*EdbData)
- for _, v := range existDataList {
- existDataMap[v.DataTime] = v
- }
- //计算来源数据
- var fromCondition string
- var fromPars []interface{}
- fromCondition += " AND edb_info_id=? "
- fromPars = append(fromPars, fromEdbInfo.EdbInfoId)
- if startDate != `` {
- fromCondition += " AND data_time>=? "
- fromPars = append(fromPars, startDate)
- }
- //fmt.Println("fromPars:", fromPars)
- fromDataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
- if err != nil {
- return
- }
- latestDateStr = fromEdbInfo.LatestDate
- var fromDateArr []string
- fromDataMap := make(map[string]*EdbInfoSearchData)
- for _, v := range fromDataList {
- fromDateArr = append(fromDateArr, v.DataTime)
- fromDataMap[v.DataTime] = v
- }
- addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
- var isAdd bool
- arrLen := len(fromDateArr)
- existAddDataMap := make(map[string]string)
- for ak, av := range fromDateArr {
- //处理第一个值
- var valArr []float64
- if findItem, ok := fromDataMap[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 := fromDateArr[arrIndex]
- if findItem, ok := fromDataMap[arrVal]; ok {
- valArr = append(valArr, findItem.Value)
- } else {
- continue
- }
- }
- }
- valArrLen := len(valArr)
- //var totalVal float64
- 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()
- valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValue = val
- }
- if existVal, existOk := existDataMap[av]; !existOk {
- currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
- isAdd = true
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, _ := decimal.NewFromString(existVal.Value)
- existStr := existValDecimal.String()
- fmt.Println(existStr, valStr, av)
- if existStr != valStr {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- }
- if isAdd {
- addSql = strings.TrimRight(addSql, ",")
- //utils.FileLog.Info("addSql:" + addSql)
- _, err = to.Raw(addSql).Exec()
- if err != nil {
- return
- }
- }
- return
- }
|