edb_data_calculate_avg.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. type CalculateAvg struct {
  15. }
  16. // Add 新增
  17. func (obj CalculateAvg) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, err error, errMsg string) {
  18. req := params.Req
  19. edbCode := params.EdbCode
  20. o := orm.NewOrm()
  21. to, err := o.Begin()
  22. if err != nil {
  23. return
  24. }
  25. defer func() {
  26. if err != nil {
  27. fmt.Println("CalculateAvg.Add,Err:" + err.Error())
  28. _ = to.Rollback()
  29. } else {
  30. _ = to.Commit()
  31. }
  32. }()
  33. if req.EdbInfoId > 0 {
  34. err = errors.New("无法新增")
  35. return
  36. }
  37. edbInfo = new(EdbInfo)
  38. edbInfo.Source = obj.GetSource()
  39. edbInfo.SourceName = obj.GetSourceName()
  40. edbInfo.EdbCode = edbCode
  41. edbInfo.EdbName = req.EdbName
  42. edbInfo.EdbNameSource = req.EdbName
  43. edbInfo.Frequency = req.Frequency
  44. edbInfo.Unit = req.Unit
  45. edbInfo.ClassifyId = req.ClassifyId
  46. edbInfo.SysUserId = params.SysUserId
  47. edbInfo.SysUserRealName = params.SysUserRealName
  48. edbInfo.CreateTime = time.Now()
  49. edbInfo.ModifyTime = time.Now()
  50. edbInfo.UniqueCode = params.UniqueCode
  51. edbInfo.EdbType = obj.GetEdbType()
  52. edbInfo.EmptyType = req.EmptyType
  53. edbInfo.MaxEmptyType = req.MaxEmptyType
  54. edbInfo.Extra = req.Extra
  55. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  56. if tmpErr != nil {
  57. err = tmpErr
  58. return
  59. }
  60. edbInfo.EdbInfoId = int(newEdbInfoId)
  61. //关联关系
  62. tagMap := make(map[string]int)
  63. relationEdbInfoList := make([]*EdbInfo, 0)
  64. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  65. for k, v := range req.EdbInfoIdArr {
  66. tmpEdbInfo, e := GetEdbInfoById(v.EdbInfoId)
  67. if e != nil {
  68. err = e
  69. return
  70. }
  71. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  72. calculateMappingItem := new(EdbInfoCalculateMapping)
  73. calculateMappingItem.CreateTime = time.Now()
  74. calculateMappingItem.ModifyTime = time.Now()
  75. calculateMappingItem.Sort = k
  76. calculateMappingItem.EdbCode = edbCode
  77. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  78. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  79. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  80. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  81. calculateMappingItem.FromSource = tmpEdbInfo.Source
  82. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  83. calculateMappingItem.FromTag = v.FromTag
  84. calculateMappingItem.Source = edbInfo.Source
  85. calculateMappingItem.SourceName = edbInfo.SourceName
  86. calculateMappingItem.FromSubSource = edbInfo.SubSource
  87. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  88. tagMap[v.FromTag] = v.EdbInfoId
  89. }
  90. _, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
  91. if err != nil {
  92. return
  93. }
  94. //计算数据
  95. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.Extra, tagMap, edbInfo.EmptyType)
  96. return
  97. }
  98. func (obj CalculateAvg) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  99. req := params.Req
  100. edbInfo := params.EdbInfo
  101. o := orm.NewOrm()
  102. to, err := o.Begin()
  103. if err != nil {
  104. return
  105. }
  106. defer func() {
  107. if err != nil {
  108. fmt.Println("CalculateAvg.Edit,Err:" + err.Error())
  109. _ = to.Rollback()
  110. } else {
  111. _ = to.Commit()
  112. }
  113. }()
  114. if len(req.EdbInfoIdArr) <= 0 {
  115. err = fmt.Errorf("请选择要关联的指标")
  116. return
  117. }
  118. needCalculate := false
  119. if edbInfo.EmptyType != req.EmptyType || edbInfo.Extra != req.Extra {
  120. needCalculate = true
  121. }
  122. //修改指标信息
  123. edbInfo.EdbName = req.EdbName
  124. edbInfo.EdbNameSource = req.EdbName
  125. edbInfo.Frequency = req.Frequency
  126. edbInfo.Unit = req.Unit
  127. edbInfo.ClassifyId = req.ClassifyId
  128. edbInfo.CalculateFormula = req.Formula
  129. edbInfo.Extra = req.Extra
  130. edbInfo.EmptyType = req.EmptyType
  131. edbInfo.MaxEmptyType = req.MaxEmptyType
  132. edbInfo.ModifyTime = time.Now()
  133. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "Extra", "EmptyType", "MaxEmptyType", "ModifyTime")
  134. if err != nil {
  135. return
  136. }
  137. //判断是否重复指标
  138. //edbInfoMap := make(map[int]string)
  139. if !needCalculate {
  140. //用到的指标
  141. newEdbInfoIdArr := make([]string, 0)
  142. for _, tmpEdbInfo := range req.EdbInfoIdArr {
  143. /*_, ok := edbInfoMap[tmpEdbInfo.EdbInfoId]
  144. if ok {
  145. br.Msg = "选择指标失败,请勿选择重复指标!"
  146. return
  147. }
  148. edbInfoMap[tmpEdbInfo.EdbInfoId] = tmpEdbInfo.FromTag*/
  149. newEdbInfoIdArr = append(newEdbInfoIdArr, strconv.Itoa(tmpEdbInfo.EdbInfoId))
  150. }
  151. edbInfoIdStr := strings.Join(newEdbInfoIdArr, ",")
  152. oldEdbInfoIdStr, e := GetCalculateEdbInfo(req.EdbInfoId)
  153. if e != nil {
  154. errMsg = "获取数据失败,GetCalculateEdbInfo:" + e.Error()
  155. err = fmt.Errorf("查询关联指标失败")
  156. return
  157. }
  158. if edbInfoIdStr != oldEdbInfoIdStr { // 不需要重复计算
  159. needCalculate = true
  160. }
  161. }
  162. fmt.Printf("needCalculate:%v\n", needCalculate)
  163. if !needCalculate {
  164. return
  165. }
  166. //删除,计算指标关联的,基础指标的关联关系
  167. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  168. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  169. if err != nil {
  170. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  171. return
  172. }
  173. //清空原有数据
  174. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  175. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  176. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  177. if err != nil {
  178. return
  179. }
  180. //关联关系
  181. tagMap := make(map[string]int)
  182. relationEdbInfoList := make([]*EdbInfo, 0)
  183. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  184. for k, v := range req.EdbInfoIdArr {
  185. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  186. if tmpErr != nil {
  187. err = tmpErr
  188. return
  189. }
  190. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  191. calculateMappingItem := new(EdbInfoCalculateMapping)
  192. calculateMappingItem.CreateTime = time.Now()
  193. calculateMappingItem.ModifyTime = time.Now()
  194. calculateMappingItem.Sort = k
  195. calculateMappingItem.EdbCode = edbInfo.EdbCode
  196. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  197. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  198. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  199. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  200. calculateMappingItem.FromSource = tmpEdbInfo.Source
  201. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  202. calculateMappingItem.FromTag = v.FromTag
  203. calculateMappingItem.Source = edbInfo.Source
  204. calculateMappingItem.SourceName = edbInfo.SourceName
  205. calculateMappingItem.FromSubSource = edbInfo.SubSource
  206. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  207. tagMap[v.FromTag] = v.EdbInfoId
  208. }
  209. _, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
  210. if err != nil {
  211. return
  212. }
  213. //计算数据
  214. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.Extra, tagMap, edbInfo.EmptyType)
  215. return
  216. }
  217. func (obj CalculateAvg) Refresh(params RefreshParams) (err error, errMsg string) {
  218. edbInfo := params.EdbInfo
  219. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  220. if err != nil {
  221. return
  222. }
  223. tagMap := make(map[string]int)
  224. relationEdbInfoList := make([]*EdbInfo, 0)
  225. for _, v := range edbInfoCalculateDetailList {
  226. tagMap[v.FromTag] = v.FromEdbInfoId
  227. fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
  228. relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
  229. }
  230. o := orm.NewOrm()
  231. to, err := o.Begin()
  232. if err != nil {
  233. return
  234. }
  235. defer func() {
  236. if err != nil {
  237. fmt.Println(reflect.TypeOf(obj).Name() + ",Err:" + err.Error())
  238. _ = to.Rollback()
  239. } else {
  240. _ = to.Commit()
  241. }
  242. }()
  243. // 计算数据
  244. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.Extra, tagMap, edbInfo.EmptyType)
  245. return
  246. }
  247. func (obj CalculateAvg) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, edbInfoIdArr []*EdbInfo, edbCode, extra string, edbInfoTag map[string]int, emptyType int) (err error) {
  248. //to orm.TxOrmer, edbInfoId, source, subSource int, edbInfoIdArr []*EdbInfo, edbCode, extra string, edbInfoTag map[string]int, emptyType int
  249. realSaveDataMap := make(map[string]map[int]float64)
  250. saveDataMap := make(map[string]map[int]float64)
  251. // 最小的结束日期 , 最晚的数据开始日期
  252. var minLatestDate, maxStartDate time.Time
  253. dateList := make([]string, 0) // 最终的日期数据
  254. dateMap := make(map[string]struct{}) // 最终的日期数据
  255. edbInfoIdStr := strconv.Itoa(edbInfoId)
  256. tableName := GetEdbDataTableName(source, subSource)
  257. // 获取多指标求和关联的指标id
  258. dateTagConfig := ""
  259. if extra != "" {
  260. var dateConfig CalculateEdbExtra
  261. err = json.Unmarshal([]byte(extra), &dateConfig)
  262. if err != nil {
  263. err = fmt.Errorf("refreshAllCalculate,extra解析失败,Err:%s", err.Error())
  264. return
  265. }
  266. dateTagConfig = dateConfig.DateTag
  267. }
  268. for edbInfoIndex, v := range edbInfoIdArr {
  269. var condition string
  270. var pars []interface{}
  271. condition += " AND edb_info_id=? "
  272. pars = append(pars, v.EdbInfoId)
  273. dataList, err := GetEdbDataListAllByTo(to, condition, pars, v.Source, v.SubSource, 1)
  274. if err != nil {
  275. return err
  276. }
  277. for _, dv := range dataList {
  278. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  279. if _, ok := val[v.EdbInfoId]; !ok {
  280. val[v.EdbInfoId] = dv.Value
  281. }
  282. } else {
  283. temp := make(map[int]float64)
  284. temp[v.EdbInfoId] = dv.Value
  285. realSaveDataMap[dv.DataTime] = temp
  286. }
  287. // saveDataMap
  288. if val, ok := saveDataMap[dv.DataTime]; ok {
  289. if _, ok := val[v.EdbInfoId]; !ok {
  290. val[v.EdbInfoId] = dv.Value
  291. }
  292. } else {
  293. temp2 := make(map[int]float64)
  294. temp2[v.EdbInfoId] = dv.Value
  295. saveDataMap[dv.DataTime] = temp2
  296. }
  297. if dateTagConfig == "all" {
  298. if _, ok := dateMap[dv.DataTime]; !ok {
  299. dateList = append(dateList, dv.DataTime)
  300. dateMap[dv.DataTime] = struct{}{}
  301. }
  302. } else if dateTagConfig == "" { // 默认取第一个指标的时间序列
  303. if edbInfoIndex == 0 {
  304. if _, ok := dateMap[dv.DataTime]; !ok {
  305. dateList = append(dateList, dv.DataTime)
  306. dateMap[dv.DataTime] = struct{}{}
  307. }
  308. }
  309. } else {
  310. if eId, ok := edbInfoTag[dateTagConfig]; ok {
  311. if v.EdbInfoId == eId {
  312. if _, ok1 := dateMap[dv.DataTime]; !ok1 {
  313. dateList = append(dateList, dv.DataTime)
  314. dateMap[dv.DataTime] = struct{}{}
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. // 处理最大日期和最小日期
  322. for _, v := range dateList {
  323. tmpDate, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
  324. if minLatestDate.IsZero() || tmpDate.After(minLatestDate) {
  325. minLatestDate = tmpDate
  326. }
  327. if maxStartDate.IsZero() || tmpDate.Before(maxStartDate) {
  328. maxStartDate = tmpDate
  329. }
  330. }
  331. //数据处理,将日期内不全的数据做补全
  332. HandleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, edbInfoIdArr, emptyType)
  333. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  334. var isAdd bool
  335. //获取指标所有数据
  336. dataList := make([]*EdbData, 0)
  337. dataTableName := GetEdbDataTableName(source, subSource)
  338. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  339. sql = fmt.Sprintf(sql, dataTableName)
  340. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  341. if err != nil {
  342. return err
  343. }
  344. dataMap := make(map[string]string)
  345. removeDateMap := make(map[string]int) //需要移除的日期
  346. for _, v := range dataList {
  347. dataMap[v.DataTime] = v.Value
  348. removeDateMap[v.DataTime] = 1
  349. }
  350. existDataMap := make(map[string]string)
  351. for sk, sv := range saveDataMap {
  352. if _, ok := dateMap[sk]; !ok {
  353. continue
  354. }
  355. // 当空值处理类型选择了不计算时,只要有一个指标在某个日期没有值(即空值),则计算指标在该日期没有值
  356. if len(sv) != len(edbInfoIdArr) {
  357. continue
  358. }
  359. var calVal float64
  360. for _, value := range sv {
  361. calVal += value
  362. }
  363. calVal = calVal / float64(len(sv))
  364. // 有计算出来值,那么就从待删除指标中移除
  365. delete(removeDateMap, sk)
  366. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String()
  367. if existVal, ok := dataMap[sk]; !ok {
  368. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  369. timestamp := dataTime.UnixNano() / 1e6
  370. timeStr := fmt.Sprintf("%d", timestamp)
  371. if _, existOk := existDataMap[sk]; !existOk {
  372. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  373. isAdd = true
  374. }
  375. existDataMap[sk] = sk
  376. } else {
  377. existValDecimal, err := decimal.NewFromString(existVal)
  378. existStr := existValDecimal.String()
  379. if existStr != saveValue {
  380. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  381. sql = fmt.Sprintf(sql, dataTableName)
  382. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  383. if err != nil {
  384. return err
  385. }
  386. }
  387. }
  388. }
  389. if isAdd {
  390. addSql = strings.TrimRight(addSql, ",")
  391. _, err = to.Raw(addSql).Exec()
  392. if err != nil {
  393. fmt.Println("RefreshAllCalculate add Err", err.Error())
  394. return
  395. }
  396. }
  397. if len(removeDateMap) > 0 {
  398. removeDateList := make([]string, 0) //需要移除的日期
  399. for k := range removeDateMap {
  400. removeDateList = append(removeDateList, k)
  401. }
  402. removeDateStr := strings.Join(removeDateList, `","`)
  403. removeDateStr = `"` + removeDateStr + `"`
  404. //如果拼接指标变更了,那么需要删除所有的指标数据
  405. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  406. _, err = to.Raw(sql, edbInfoId).Exec()
  407. if err != nil {
  408. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  409. return
  410. }
  411. }
  412. return
  413. }
  414. // GetSource 获取来源编码id
  415. func (obj CalculateAvg) GetSource() int {
  416. return utils.DATA_SOURCE_CALCULATE_AVG
  417. }
  418. // GetSourceName 获取来源名称
  419. func (obj CalculateAvg) GetSourceName() string {
  420. return utils.DATA_SOURCE_NAME_CALCULATE_AVG
  421. }
  422. // GetEdbType 获取指标类型
  423. func (obj CalculateAvg) GetEdbType() int {
  424. return utils.CALCULATE_EDB_TYPE
  425. }