base_predict_from_calculate.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "github.com/yidane/formula"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // PredictEdbInfoCalculateSaveReq 预测计算(运算)指标请求参数
  14. type PredictEdbInfoCalculateSaveReq struct {
  15. AdminId int `description:"添加人id"`
  16. AdminName string `description:"添加人名称"`
  17. EdbName string `description:"指标名称"`
  18. Frequency string `description:"频率"`
  19. Unit string `description:"单位"`
  20. ClassifyId int `description:"分类id"`
  21. CalculateFormula string `description:"计算公式"`
  22. EdbInfoIdArr []struct {
  23. EdbInfoId int `description:"指标id"`
  24. FromTag string `description:"指标对应标签"`
  25. }
  26. }
  27. // PredictCalculateItems 预测计算(运算)指标信息
  28. type PredictCalculateItems struct {
  29. EdbInfoId int
  30. DataMap map[string]float64
  31. }
  32. // EditPredictCalculate 新增预测计算(运算)指标
  33. func EditPredictCalculate(edbInfo *EdbInfo, calculateMappingList []*EdbInfoCalculateMapping) (err error) {
  34. o := orm.NewOrm()
  35. to, err := o.Begin()
  36. if err != nil {
  37. return
  38. }
  39. defer func() {
  40. if err != nil {
  41. tmpErr := to.Rollback()
  42. errMsg := fmt.Sprintf("AddPredictCalculate Err:%s" + err.Error())
  43. if tmpErr != nil {
  44. errMsg += `;rollback失败:` + tmpErr.Error()
  45. }
  46. utils.FileLog.Info(errMsg)
  47. return
  48. }
  49. tmpErr := to.Commit()
  50. if tmpErr != nil {
  51. errMsg := fmt.Sprintf("AddPredictCalculate commit Err:%s" + tmpErr.Error())
  52. utils.FileLog.Info(errMsg)
  53. }
  54. }()
  55. // 修改指标信息
  56. _, err = to.Update(edbInfo, "EdbName", "Frequency", "Unit", "ClassifyId", "CalculateFormula")
  57. if err != nil {
  58. return
  59. }
  60. //删除,计算指标关联的,基础指标的关联关系
  61. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  62. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  63. if err != nil {
  64. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  65. return
  66. }
  67. // 插入新的关系表
  68. if len(calculateMappingList) > 0 {
  69. _, err = to.InsertMulti(len(calculateMappingList), calculateMappingList)
  70. }
  71. //数据表
  72. tableName := GetEdbDataTableName(edbInfo.Source)
  73. //清空原有数据
  74. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  75. _, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
  76. if err != nil {
  77. return
  78. }
  79. return
  80. }
  81. func AddPredictCalculateData(edbInfoIdList []*EdbInfo, edbInfo *EdbInfo, edbCode, formulaStr string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  82. o := orm.NewOrm()
  83. to, err := o.Begin()
  84. if err != nil {
  85. return
  86. }
  87. defer func() {
  88. if err != nil {
  89. fmt.Println("AddPredictCalculateData Calculate,Err:" + err.Error())
  90. _ = to.Rollback()
  91. } else {
  92. _ = to.Commit()
  93. }
  94. }()
  95. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfo.EdbInfoId, edbInfo.Source, edbCode, formulaStr, "", edbInfoIdBytes)
  96. return
  97. }
  98. // RefreshAllPredictCalculate 刷新预测计算指标的全部数据
  99. func RefreshAllPredictCalculate(edbInfoIdList []*EdbInfo, edbInfoId, source int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  100. o := orm.NewOrm()
  101. to, err := o.Begin()
  102. if err != nil {
  103. return
  104. }
  105. defer func() {
  106. if err != nil {
  107. fmt.Println("RefreshAllCalculate,Err:" + err.Error())
  108. _ = to.Rollback()
  109. } else {
  110. _ = to.Commit()
  111. }
  112. }()
  113. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfoId, source, edbCode, formulaStr, startDate, edbInfoIdBytes)
  114. return
  115. }
  116. // refreshAllPredictCalculate 刷新预测计算指标的全部数据
  117. func refreshAllPredictCalculate(to orm.TxOrmer, edbInfoIdList []*EdbInfo, edbInfoId, source int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  118. fmt.Println("startDate:", startDate)
  119. // 最小的结束日期 , 最晚的数据开始日期
  120. var minLatestDate, maxStartDate time.Time
  121. dateList := make([]string, 0) // 第一个指标的日期数据
  122. realSaveDataMap := make(map[string]map[int]float64)
  123. saveDataMap := make(map[string]map[int]float64)
  124. for edbInfoIndex, v := range edbInfoIdList {
  125. tmpLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.EndDate, time.Local)
  126. if tmpErr != nil {
  127. err = errors.New(`最近的日期格式化失败;日期:` + v.EndDate + `;err:` + tmpErr.Error())
  128. return
  129. }
  130. if minLatestDate.IsZero() || tmpLatestDate.Before(minLatestDate) {
  131. minLatestDate = tmpLatestDate
  132. }
  133. tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.StartDate, time.Local)
  134. if tmpErr != nil {
  135. err = errors.New(`最近的日期格式化失败;日期:` + v.StartDate + `;err:` + tmpErr.Error())
  136. return
  137. }
  138. if maxStartDate.IsZero() || maxStartDate.Before(tmpStartDate) {
  139. maxStartDate = tmpStartDate
  140. }
  141. // 获取关联指标数据
  142. dataList, tmpErr := GetPredictEdbDataListAllByStartDate(v, 1, startDate)
  143. if tmpErr != nil {
  144. err = tmpErr
  145. return
  146. }
  147. for _, dv := range dataList { // 现有实际数据
  148. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  149. if _, ok := val[v.EdbInfoId]; !ok {
  150. val[v.EdbInfoId] = dv.Value
  151. }
  152. } else {
  153. temp := make(map[int]float64)
  154. temp[v.EdbInfoId] = dv.Value
  155. realSaveDataMap[dv.DataTime] = temp
  156. }
  157. // 待处理的数据
  158. if val, ok := saveDataMap[dv.DataTime]; ok {
  159. if _, ok := val[v.EdbInfoId]; !ok {
  160. val[v.EdbInfoId] = dv.Value
  161. }
  162. } else {
  163. temp := make(map[int]float64)
  164. temp[v.EdbInfoId] = dv.Value
  165. saveDataMap[dv.DataTime] = temp
  166. }
  167. if edbInfoIndex == 0 {
  168. dateList = append(dateList, dv.DataTime)
  169. }
  170. }
  171. }
  172. //数据处理,将日期内不全的数据做填补
  173. handleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, edbInfoIdList)
  174. formulaMap := utils.CheckFormula(formulaStr)
  175. addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  176. var isAdd bool
  177. if !minLatestDate.IsZero() {
  178. latestDateStr = minLatestDate.Format(utils.FormatDate)
  179. }
  180. //获取指标所有数据
  181. dataList := make([]*EdbData, 0)
  182. dataTableName := GetEdbDataTableName(source)
  183. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  184. sql = fmt.Sprintf(sql, dataTableName)
  185. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  186. if err != nil {
  187. return
  188. }
  189. dataMap := make(map[string]string)
  190. for _, v := range dataList {
  191. dataMap[v.DataTime] = v.Value
  192. }
  193. edbInfoIdStr := strconv.Itoa(edbInfoId)
  194. existDataMap := make(map[string]string)
  195. removeDateList := make([]string, 0) //需要移除的日期
  196. for sk, sv := range saveDataMap {
  197. //fmt.Println(sk, sv)
  198. formulaStr = strings.ToUpper(formulaStr)
  199. formulaFormStr := ReplaceFormula(edbInfoIdList, sv, formulaMap, formulaStr, edbInfoIdBytes)
  200. if formulaFormStr != "" {
  201. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  202. expression := formula.NewExpression(formulaFormStr)
  203. calResult, tmpErr := expression.Evaluate()
  204. if tmpErr != nil {
  205. // 分母为0的报错
  206. if strings.Contains(err.Error(), "divide by zero") {
  207. removeDateList = append(removeDateList, sk)
  208. continue
  209. }
  210. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  211. fmt.Println(err)
  212. return
  213. }
  214. calVal, tmpErr := calResult.Float64()
  215. if tmpErr != nil {
  216. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  217. fmt.Println(err)
  218. return
  219. }
  220. nanCheck := fmt.Sprintf("%0.f", calVal)
  221. // 分母为0.0的报错
  222. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  223. removeDateList = append(removeDateList, sk)
  224. continue
  225. }
  226. // 最近实际日期的实际数据
  227. if latestDateStr == sk {
  228. latestValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  229. }
  230. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  231. if existVal, ok := dataMap[sk]; !ok {
  232. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  233. timestamp := dataTime.UnixNano() / 1e6
  234. timeStr := fmt.Sprintf("%d", timestamp)
  235. if _, existOk := existDataMap[sk]; !existOk {
  236. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  237. isAdd = true
  238. }
  239. existDataMap[sk] = sk
  240. } else {
  241. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  242. if tmpErr != nil {
  243. err = tmpErr
  244. return
  245. }
  246. existStr := existValDecimal.String()
  247. if existStr != saveValue {
  248. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  249. sql = fmt.Sprintf(sql, dataTableName)
  250. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  251. if err != nil {
  252. return
  253. }
  254. }
  255. }
  256. } else {
  257. //计算公式异常,那么就移除该指标
  258. removeDateList = append(removeDateList, sk)
  259. continue
  260. }
  261. }
  262. if isAdd {
  263. addSql = strings.TrimRight(addSql, ",")
  264. _, err = to.Raw(addSql).Exec()
  265. if err != nil {
  266. fmt.Println("RefreshAllCalculate add Err", err.Error())
  267. return
  268. }
  269. }
  270. if len(removeDateList) > 0 {
  271. removeDateStr := strings.Join(removeDateList, `","`)
  272. removeDateStr = `"` + removeDateStr + `"`
  273. //如果拼接指标变更了,那么需要删除所有的指标数据
  274. tableName := GetEdbDataTableName(source)
  275. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  276. _, err = to.Raw(sql, edbInfoId).Exec()
  277. if err != nil {
  278. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  279. return
  280. }
  281. }
  282. return
  283. }