edb_data_calculate_percentile.go 13 KB

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