base_predict_from_calculate.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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", "EmptyType", "MaxEmptyType")
  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, edbInfo.SubSource)
  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. // AddPredictCalculateData 新增预测计算(运算)指标的数据
  82. //func AddPredictCalculateDataBak(edbInfoIdList []*EdbInfo, edbInfoId int, edbCode, formulaStr string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  83. // o := orm.NewOrm()
  84. // defer func() {
  85. // if err != nil {
  86. // utils.FileLog.Info(fmt.Sprintf("Calculate Err:%s" + err.Error()))
  87. // }
  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. //
  95. // for edbInfoIndex, v := range edbInfoIdList {
  96. // tmpLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  97. // if tmpErr != nil {
  98. // err = errors.New(`最近的日期格式化失败;日期:` + v.LatestDate + `;err:` + tmpErr.Error())
  99. // return
  100. // }
  101. // // 如果不存在最小的真实数据日期,那么将当前指标的真实数据日期给赋值;
  102. // // 如果存在最小的真实数据日期,同时当前指标的真实数据日期 早于 最小的真实数据日期, 那么将当前指标的真实数据日期给赋值;
  103. // if minLatestDate.IsZero() || tmpLatestDate.Before(minLatestDate) {
  104. // minLatestDate = tmpLatestDate
  105. // }
  106. //
  107. // dataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  108. // if tmpErr != nil {
  109. // err = tmpErr
  110. // return
  111. // }
  112. // dataMap := make(map[string]float64)
  113. // for _, dv := range dataList {
  114. // // 现有实际数据
  115. // if val, ok := oldSaveDataMap[dv.DataTime]; ok {
  116. // if _, ok := val[v.EdbInfoId]; !ok {
  117. // val[v.EdbInfoId] = dv.Value
  118. // }
  119. // } else {
  120. // temp := make(map[int]float64)
  121. // temp[v.EdbInfoId] = dv.Value
  122. // oldSaveDataMap[dv.DataTime] = temp
  123. // }
  124. //
  125. // // 待处理的数据
  126. // if val, ok := saveDataMap[dv.DataTime]; ok {
  127. // if _, ok := val[v.EdbInfoId]; !ok {
  128. // val[v.EdbInfoId] = dv.Value
  129. // }
  130. // } else {
  131. // temp := make(map[int]float64)
  132. // temp[v.EdbInfoId] = dv.Value
  133. // saveDataMap[dv.DataTime] = temp
  134. // }
  135. //
  136. // // 以第一个指标的日期作为基准日期
  137. // if edbInfoIndex == 0 {
  138. // dateList = append(dateList, dv.DataTime)
  139. // }
  140. // }
  141. // item := new(PredictCalculateItems)
  142. // item.EdbInfoId = v.EdbInfoId
  143. // item.DataMap = dataMap
  144. // }
  145. //
  146. // //数据处理,将日期内不全的数据做补全
  147. // handleDateSaveDataMap(dateList, oldSaveDataMap, saveDataMap, edbInfoIdList)
  148. //
  149. // formulaMap := utils.CheckFormula(formulaStr)
  150. // addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  151. // nowStr := time.Now().Format(utils.FormatDateTime)
  152. // var isAdd bool
  153. //
  154. // if !minLatestDate.IsZero() {
  155. // latestDateStr = minLatestDate.Format(utils.FormatDate)
  156. // }
  157. // for sk, sv := range saveDataMap {
  158. // formulaStr = strings.ToUpper(formulaStr)
  159. // formulaFormStr := ReplaceFormula(edbInfoIdList, sv, formulaMap, formulaStr, edbInfoIdBytes)
  160. // if formulaStr == "" {
  161. // return
  162. // }
  163. // if formulaFormStr != "" {
  164. // expression := formula.NewExpression(formulaFormStr)
  165. // calResult, tmpErr := expression.Evaluate()
  166. // if tmpErr != nil {
  167. // err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  168. // fmt.Println(err)
  169. // return
  170. // }
  171. // calVal, tmpErr := calResult.Float64()
  172. // if tmpErr != nil {
  173. // err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  174. // fmt.Println(err)
  175. // return
  176. // }
  177. //
  178. // //需要存入的数据
  179. // {
  180. // if latestDateStr == sk {
  181. // nanCheck := fmt.Sprintf("%0.f", calVal)
  182. // // 分母为0.0的报错
  183. // if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  184. // err = errors.New("计算失败 分母为0:Err: formulaStr:" + formulaFormStr)
  185. // fmt.Println(err)
  186. // return
  187. // }
  188. // latestValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  189. // }
  190. // dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  191. // timestamp := dataTime.UnixNano() / 1e6
  192. // timeStr := fmt.Sprintf("%d", timestamp)
  193. // addSql += "("
  194. // addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + sk + "'" + "," + utils.SubFloatToString(calVal, 4) + "," + "'" + nowStr + "'" +
  195. // "," + "'" + nowStr + "'" + "," + "'" + timeStr + "'"
  196. // addSql += "),"
  197. // isAdd = true
  198. // }
  199. // } else {
  200. // fmt.Println("formulaFormStr is empty")
  201. // }
  202. // }
  203. // if isAdd {
  204. // addSql = strings.TrimRight(addSql, ",")
  205. // _, err = o.Raw(addSql).Exec()
  206. // if err != nil {
  207. // fmt.Println("AddPredictCalculate Err:" + err.Error())
  208. // //errMsg = " tx.Exec Err :" + err.Error()
  209. // return
  210. // }
  211. // }
  212. // return
  213. //}
  214. func AddPredictCalculateData(edbInfoIdList []*EdbInfo, edbInfo *EdbInfo, edbCode, formulaStr string, edbInfoIdBytes []string) (latestDateStr string, latestValue float64, err error) {
  215. o := orm.NewOrm()
  216. to, err := o.Begin()
  217. if err != nil {
  218. return
  219. }
  220. defer func() {
  221. if err != nil {
  222. fmt.Println("AddPredictCalculateData Calculate,Err:" + err.Error())
  223. _ = to.Rollback()
  224. } else {
  225. _ = to.Commit()
  226. }
  227. }()
  228. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbCode, formulaStr, "", edbInfoIdBytes, edbInfo.EmptyType, edbInfo.MaxEmptyType)
  229. return
  230. }
  231. // RefreshAllPredictCalculate 刷新预测计算指标的全部数据
  232. func RefreshAllPredictCalculate(edbInfoIdList []*EdbInfo, edbInfoId, source, subSource int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string, emptyType, maxEmptyType int) (latestDateStr string, latestValue float64, err error) {
  233. o := orm.NewOrm()
  234. to, err := o.Begin()
  235. if err != nil {
  236. return
  237. }
  238. defer func() {
  239. if err != nil {
  240. fmt.Println("RefreshAllCalculate,Err:" + err.Error())
  241. _ = to.Rollback()
  242. } else {
  243. _ = to.Commit()
  244. }
  245. }()
  246. latestDateStr, latestValue, err = refreshAllPredictCalculate(to, edbInfoIdList, edbInfoId, source, subSource, edbCode, formulaStr, startDate, edbInfoIdBytes, emptyType, maxEmptyType)
  247. return
  248. }
  249. // refreshAllPredictCalculate 刷新预测计算指标的全部数据
  250. func refreshAllPredictCalculate(to orm.TxOrmer, edbInfoIdList []*EdbInfo, edbInfoId, source, subSource int, edbCode, formulaStr, startDate string, edbInfoIdBytes []string, emptyType, maxEmptyType int) (latestDateStr string, latestValue float64, err error) {
  251. fmt.Println("startDate:", startDate)
  252. // 最小的结束日期 , 最晚的数据开始日期
  253. var minLatestDate, maxStartDate time.Time
  254. dateList := make([]string, 0) // 第一个指标的日期数据
  255. realSaveDataMap := make(map[string]map[int]float64)
  256. saveDataMap := make(map[string]map[int]float64)
  257. for edbInfoIndex, v := range edbInfoIdList {
  258. // 单独存储max、min函数里的指标的数据
  259. /*tmpLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  260. if tmpErr != nil {
  261. err = errors.New(`最近的日期格式化失败;日期:` + v.EndDate + `;err:` + tmpErr.Error())
  262. return
  263. }
  264. if minLatestDate.IsZero() || tmpLatestDate.Before(minLatestDate) {
  265. minLatestDate = tmpLatestDate
  266. }
  267. tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.StartDate, time.Local)
  268. if tmpErr != nil {
  269. err = errors.New(`最近的日期格式化失败;日期:` + v.StartDate + `;err:` + tmpErr.Error())
  270. return
  271. }
  272. if maxStartDate.IsZero() || maxStartDate.Before(tmpStartDate) {
  273. maxStartDate = tmpStartDate
  274. }*/
  275. // 获取关联指标数据
  276. dataList, tmpErr := GetPredictEdbDataListAllByStartDate(v, 1, startDate)
  277. if tmpErr != nil {
  278. err = tmpErr
  279. return
  280. }
  281. for _, dv := range dataList { // 现有实际数据
  282. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  283. if _, ok := val[v.EdbInfoId]; !ok {
  284. val[v.EdbInfoId] = dv.Value
  285. }
  286. } else {
  287. temp := make(map[int]float64)
  288. temp[v.EdbInfoId] = dv.Value
  289. realSaveDataMap[dv.DataTime] = temp
  290. }
  291. // 待处理的数据
  292. if val, ok := saveDataMap[dv.DataTime]; ok {
  293. if _, ok := val[v.EdbInfoId]; !ok {
  294. val[v.EdbInfoId] = dv.Value
  295. }
  296. } else {
  297. temp := make(map[int]float64)
  298. temp[v.EdbInfoId] = dv.Value
  299. saveDataMap[dv.DataTime] = temp
  300. }
  301. if edbInfoIndex == 0 {
  302. dateList = append(dateList, dv.DataTime)
  303. tmpDate, _ := time.ParseInLocation(utils.FormatDate, dv.DataTime, time.Local)
  304. if minLatestDate.IsZero() || tmpDate.After(minLatestDate) {
  305. minLatestDate = tmpDate
  306. }
  307. if maxStartDate.IsZero() || tmpDate.Before(maxStartDate) {
  308. maxStartDate = tmpDate
  309. }
  310. }
  311. }
  312. }
  313. //数据处理,将日期内不全的数据做填补
  314. HandleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, edbInfoIdList, emptyType)
  315. formulaDateSlice, formulaDateMap, err := utils.HandleFormulaJson(formulaStr, minLatestDate)
  316. if err != nil {
  317. return
  318. }
  319. addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  320. var isAdd bool
  321. if !minLatestDate.IsZero() {
  322. latestDateStr = minLatestDate.Format(utils.FormatDate)
  323. }
  324. //获取指标所有数据
  325. dataList := make([]*EdbData, 0)
  326. dataTableName := GetEdbDataTableName(source, subSource)
  327. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  328. sql = fmt.Sprintf(sql, dataTableName)
  329. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  330. if err != nil {
  331. return
  332. }
  333. dataMap := make(map[string]string)
  334. for _, v := range dataList {
  335. dataMap[v.DataTime] = v.Value
  336. }
  337. edbInfoIdStr := strconv.Itoa(edbInfoId)
  338. existDataMap := make(map[string]string)
  339. removeDateList := make([]string, 0) //需要移除的日期
  340. // 判断是否特殊处理max和min函数
  341. maxDealFlag := false
  342. if emptyType == 4 && maxEmptyType == 2 {
  343. maxDealFlag = true
  344. }
  345. for sk, sv := range saveDataMap {
  346. // 当空值处理类型选择了不计算时,只要有一个指标在某个日期没有值(即空值),则计算指标在该日期没有值
  347. if emptyType == 1 {
  348. if len(sv) != len(edbInfoIdList) {
  349. continue
  350. }
  351. }
  352. //fmt.Println(sk, sv)
  353. // 根据时间范围,选择对应的公式
  354. formulaMap := make(map[string]string)
  355. formulaStr = ""
  356. for _, fv := range formulaDateSlice {
  357. if sk < fv {
  358. if f, ok := formulaDateMap[fv]; ok {
  359. formulaStr = f
  360. formulaMap = utils.CheckFormula(formulaStr)
  361. }
  362. break
  363. }
  364. }
  365. if formulaStr == "" {
  366. continue
  367. }
  368. svMax := make(map[int]float64)
  369. if maxDealFlag {
  370. // 特殊处理max和min函数,如果原本的值为空,则选择空值参与运算
  371. if svMaxData, ok := realSaveDataMap[sk]; ok {
  372. svMax = svMaxData
  373. }
  374. }
  375. formulaStr = strings.ToUpper(formulaStr)
  376. formulaFormStr := ReplaceFormula(edbInfoIdList, sv, svMax, formulaMap, formulaStr, edbInfoIdBytes, maxDealFlag)
  377. if formulaFormStr != "" {
  378. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  379. fmt.Println(fmt.Sprintf("date %s:formulaFormStr:%s", sk, formulaFormStr))
  380. expression := formula.NewExpression(formulaFormStr)
  381. calResult, tmpErr := expression.Evaluate()
  382. if tmpErr != nil {
  383. // 分母为0的报错
  384. if strings.Contains(err.Error(), "divide by zero") {
  385. removeDateList = append(removeDateList, sk)
  386. continue
  387. }
  388. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  389. fmt.Println(err)
  390. return
  391. }
  392. calVal, tmpErr := calResult.Float64()
  393. if tmpErr != nil {
  394. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  395. fmt.Println(err)
  396. return
  397. }
  398. nanCheck := fmt.Sprintf("%0.f", calVal)
  399. // 分母为0.0的报错
  400. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  401. removeDateList = append(removeDateList, sk)
  402. continue
  403. }
  404. // 最近实际日期的实际数据
  405. if latestDateStr == sk {
  406. latestValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  407. }
  408. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  409. if existVal, ok := dataMap[sk]; !ok {
  410. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  411. timestamp := dataTime.UnixNano() / 1e6
  412. timeStr := fmt.Sprintf("%d", timestamp)
  413. if _, existOk := existDataMap[sk]; !existOk {
  414. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  415. isAdd = true
  416. }
  417. existDataMap[sk] = sk
  418. } else {
  419. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  420. if tmpErr != nil {
  421. err = tmpErr
  422. return
  423. }
  424. existStr := existValDecimal.String()
  425. if existStr != saveValue {
  426. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  427. sql = fmt.Sprintf(sql, dataTableName)
  428. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  429. if err != nil {
  430. return
  431. }
  432. }
  433. }
  434. } else {
  435. //计算公式异常,那么就移除该指标
  436. removeDateList = append(removeDateList, sk)
  437. continue
  438. }
  439. }
  440. if isAdd {
  441. addSql = strings.TrimRight(addSql, ",")
  442. _, err = to.Raw(addSql).Exec()
  443. if err != nil {
  444. fmt.Println("RefreshAllCalculate add Err", err.Error())
  445. return
  446. }
  447. }
  448. if len(removeDateList) > 0 {
  449. removeDateStr := strings.Join(removeDateList, `","`)
  450. removeDateStr = `"` + removeDateStr + `"`
  451. //如果拼接指标变更了,那么需要删除所有的指标数据
  452. tableName := GetEdbDataTableName(source, subSource)
  453. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  454. _, err = to.Raw(sql, edbInfoId).Exec()
  455. if err != nil {
  456. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  457. return
  458. }
  459. }
  460. return
  461. }