predict_edb_data_calculate_percentile.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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: req.EdbName,
  63. UnitEn: req.Unit,
  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. switch params.Lang {
  127. case utils.EnLangVersion:
  128. edbInfo.EdbNameEn = req.EdbName
  129. edbInfo.UnitEn = req.Unit
  130. default:
  131. edbInfo.EdbName = req.EdbName
  132. edbInfo.Unit = req.Unit
  133. edbInfo.EdbNameSource = req.EdbName
  134. }
  135. edbInfo.Frequency = req.Frequency
  136. edbInfo.ClassifyId = req.ClassifyId
  137. edbInfo.CalculateFormula = req.Formula
  138. edbInfo.ModifyTime = time.Now()
  139. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  140. if err != nil {
  141. return
  142. }
  143. var existCondition string
  144. var existPars []interface{}
  145. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  146. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  147. //判断计算指标是否被更换
  148. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  149. if err != nil {
  150. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  151. return
  152. }
  153. if count > 0 { // 指标未被替换,无需删除关联数据
  154. // 频度被换了,需要重新计算
  155. if isRecalculate {
  156. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  157. }
  158. return
  159. }
  160. //删除,计算指标关联的,基础指标的关联关系
  161. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  162. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  163. if err != nil {
  164. return
  165. }
  166. //清空原有数据
  167. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  168. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  169. if err != nil {
  170. return
  171. }
  172. //关联关系
  173. {
  174. calculateMappingItem := &EdbInfoCalculateMapping{
  175. EdbInfoCalculateMappingId: 0,
  176. EdbInfoId: edbInfo.EdbInfoId,
  177. Source: obj.GetSource(),
  178. SourceName: obj.GetSourceName(),
  179. EdbCode: edbInfo.EdbCode,
  180. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  181. FromEdbCode: fromEdbInfo.EdbCode,
  182. FromEdbName: fromEdbInfo.EdbName,
  183. FromSource: fromEdbInfo.Source,
  184. FromSourceName: fromEdbInfo.SourceName,
  185. FromTag: "",
  186. Sort: 1,
  187. CreateTime: time.Now(),
  188. ModifyTime: time.Now(),
  189. }
  190. _, err = to.Insert(calculateMappingItem)
  191. if err != nil {
  192. return
  193. }
  194. }
  195. //计算数据
  196. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  197. return
  198. }
  199. // Refresh 刷新
  200. func (obj PredictPercentile) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  201. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  202. if err != nil {
  203. return
  204. }
  205. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  206. if err != nil {
  207. errMsg = "GetEdbInfoById Err:" + err.Error()
  208. return
  209. }
  210. o := orm.NewOrm()
  211. to, err := o.Begin()
  212. if err != nil {
  213. return
  214. }
  215. defer func() {
  216. if err != nil {
  217. _ = to.Rollback()
  218. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  219. } else {
  220. _ = to.Commit()
  221. }
  222. }()
  223. // 计算数据
  224. latestDateStr, latestValue, err, errMsg = obj.refresh(to, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  225. return
  226. }
  227. // GetSource 获取来源编码id
  228. func (obj PredictPercentile) GetSource() int {
  229. return utils.DATA_SOURCE_PREDICT_CALCULATE_PERCENTILE
  230. }
  231. // GetSourceName 获取来源名称
  232. func (obj PredictPercentile) GetSourceName() string {
  233. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_PERCENTILE
  234. }
  235. func (obj PredictPercentile) refresh(to orm.TxOrmer, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error, errMsg string) {
  236. edbInfoId := edbInfo.EdbInfoId
  237. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  238. edbInfoIdStr := strconv.Itoa(edbInfoId)
  239. var percentileConfig PercentileConfig
  240. err = json.Unmarshal([]byte(edbInfo.CalculateFormula), &percentileConfig)
  241. if err != nil {
  242. return
  243. }
  244. // 获取百分位的指标数据
  245. fromDataList, err, errMsg := obj.getPercentileData(fromEdbInfo, percentileConfig.CalculateValue, percentileConfig.CalculateUnit)
  246. if err != nil {
  247. return
  248. }
  249. //获取指标所有数据
  250. existDataList := make([]*EdbData, 0)
  251. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  252. sql = fmt.Sprintf(sql, dataTableName)
  253. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  254. if err != nil {
  255. return
  256. }
  257. existDataMap := make(map[string]string)
  258. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  259. for _, v := range existDataList {
  260. existDataMap[v.DataTime] = v.Value
  261. removeDataTimeMap[v.DataTime] = 1
  262. }
  263. needAddDateMap := make(map[time.Time]int)
  264. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  265. var isAdd bool
  266. for _, tmpData := range fromDataList {
  267. currDateStr := tmpData.DataTime
  268. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  269. if tmpErr != nil {
  270. err = tmpErr
  271. return
  272. }
  273. // 当前的实际值
  274. saveValue := decimal.NewFromFloat(tmpData.Value).Round(4).String()
  275. existVal, ok := existDataMap[currDateStr]
  276. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  277. if ok {
  278. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  279. delete(removeDataTimeMap, currDateStr)
  280. if existVal != saveValue {
  281. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  282. sql = fmt.Sprintf(sql, dataTableName)
  283. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  284. if err != nil {
  285. return
  286. }
  287. }
  288. continue
  289. }
  290. // 库中不存在该日期的数据
  291. timestamp := currTime.UnixNano() / 1e6
  292. timeStr := fmt.Sprintf("%d", timestamp)
  293. if _, existOk := needAddDateMap[currTime]; !existOk {
  294. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  295. isAdd = true
  296. }
  297. needAddDateMap[currTime] = 1
  298. }
  299. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  300. {
  301. removeDateList := make([]string, 0)
  302. for dateTime := range removeDataTimeMap {
  303. removeDateList = append(removeDateList, dateTime)
  304. }
  305. removeNum := len(removeDateList)
  306. if removeNum > 0 {
  307. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  308. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  309. if err != nil {
  310. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  311. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  312. return
  313. }
  314. }
  315. }
  316. if isAdd {
  317. addSql = strings.TrimRight(addSql, ",")
  318. _, err = to.Raw(addSql).Exec()
  319. if err != nil {
  320. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  321. return
  322. }
  323. }
  324. //确定实际数据的最终值
  325. {
  326. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
  327. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  328. return
  329. }
  330. if tmpErr == nil {
  331. latestDateStr = finalLast.DataTime
  332. latestValue = finalLast.Value
  333. }
  334. }
  335. return
  336. }
  337. // GetPercentileData 获取百分位的指标数据
  338. func (obj PredictPercentile) getPercentileData(fromEdbInfo *EdbInfo, calculateValue int, calculateUnit string) (newDataList []EdbInfoSearchData, err error, errMsg string) {
  339. // 获取时间基准指标在时间区间内的值
  340. dataList := make([]*EdbInfoSearchData, 0)
  341. switch fromEdbInfo.EdbInfoType {
  342. case 0:
  343. //获取来源指标的数据
  344. dataList, err = GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  345. EdbInfoId: fromEdbInfo.EdbInfoId,
  346. }, 1)
  347. case 1:
  348. dataList, err = GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, "")
  349. default:
  350. err = errors.New(fmt.Sprint("获取失败,指标base类型异常", fromEdbInfo.EdbInfoType))
  351. return
  352. }
  353. moveUnitDays, ok := utils.FrequencyDaysMap[calculateUnit]
  354. if !ok {
  355. errMsg = `错误的周期`
  356. err = errors.New(errMsg)
  357. return
  358. }
  359. calculateDay := calculateValue * moveUnitDays
  360. // 指标对应的所有数据
  361. newDataList = make([]EdbInfoSearchData, 0)
  362. dataMap := make(map[time.Time]float64, 0)
  363. for _, tmpData := range dataList {
  364. currDateTime, _ := time.ParseInLocation(utils.FormatDate, tmpData.DataTime, time.Local)
  365. dataMap[currDateTime] = tmpData.Value
  366. }
  367. //百分位:对所选指标滚动地取对应时间长度的数据值,取最大值Max,最小值Min,计算Max-Min,百分位=(现值-Min)/(Max-Min),Max=Min时不予计算。
  368. for i, tmpData := range dataList {
  369. currDateTime, _ := time.ParseInLocation(utils.FormatDate, tmpData.DataTime, time.Local)
  370. maxVal := tmpData.Value
  371. minVal := tmpData.Value
  372. for k := 0; k < calculateDay; k++ {
  373. preVal, ok2 := dataMap[currDateTime.AddDate(0, 0, -k)]
  374. if ok2 {
  375. if preVal > maxVal {
  376. maxVal = preVal
  377. }
  378. if preVal < minVal {
  379. minVal = preVal
  380. }
  381. }
  382. }
  383. if maxVal == minVal {
  384. continue
  385. }
  386. tmpV := (tmpData.Value - minVal) / (maxVal - minVal) * 100
  387. tmpV, _ = decimal.NewFromFloat(tmpV).Round(4).Float64()
  388. //百分位=(现值-Min)/(Max-Min)
  389. newDataList = append(newDataList, EdbInfoSearchData{
  390. EdbDataId: i,
  391. DataTime: dataList[i].DataTime,
  392. Value: tmpV,
  393. })
  394. }
  395. return
  396. }