base_predict_from_calculate.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 startDateValue float64
  254. // 最小的结束日期 , 最晚的数据开始日期
  255. var newLatestDate, minLatestDate, maxStartDate time.Time
  256. dateList := make([]string, 0) // 第一个指标的日期数据
  257. realSaveDataMap := make(map[string]map[int]float64)
  258. saveDataMap := make(map[string]map[int]float64)
  259. for edbInfoIndex, v := range edbInfoIdList {
  260. // 单独存储max、min函数里的指标的数据
  261. tmpNewLatestDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  262. if tmpErr != nil {
  263. err = errors.New(`最近的日期格式化失败;日期:` + v.LatestDate + `;err:` + tmpErr.Error())
  264. return
  265. }
  266. if newLatestDate.IsZero() || tmpNewLatestDate.Before(minLatestDate) {
  267. newLatestDate = tmpNewLatestDate
  268. }
  269. /*tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.StartDate, time.Local)
  270. if tmpErr != nil {
  271. err = errors.New(`最近的日期格式化失败;日期:` + v.StartDate + `;err:` + tmpErr.Error())
  272. return
  273. }
  274. if maxStartDate.IsZero() || maxStartDate.Before(tmpStartDate) {
  275. maxStartDate = tmpStartDate
  276. }
  277. tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.EndDate, time.Local)
  278. if tmpErr != nil {
  279. err = errors.New(`最近的日期格式化失败;日期:` + v.EndDate + `;err:` + tmpErr.Error())
  280. return
  281. }
  282. if minEndDate.IsZero() || tmpEndDate.Before(minEndDate) {
  283. minEndDate = tmpEndDate
  284. }
  285. }*/
  286. // 获取关联指标数据
  287. dataList, tmpErr := GetPredictEdbDataListAllByStartDate(v, 1, startDate)
  288. if tmpErr != nil {
  289. err = tmpErr
  290. return
  291. }
  292. for _, dv := range dataList { // 现有实际数据
  293. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  294. if _, ok := val[v.EdbInfoId]; !ok {
  295. val[v.EdbInfoId] = dv.Value
  296. }
  297. } else {
  298. temp := make(map[int]float64)
  299. temp[v.EdbInfoId] = dv.Value
  300. realSaveDataMap[dv.DataTime] = temp
  301. }
  302. // 待处理的数据
  303. if val, ok := saveDataMap[dv.DataTime]; ok {
  304. if _, ok := val[v.EdbInfoId]; !ok {
  305. val[v.EdbInfoId] = dv.Value
  306. }
  307. } else {
  308. temp := make(map[int]float64)
  309. temp[v.EdbInfoId] = dv.Value
  310. saveDataMap[dv.DataTime] = temp
  311. }
  312. if edbInfoIndex == 0 {
  313. dateList = append(dateList, dv.DataTime)
  314. tmpDate, _ := time.ParseInLocation(utils.FormatDate, dv.DataTime, time.Local)
  315. if minLatestDate.IsZero() || tmpDate.After(minLatestDate) {
  316. minLatestDate = tmpDate
  317. }
  318. if maxStartDate.IsZero() || tmpDate.Before(maxStartDate) {
  319. maxStartDate = tmpDate
  320. }
  321. }
  322. }
  323. }
  324. //数据处理,将日期内不全的数据做填补
  325. HandleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, edbInfoIdList, emptyType)
  326. formulaDateSlice, formulaDateMap, err := utils.HandleFormulaJson(formulaStr, minLatestDate)
  327. if err != nil {
  328. return
  329. }
  330. addSql := ` INSERT INTO edb_data_predict_calculate (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  331. var isAdd bool
  332. //获取指标所有数据
  333. dataList := make([]*EdbData, 0)
  334. dataTableName := GetEdbDataTableName(source, subSource)
  335. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  336. sql = fmt.Sprintf(sql, dataTableName)
  337. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  338. if err != nil {
  339. return
  340. }
  341. dataMap := make(map[string]string)
  342. for _, v := range dataList {
  343. dataMap[v.DataTime] = v.Value
  344. }
  345. edbInfoIdStr := strconv.Itoa(edbInfoId)
  346. existDataMap := make(map[string]string)
  347. removeDateList := make([]string, 0) //需要移除的日期
  348. // 判断是否特殊处理max和min函数
  349. maxDealFlag := false
  350. if emptyType == 4 && maxEmptyType == 2 {
  351. maxDealFlag = true
  352. }
  353. for sk, sv := range saveDataMap {
  354. // 当空值处理类型选择了不计算时,只要有一个指标在某个日期没有值(即空值),则计算指标在该日期没有值
  355. if emptyType == 1 {
  356. if len(sv) != len(edbInfoIdList) {
  357. continue
  358. }
  359. }
  360. //fmt.Println(sk, sv)
  361. // 根据时间范围,选择对应的公式
  362. formulaMap := make(map[string]string)
  363. formulaStr = ""
  364. for _, fv := range formulaDateSlice {
  365. if sk < fv {
  366. if f, ok := formulaDateMap[fv]; ok {
  367. formulaStr = f
  368. formulaMap, err = utils.CheckFormula(formulaStr)
  369. if err != nil {
  370. err = fmt.Errorf("公式错误,请重新填写")
  371. return
  372. }
  373. }
  374. break
  375. }
  376. }
  377. if formulaStr == "" {
  378. continue
  379. }
  380. svMax := make(map[int]float64)
  381. if maxDealFlag {
  382. // 特殊处理max和min函数,如果原本的值为空,则选择空值参与运算
  383. if svMaxData, ok := realSaveDataMap[sk]; ok {
  384. svMax = svMaxData
  385. }
  386. }
  387. formulaStr = strings.ToUpper(formulaStr)
  388. formulaFormStr := ReplaceFormula(edbInfoIdList, sv, svMax, formulaMap, formulaStr, edbInfoIdBytes, maxDealFlag)
  389. if formulaFormStr != "" {
  390. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  391. fmt.Println(fmt.Sprintf("date %s:formulaFormStr:%s", sk, formulaFormStr))
  392. expression := formula.NewExpression(formulaFormStr)
  393. calResult, tmpErr := expression.Evaluate()
  394. if tmpErr != nil {
  395. // 分母为0的报错
  396. if strings.Contains(err.Error(), "divide by zero") {
  397. removeDateList = append(removeDateList, sk)
  398. continue
  399. }
  400. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  401. fmt.Println(err)
  402. return
  403. }
  404. calVal, tmpErr := calResult.Float64()
  405. if tmpErr != nil {
  406. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  407. fmt.Println(err)
  408. return
  409. }
  410. nanCheck := fmt.Sprintf("%0.f", calVal)
  411. // 分母为0.0的报错
  412. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  413. removeDateList = append(removeDateList, sk)
  414. continue
  415. }
  416. // 最近实际日期的实际数据
  417. if maxStartDate.Format(utils.FormatDate) == sk {
  418. startDateValue, _ = decimal.NewFromFloat(calVal).Truncate(4).Float64() //保留4位小数
  419. }
  420. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  421. if existVal, ok := dataMap[sk]; !ok {
  422. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  423. timestamp := dataTime.UnixNano() / 1e6
  424. timeStr := fmt.Sprintf("%d", timestamp)
  425. if _, existOk := existDataMap[sk]; !existOk {
  426. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  427. isAdd = true
  428. }
  429. existDataMap[sk] = sk
  430. } else {
  431. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  432. if tmpErr != nil {
  433. err = tmpErr
  434. return
  435. }
  436. existStr := existValDecimal.String()
  437. if existStr != saveValue {
  438. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  439. sql = fmt.Sprintf(sql, dataTableName)
  440. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  441. if err != nil {
  442. return
  443. }
  444. }
  445. }
  446. } else {
  447. //计算公式异常,那么就移除该指标
  448. removeDateList = append(removeDateList, sk)
  449. continue
  450. }
  451. }
  452. if isAdd {
  453. addSql = strings.TrimRight(addSql, ",")
  454. _, err = to.Raw(addSql).Exec()
  455. if err != nil {
  456. fmt.Println("RefreshAllCalculate add Err", err.Error())
  457. return
  458. }
  459. }
  460. if len(removeDateList) > 0 {
  461. removeDateStr := strings.Join(removeDateList, `","`)
  462. removeDateStr = `"` + removeDateStr + `"`
  463. //如果拼接指标变更了,那么需要删除所有的指标数据
  464. tableName := GetEdbDataTableName(source, subSource)
  465. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  466. _, err = to.Raw(sql, edbInfoId).Exec()
  467. if err != nil {
  468. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  469. return
  470. }
  471. }
  472. //查询预测日期
  473. if !newLatestDate.IsZero() {
  474. latestDateStr = newLatestDate.Format(utils.FormatDate)
  475. sql = fmt.Sprintf(` SELECT * FROM %s WHERE edb_info_id = ? and data_time <= ? ORDER BY data_time desc limit 1`, dataTableName)
  476. var latestDate EdbData
  477. e := to.Raw(sql, edbInfoId, latestDateStr).QueryRow(&latestDate)
  478. if e != nil {
  479. if e.Error() == utils.ErrNoRow() {
  480. //首个日期
  481. latestDateStr = maxStartDate.Format(utils.FormatDate)
  482. latestValue = startDateValue
  483. } else {
  484. err = fmt.Errorf("查询最新日期失败,Err:" + e.Error())
  485. return
  486. }
  487. } else {
  488. floatValue, _ := strconv.ParseFloat(latestDate.Value, 64)
  489. latestDateStr = latestDate.DataTime
  490. latestValue = floatValue
  491. }
  492. }
  493. return
  494. }