base_predict_from_calculate.go 17 KB

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