edb_data_calculate_avg.go 14 KB

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