edb_data_calculate_percentile.go 14 KB

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