base_predict_from_calculate.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "github.com/yidane/formula"
  8. "hongze/hongze_edb_lib/services"
  9. "hongze/hongze_edb_lib/utils"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // PredictEdbInfoCalculateSaveReq 预测计算(运算)指标请求参数
  15. type PredictEdbInfoCalculateSaveReq struct {
  16. AdminId int `description:"添加人id"`
  17. AdminName string `description:"添加人名称"`
  18. EdbName string `description:"指标名称"`
  19. Frequency string `description:"频率"`
  20. Unit string `description:"单位"`
  21. ClassifyId int `description:"分类id"`
  22. CalculateFormula string `description:"计算公式"`
  23. EdbInfoIdArr []struct {
  24. EdbInfoId int `description:"指标id"`
  25. FromTag string `description:"指标对应标签"`
  26. }
  27. }
  28. // PredictCalculateItems 预测计算(运算)指标信息
  29. type PredictCalculateItems struct {
  30. EdbInfoId int
  31. DataMap map[string]float64
  32. }
  33. // EditPredictCalculate 新增预测计算(运算)指标
  34. func EditPredictCalculate(edbInfo *EdbInfo, calculateMappingList []*EdbInfoCalculateMapping) (err error) {
  35. o := orm.NewOrm()
  36. to, err := o.Begin()
  37. if err != nil {
  38. return
  39. }
  40. defer func() {
  41. if err != nil {
  42. tmpErr := to.Rollback()
  43. errMsg := fmt.Sprintf("AddPredictCalculate Err:%s" + err.Error())
  44. if tmpErr != nil {
  45. errMsg += `;rollback失败:` + tmpErr.Error()
  46. }
  47. utils.FileLog.Info(errMsg)
  48. return
  49. }
  50. tmpErr := to.Commit()
  51. if tmpErr != nil {
  52. errMsg := fmt.Sprintf("AddPredictCalculate commit Err:%s" + tmpErr.Error())
  53. utils.FileLog.Info(errMsg)
  54. }
  55. }()
  56. // 修改指标信息
  57. _, err = to.Update(edbInfo, "EdbName", "Frequency", "Unit", "ClassifyId", "CalculateFormula")
  58. if err != nil {
  59. return
  60. }
  61. //删除,计算指标关联的,基础指标的关联关系
  62. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  63. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  64. if err != nil {
  65. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  66. return
  67. }
  68. // 插入新的关系表
  69. if len(calculateMappingList) > 0 {
  70. _, err = to.InsertMulti(len(calculateMappingList), calculateMappingList)
  71. }
  72. //数据表
  73. tableName := GetEdbDataTableName(edbInfo.Source)
  74. //清空原有数据
  75. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  76. _, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
  77. if err != nil {
  78. return
  79. }
  80. return
  81. }
  82. // AddPredictCalculateData 新增预测计算(运算)指标的数据
  83. func AddPredictCalculateDataBak(edbInfoIdList []*EdbInfo, edbInfoId int, edbCode, formulaStr string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  84. o := orm.NewOrm()
  85. defer func() {
  86. if err != nil {
  87. utils.FileLog.Info(fmt.Sprintf("Calculate Err:%s" + err.Error()))
  88. }
  89. }()
  90. var minLatestDate time.Time
  91. oldSaveDataMap := make(map[string]map[int]float64)
  92. saveDataMap := make(map[string]map[int]float64)
  93. dateList := make([]string, 0)
  94. for edbInfoIndex, v := range edbInfoIdList {
  95. tmpLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  96. if tmpErr != nil {
  97. err = errors.New(`最近的日期格式化失败;日期:` + v.LatestDate + `;err:` + tmpErr.Error())
  98. return
  99. }
  100. // 如果不存在最小的真实数据日期,那么将当前指标的真实数据日期给赋值;
  101. // 如果存在最小的真实数据日期,同时当前指标的真实数据日期 早于 最小的真实数据日期, 那么将当前指标的真实数据日期给赋值;
  102. if minLatestDate.IsZero() || tmpLatestDate.Before(minLatestDate) {
  103. minLatestDate = tmpLatestDate
  104. }
  105. dataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  106. if tmpErr != nil {
  107. err = tmpErr
  108. return
  109. }
  110. dataMap := make(map[string]float64)
  111. for _, dv := range dataList {
  112. // 现有实际数据
  113. if val, ok := oldSaveDataMap[dv.DataTime]; ok {
  114. if _, ok := val[v.EdbInfoId]; !ok {
  115. val[v.EdbInfoId] = dv.Value
  116. }
  117. } else {
  118. temp := make(map[int]float64)
  119. temp[v.EdbInfoId] = dv.Value
  120. oldSaveDataMap[dv.DataTime] = temp
  121. }
  122. // 待处理的数据
  123. if val, ok := saveDataMap[dv.DataTime]; ok {
  124. if _, ok := val[v.EdbInfoId]; !ok {
  125. val[v.EdbInfoId] = dv.Value
  126. }
  127. } else {
  128. temp := make(map[int]float64)
  129. temp[v.EdbInfoId] = dv.Value
  130. saveDataMap[dv.DataTime] = temp
  131. }
  132. // 以第一个指标的日期作为基准日期
  133. if edbInfoIndex == 0 {
  134. dateList = append(dateList, dv.DataTime)
  135. }
  136. }
  137. item := new(PredictCalculateItems)
  138. item.EdbInfoId = v.EdbInfoId
  139. item.DataMap = dataMap
  140. }
  141. //数据处理,将日期内不全的数据做补全
  142. handleDateSaveDataMap(dateList, oldSaveDataMap, saveDataMap, edbInfoIdList)
  143. formulaMap := services.CheckFormula(formulaStr)
  144. addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  145. nowStr := time.Now().Format(utils.FormatDateTime)
  146. var isAdd bool
  147. if !minLatestDate.IsZero() {
  148. latestDateStr = minLatestDate.Format(utils.FormatDate)
  149. }
  150. for sk, sv := range saveDataMap {
  151. formulaStr = strings.ToUpper(formulaStr)
  152. formulaFormStr := ReplaceFormula(edbInfoIdList, sv, formulaMap, formulaStr, edbInfoIdBytes)
  153. if formulaStr == "" {
  154. return
  155. }
  156. if formulaFormStr != "" {
  157. expression := formula.NewExpression(formulaFormStr)
  158. calResult, tmpErr := expression.Evaluate()
  159. if tmpErr != nil {
  160. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  161. fmt.Println(err)
  162. return
  163. }
  164. calVal, tmpErr := calResult.Float64()
  165. if tmpErr != nil {
  166. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  167. fmt.Println(err)
  168. return
  169. }
  170. //需要存入的数据
  171. {
  172. if latestDateStr == sk {
  173. latestValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  174. }
  175. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  176. timestamp := dataTime.UnixNano() / 1e6
  177. timeStr := fmt.Sprintf("%d", timestamp)
  178. addSql += "("
  179. addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + sk + "'" + "," + utils.SubFloatToString(calVal, 4) + "," + "'" + nowStr + "'" +
  180. "," + "'" + nowStr + "'" + "," + "'" + timeStr + "'"
  181. addSql += "),"
  182. isAdd = true
  183. }
  184. } else {
  185. fmt.Println("formulaFormStr is empty")
  186. }
  187. }
  188. if isAdd {
  189. addSql = strings.TrimRight(addSql, ",")
  190. _, err = o.Raw(addSql).Exec()
  191. if err != nil {
  192. fmt.Println("AddPredictCalculate Err:" + err.Error())
  193. //errMsg = " tx.Exec Err :" + err.Error()
  194. return
  195. }
  196. }
  197. return
  198. }
  199. func AddPredictCalculateData(edbInfoIdList []*EdbInfo, edbInfo *EdbInfo, edbCode, formulaStr string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  200. o := orm.NewOrm()
  201. to, err := o.Begin()
  202. if err != nil {
  203. return
  204. }
  205. defer func() {
  206. if err != nil {
  207. fmt.Println("AddPredictCalculateData Calculate,Err:" + err.Error())
  208. _ = to.Rollback()
  209. } else {
  210. _ = to.Commit()
  211. }
  212. }()
  213. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfo.EdbInfoId, edbInfo.Source, edbCode, formulaStr, "", edbInfoIdBytes)
  214. return
  215. }
  216. // RefreshAllPredictCalculate 刷新预测计算指标的全部数据
  217. func RefreshAllPredictCalculate(edbInfoIdList []*EdbInfo, edbInfoId, source int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  218. o := orm.NewOrm()
  219. to, err := o.Begin()
  220. if err != nil {
  221. return
  222. }
  223. defer func() {
  224. if err != nil {
  225. fmt.Println("RefreshAllCalculate,Err:" + err.Error())
  226. _ = to.Rollback()
  227. } else {
  228. _ = to.Commit()
  229. }
  230. }()
  231. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfoId, source, edbCode, formulaStr, startDate, edbInfoIdBytes)
  232. return
  233. }
  234. // refreshAllPredictCalculate 刷新预测计算指标的全部数据
  235. func refreshAllPredictCalculate(to orm.TxOrmer, edbInfoIdList []*EdbInfo, edbInfoId, source int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  236. fmt.Println("startDate:", startDate)
  237. var minLatestDate time.Time
  238. realSaveDataMap := make(map[string]map[int]float64)
  239. saveDataMap := make(map[string]map[int]float64)
  240. dateList := make([]string, 0)
  241. for edbInfoIndex, v := range edbInfoIdList {
  242. tmpLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  243. if tmpErr != nil {
  244. err = errors.New(`最近的日期格式化失败;日期:` + v.LatestDate + `;err:` + tmpErr.Error())
  245. return
  246. }
  247. if minLatestDate.IsZero() || tmpLatestDate.Before(minLatestDate) {
  248. minLatestDate = tmpLatestDate
  249. }
  250. // 获取关联指标数据
  251. dataList, tmpErr := GetPredictEdbDataListAllByStartDate(v, 1, startDate)
  252. if tmpErr != nil {
  253. err = tmpErr
  254. return
  255. }
  256. dataMap := make(map[string]float64)
  257. for _, dv := range dataList { // 现有实际数据
  258. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  259. if _, ok := val[v.EdbInfoId]; !ok {
  260. val[v.EdbInfoId] = dv.Value
  261. }
  262. } else {
  263. temp := make(map[int]float64)
  264. temp[v.EdbInfoId] = dv.Value
  265. realSaveDataMap[dv.DataTime] = temp
  266. }
  267. // 待处理的数据
  268. if val, ok := saveDataMap[dv.DataTime]; ok {
  269. if _, ok := val[v.EdbInfoId]; !ok {
  270. val[v.EdbInfoId] = dv.Value
  271. }
  272. } else {
  273. temp := make(map[int]float64)
  274. temp[v.EdbInfoId] = dv.Value
  275. saveDataMap[dv.DataTime] = temp
  276. }
  277. // 以第一个指标的日期作为基准日期
  278. if edbInfoIndex == 0 {
  279. dateList = append(dateList, dv.DataTime)
  280. }
  281. }
  282. item := new(CalculateItems)
  283. item.EdbInfoId = v.EdbInfoId
  284. item.DataMap = dataMap
  285. }
  286. //数据处理,将日期内不全的数据做补全
  287. handleDateSaveDataMap(dateList, realSaveDataMap, saveDataMap, edbInfoIdList)
  288. formulaMap := services.CheckFormula(formulaStr)
  289. addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  290. var isAdd bool
  291. if !minLatestDate.IsZero() {
  292. latestDateStr = minLatestDate.Format(utils.FormatDate)
  293. }
  294. //获取指标所有数据
  295. dataList := make([]*EdbData, 0)
  296. dataTableName := GetEdbDataTableName(source)
  297. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  298. sql = fmt.Sprintf(sql, dataTableName)
  299. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  300. if err != nil {
  301. return
  302. }
  303. dataMap := make(map[string]string)
  304. for _, v := range dataList {
  305. dataMap[v.DataTime] = v.Value
  306. }
  307. edbInfoIdStr := strconv.Itoa(edbInfoId)
  308. existDataMap := make(map[string]string)
  309. removeDateList := make([]string, 0) //需要移除的日期
  310. for sk, sv := range saveDataMap {
  311. //fmt.Println(sk, sv)
  312. formulaStr = strings.ToUpper(formulaStr)
  313. formulaFormStr := ReplaceFormula(edbInfoIdList, sv, formulaMap, formulaStr, edbInfoIdBytes)
  314. if formulaFormStr != "" {
  315. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  316. expression := formula.NewExpression(formulaFormStr)
  317. calResult, tmpErr := expression.Evaluate()
  318. if tmpErr != nil {
  319. // 分母为0的报错
  320. if strings.Contains(err.Error(), "divide by zero") {
  321. removeDateList = append(removeDateList, sk)
  322. continue
  323. }
  324. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  325. fmt.Println(err)
  326. return
  327. }
  328. calVal, tmpErr := calResult.Float64()
  329. if tmpErr != nil {
  330. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  331. fmt.Println(err)
  332. return
  333. }
  334. // 最近实际日期的实际数据
  335. if latestDateStr == sk {
  336. latestValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  337. }
  338. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  339. if existVal, ok := dataMap[sk]; !ok {
  340. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  341. timestamp := dataTime.UnixNano() / 1e6
  342. timeStr := fmt.Sprintf("%d", timestamp)
  343. if _, existOk := existDataMap[sk]; !existOk {
  344. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  345. isAdd = true
  346. }
  347. existDataMap[sk] = sk
  348. } else {
  349. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  350. if tmpErr != nil {
  351. err = tmpErr
  352. return
  353. }
  354. existStr := existValDecimal.String()
  355. if existStr != saveValue {
  356. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  357. sql = fmt.Sprintf(sql, dataTableName)
  358. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  359. if err != nil {
  360. return
  361. }
  362. }
  363. }
  364. } else {
  365. //计算公式异常,那么就移除该指标
  366. removeDateList = append(removeDateList, sk)
  367. continue
  368. }
  369. }
  370. if isAdd {
  371. addSql = strings.TrimRight(addSql, ",")
  372. _, err = to.Raw(addSql).Exec()
  373. if err != nil {
  374. fmt.Println("RefreshAllCalculate add Err", err.Error())
  375. return
  376. }
  377. }
  378. if len(removeDateList) > 0 {
  379. removeDateStr := strings.Join(removeDateList, `","`)
  380. removeDateStr = `"` + removeDateStr + `"`
  381. //如果拼接指标变更了,那么需要删除所有的指标数据
  382. tableName := GetEdbDataTableName(source)
  383. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  384. _, err = to.Raw(sql, edbInfoId).Exec()
  385. if err != nil {
  386. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  387. return
  388. }
  389. }
  390. return
  391. }