edb_data_calculate_sum.go 13 KB

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