edb_data_calculate_sum.go 14 KB

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