edb_data_calculate_avg.go 14 KB

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