predict_edb_data_calculate_percentile.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/utils"
  6. "fmt"
  7. "github.com/beego/beego/v2/client/orm"
  8. "github.com/shopspring/decimal"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // PredictPercentile 预测累计值年初至今
  15. type PredictPercentile struct {
  16. }
  17. // Add 添加
  18. func (obj PredictPercentile) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  19. req := params.Req
  20. fromEdbInfo := params.FromEdbInfo
  21. edbCode := params.EdbCode
  22. o := orm.NewOrm()
  23. to, err := o.Begin()
  24. if err != nil {
  25. return
  26. }
  27. defer func() {
  28. if err != nil {
  29. _ = to.Rollback()
  30. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  31. } else {
  32. _ = to.Commit()
  33. }
  34. }()
  35. edbInfo = &EdbInfo{
  36. //EdbInfoId: 0,
  37. SourceName: obj.GetSourceName(),
  38. Source: obj.GetSource(),
  39. EdbCode: edbCode,
  40. EdbName: req.EdbName,
  41. EdbNameSource: req.EdbName,
  42. Frequency: req.Frequency,
  43. Unit: req.Unit,
  44. StartDate: "",
  45. EndDate: "",
  46. ClassifyId: req.ClassifyId,
  47. SysUserId: params.SysUserId,
  48. SysUserRealName: params.SysUserRealName,
  49. UniqueCode: params.UniqueCode,
  50. CreateTime: time.Now(),
  51. ModifyTime: time.Now(),
  52. MinValue: 0,
  53. MaxValue: 0,
  54. CalculateFormula: req.Formula,
  55. EdbType: 2,
  56. Sort: 0,
  57. MoveType: 0,
  58. MoveFrequency: "",
  59. NoUpdate: 0,
  60. ServerUrl: "",
  61. EdbInfoType: 1,
  62. EdbNameEn: "",
  63. UnitEn: "",
  64. LatestDate: "",
  65. LatestValue: 0,
  66. ChartImage: "",
  67. Calendar: "",
  68. }
  69. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  70. if tmpErr != nil {
  71. err = tmpErr
  72. return
  73. }
  74. edbInfo.EdbInfoId = int(newEdbInfoId)
  75. //关联关系
  76. {
  77. calculateMappingItem := new(EdbInfoCalculateMapping)
  78. calculateMappingItem.CreateTime = time.Now()
  79. calculateMappingItem.ModifyTime = time.Now()
  80. calculateMappingItem.Sort = 1
  81. calculateMappingItem.EdbCode = edbCode
  82. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  83. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  84. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  85. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  86. calculateMappingItem.FromSource = fromEdbInfo.Source
  87. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  88. calculateMappingItem.FromTag = ""
  89. calculateMappingItem.Source = edbInfo.Source
  90. calculateMappingItem.SourceName = edbInfo.SourceName
  91. _, err = to.Insert(calculateMappingItem)
  92. if err != nil {
  93. return
  94. }
  95. }
  96. //计算数据
  97. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  98. return
  99. }
  100. // Edit 编辑
  101. func (obj PredictPercentile) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  102. req := params.Req
  103. edbInfo := params.EdbInfo
  104. fromEdbInfo := params.FromEdbInfo
  105. latestDateStr = edbInfo.LatestDate
  106. latestValue = edbInfo.LatestValue
  107. o := orm.NewOrm()
  108. to, err := o.Begin()
  109. if err != nil {
  110. return
  111. }
  112. defer func() {
  113. if err != nil {
  114. _ = to.Rollback()
  115. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  116. } else {
  117. _ = to.Commit()
  118. }
  119. }()
  120. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  121. var isRecalculate bool
  122. if edbInfo.CalculateFormula != req.Formula {
  123. isRecalculate = true
  124. }
  125. //修改指标信息
  126. edbInfo.EdbName = req.EdbName
  127. edbInfo.EdbNameSource = req.EdbName
  128. edbInfo.Frequency = req.Frequency
  129. edbInfo.Unit = req.Unit
  130. edbInfo.ClassifyId = req.ClassifyId
  131. edbInfo.CalculateFormula = req.Formula
  132. edbInfo.ModifyTime = time.Now()
  133. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  134. if err != nil {
  135. return
  136. }
  137. var existCondition string
  138. var existPars []interface{}
  139. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  140. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  141. //判断计算指标是否被更换
  142. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  143. if err != nil {
  144. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  145. return
  146. }
  147. if count > 0 { // 指标未被替换,无需删除关联数据
  148. // 频度被换了,需要重新计算
  149. if isRecalculate {
  150. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  151. }
  152. return
  153. }
  154. //删除,计算指标关联的,基础指标的关联关系
  155. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  156. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  157. if err != nil {
  158. return
  159. }
  160. //清空原有数据
  161. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  162. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  163. if err != nil {
  164. return
  165. }
  166. //关联关系
  167. {
  168. calculateMappingItem := &EdbInfoCalculateMapping{
  169. EdbInfoCalculateMappingId: 0,
  170. EdbInfoId: edbInfo.EdbInfoId,
  171. Source: obj.GetSource(),
  172. SourceName: obj.GetSourceName(),
  173. EdbCode: edbInfo.EdbCode,
  174. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  175. FromEdbCode: fromEdbInfo.EdbCode,
  176. FromEdbName: fromEdbInfo.EdbName,
  177. FromSource: fromEdbInfo.Source,
  178. FromSourceName: fromEdbInfo.SourceName,
  179. FromTag: "",
  180. Sort: 1,
  181. CreateTime: time.Now(),
  182. ModifyTime: time.Now(),
  183. }
  184. _, err = to.Insert(calculateMappingItem)
  185. if err != nil {
  186. return
  187. }
  188. }
  189. //计算数据
  190. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  191. return
  192. }
  193. // Refresh 刷新
  194. func (obj PredictPercentile) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  195. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  196. if err != nil {
  197. return
  198. }
  199. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  200. if err != nil {
  201. errMsg = "GetEdbInfoById Err:" + err.Error()
  202. return
  203. }
  204. o := orm.NewOrm()
  205. to, err := o.Begin()
  206. if err != nil {
  207. return
  208. }
  209. defer func() {
  210. if err != nil {
  211. _ = to.Rollback()
  212. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  213. } else {
  214. _ = to.Commit()
  215. }
  216. }()
  217. // 计算数据
  218. latestDateStr, latestValue, err, errMsg = obj.refresh(to, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  219. return
  220. }
  221. // GetSource 获取来源编码id
  222. func (obj PredictPercentile) GetSource() int {
  223. return utils.DATA_SOURCE_PREDICT_CALCULATE_PERCENTILE
  224. }
  225. // GetSourceName 获取来源名称
  226. func (obj PredictPercentile) GetSourceName() string {
  227. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_PERCENTILE
  228. }
  229. func (obj PredictPercentile) refresh(to orm.TxOrmer, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error, errMsg string) {
  230. edbInfoId := edbInfo.EdbInfoId
  231. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  232. edbInfoIdStr := strconv.Itoa(edbInfoId)
  233. var percentileConfig PercentileConfig
  234. err = json.Unmarshal([]byte(edbInfo.CalculateFormula), &percentileConfig)
  235. if err != nil {
  236. return
  237. }
  238. // 获取百分位的指标数据
  239. fromDataList, err, errMsg := obj.getPercentileData(fromEdbInfo, percentileConfig.CalculateValue, percentileConfig.CalculateUnit)
  240. if err != nil {
  241. return
  242. }
  243. //获取指标所有数据
  244. existDataList := make([]*EdbData, 0)
  245. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  246. sql = fmt.Sprintf(sql, dataTableName)
  247. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  248. if err != nil {
  249. return
  250. }
  251. existDataMap := make(map[string]string)
  252. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  253. for _, v := range existDataList {
  254. existDataMap[v.DataTime] = v.Value
  255. removeDataTimeMap[v.DataTime] = 1
  256. }
  257. needAddDateMap := make(map[time.Time]int)
  258. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  259. var isAdd bool
  260. for _, tmpData := range fromDataList {
  261. currDateStr := tmpData.DataTime
  262. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  263. if tmpErr != nil {
  264. err = tmpErr
  265. return
  266. }
  267. // 当前的实际值
  268. saveValue := decimal.NewFromFloat(tmpData.Value).Round(4).String()
  269. existVal, ok := existDataMap[currDateStr]
  270. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  271. if ok {
  272. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  273. delete(removeDataTimeMap, currDateStr)
  274. if existVal != saveValue {
  275. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  276. sql = fmt.Sprintf(sql, dataTableName)
  277. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  278. if err != nil {
  279. return
  280. }
  281. }
  282. continue
  283. }
  284. // 库中不存在该日期的数据
  285. timestamp := currTime.UnixNano() / 1e6
  286. timeStr := fmt.Sprintf("%d", timestamp)
  287. if _, existOk := needAddDateMap[currTime]; !existOk {
  288. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  289. isAdd = true
  290. }
  291. needAddDateMap[currTime] = 1
  292. }
  293. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  294. {
  295. removeDateList := make([]string, 0)
  296. for dateTime := range removeDataTimeMap {
  297. removeDateList = append(removeDateList, dateTime)
  298. }
  299. removeNum := len(removeDateList)
  300. if removeNum > 0 {
  301. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  302. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  303. if err != nil {
  304. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  305. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  306. return
  307. }
  308. }
  309. }
  310. if isAdd {
  311. addSql = strings.TrimRight(addSql, ",")
  312. _, err = to.Raw(addSql).Exec()
  313. if err != nil {
  314. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  315. return
  316. }
  317. }
  318. //确定实际数据的最终值
  319. {
  320. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
  321. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  322. return
  323. }
  324. if tmpErr == nil {
  325. latestDateStr = finalLast.DataTime
  326. latestValue = finalLast.Value
  327. }
  328. }
  329. return
  330. }
  331. // GetPercentileData 获取百分位的指标数据
  332. func (obj PredictPercentile) getPercentileData(fromEdbInfo *EdbInfo, calculateValue int, calculateUnit string) (newDataList []EdbInfoSearchData, err error, errMsg string) {
  333. // 获取时间基准指标在时间区间内的值
  334. dataList := make([]*EdbInfoSearchData, 0)
  335. switch fromEdbInfo.EdbInfoType {
  336. case 0:
  337. var condition string
  338. var pars []interface{}
  339. condition += " AND edb_info_id=? "
  340. pars = append(pars, fromEdbInfo.EdbInfoId)
  341. //获取来源指标的数据
  342. dataList, err = GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 1)
  343. case 1:
  344. dataList, err = GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, "")
  345. default:
  346. err = errors.New(fmt.Sprint("获取失败,指标base类型异常", fromEdbInfo.EdbInfoType))
  347. return
  348. }
  349. moveUnitDays, ok := utils.FrequencyDaysMap[calculateUnit]
  350. if !ok {
  351. errMsg = `错误的周期`
  352. err = errors.New(errMsg)
  353. return
  354. }
  355. calculateDay := calculateValue * moveUnitDays
  356. // 指标对应的所有数据
  357. newDataList = make([]EdbInfoSearchData, 0)
  358. dataMap := make(map[time.Time]float64, 0)
  359. for _, tmpData := range dataList {
  360. currDateTime, _ := time.ParseInLocation(utils.FormatDate, tmpData.DataTime, time.Local)
  361. dataMap[currDateTime] = tmpData.Value
  362. }
  363. //百分位:对所选指标滚动地取对应时间长度的数据值,取最大值Max,最小值Min,计算Max-Min,百分位=(现值-Min)/(Max-Min),Max=Min时不予计算。
  364. for i, tmpData := range dataList {
  365. currDateTime, _ := time.ParseInLocation(utils.FormatDate, tmpData.DataTime, time.Local)
  366. maxVal := tmpData.Value
  367. minVal := tmpData.Value
  368. for k := 0; k < calculateDay; k++ {
  369. preVal, ok2 := dataMap[currDateTime.AddDate(0, 0, -k)]
  370. if ok2 {
  371. if preVal > maxVal {
  372. maxVal = preVal
  373. }
  374. if preVal < minVal {
  375. minVal = preVal
  376. }
  377. }
  378. }
  379. if maxVal == minVal {
  380. continue
  381. }
  382. tmpV := (tmpData.Value - minVal) / (maxVal - minVal) * 100
  383. tmpV, _ = decimal.NewFromFloat(tmpV).Round(4).Float64()
  384. //百分位=(现值-Min)/(Max-Min)
  385. newDataList = append(newDataList, EdbInfoSearchData{
  386. EdbDataId: i,
  387. DataTime: dataList[i].DataTime,
  388. Value: tmpV,
  389. })
  390. }
  391. return
  392. }