edb_data_calculate_tbz.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package models
  2. import (
  3. "errors"
  4. "eta_gn/eta_index_lib/global"
  5. "eta_gn/eta_index_lib/utils"
  6. "fmt"
  7. "github.com/shopspring/decimal"
  8. "gorm.io/gorm"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // AddCalculateTbz 同比值
  14. func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  15. to := global.DEFAULT_DmSQL.Begin()
  16. defer func() {
  17. if err != nil {
  18. to.Rollback()
  19. } else {
  20. to.Commit()
  21. }
  22. }()
  23. if req.EdbInfoId <= 0 {
  24. edbInfo = new(EdbInfo)
  25. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TBZ
  26. edbInfo.SourceName = "同比值"
  27. edbInfo.EdbCode = edbCode
  28. edbInfo.EdbName = req.EdbName
  29. edbInfo.EdbNameSource = req.EdbName
  30. edbInfo.Frequency = req.Frequency
  31. edbInfo.Unit = req.Unit
  32. edbInfo.ClassifyId = req.ClassifyId
  33. edbInfo.SysUserId = sysUserId
  34. edbInfo.SysUserRealName = sysUserRealName
  35. edbInfo.CreateTime = time.Now()
  36. edbInfo.ModifyTime = time.Now()
  37. edbInfo.UniqueCode = uniqueCode
  38. edbInfo.CalculateFormula = req.Formula
  39. edbInfo.EdbNameEn = req.EdbName
  40. edbInfo.UnitEn = req.Unit
  41. edbInfo.EdbType = 2
  42. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  43. tmpErr := to.Create(edbInfo).Error
  44. if tmpErr != nil {
  45. err = tmpErr
  46. return
  47. }
  48. //关联关系
  49. {
  50. calculateMappingItem := new(EdbInfoCalculateMapping)
  51. calculateMappingItem.CreateTime = time.Now()
  52. calculateMappingItem.ModifyTime = time.Now()
  53. calculateMappingItem.Sort = 1
  54. calculateMappingItem.EdbCode = edbCode
  55. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  56. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  57. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  58. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  59. calculateMappingItem.FromSource = fromEdbInfo.Source
  60. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  61. calculateMappingItem.FromTag = ""
  62. calculateMappingItem.Source = edbInfo.Source
  63. calculateMappingItem.SourceName = edbInfo.SourceName
  64. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  65. err = to.Create(calculateMappingItem).Error
  66. if err != nil {
  67. return
  68. }
  69. }
  70. } else {
  71. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  72. if err != nil {
  73. return
  74. }
  75. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TBZ, utils.DATA_SUB_SOURCE_EDB)
  76. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  77. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  78. err = to.Exec(deleteSql, req.EdbInfoId).Error
  79. if err != nil {
  80. return
  81. }
  82. }
  83. //计算数据
  84. err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbCode, "", "")
  85. return
  86. }
  87. // EditCalculateTbz 同比值
  88. func EditCalculateTbz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  89. to := global.DEFAULT_DmSQL.Begin()
  90. defer func() {
  91. if err != nil {
  92. to.Rollback()
  93. } else {
  94. to.Commit()
  95. }
  96. }()
  97. //修改指标信息
  98. edbInfo.EdbName = req.EdbName
  99. edbInfo.EdbNameSource = req.EdbName
  100. edbInfo.Frequency = req.Frequency
  101. edbInfo.Unit = req.Unit
  102. edbInfo.ClassifyId = req.ClassifyId
  103. edbInfo.EdbNameEn = req.EdbNameEn
  104. edbInfo.UnitEn = req.UnitEn
  105. edbInfo.ModifyTime = time.Now()
  106. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  107. if err != nil {
  108. return
  109. }
  110. //判断计算指标是否被更换
  111. var existCondition string
  112. var existPars []interface{}
  113. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  114. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  115. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  116. if err != nil {
  117. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  118. return
  119. }
  120. if count > 0 { // 指标未被替换,无需重新计算
  121. return
  122. }
  123. //删除,计算指标关联的,基础指标的关联关系
  124. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  125. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  126. if err != nil {
  127. return
  128. }
  129. //清空原有数据
  130. sql = ` DELETE FROM edb_data_calculate_tbz WHERE edb_info_id = ? `
  131. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  132. if err != nil {
  133. return
  134. }
  135. //关联关系
  136. {
  137. calculateMappingItem := &EdbInfoCalculateMapping{
  138. EdbInfoCalculateMappingId: 0,
  139. EdbInfoId: edbInfo.EdbInfoId,
  140. Source: utils.DATA_SOURCE_CALCULATE_TBZ,
  141. SourceName: "同比值",
  142. EdbCode: edbInfo.EdbCode,
  143. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  144. FromEdbCode: fromEdbInfo.EdbCode,
  145. FromEdbName: fromEdbInfo.EdbName,
  146. FromSource: fromEdbInfo.Source,
  147. FromSourceName: fromEdbInfo.SourceName,
  148. FromTag: "",
  149. Sort: 1,
  150. CreateTime: time.Now(),
  151. ModifyTime: time.Now(),
  152. FromSubSource: fromEdbInfo.SubSource,
  153. }
  154. err = to.Create(calculateMappingItem).Error
  155. if err != nil {
  156. return
  157. }
  158. }
  159. //计算数据
  160. err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  161. return
  162. }
  163. // RefreshAllCalculateTbz 刷新所有同比值数据
  164. func RefreshAllCalculateTbz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  165. to := global.DEFAULT_DmSQL.Begin()
  166. defer func() {
  167. if err != nil {
  168. to.Rollback()
  169. } else {
  170. to.Commit()
  171. }
  172. }()
  173. //计算数据
  174. err = refreshAllCalculateTbz(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate)
  175. return
  176. }
  177. // refreshAllCalculateTbz
  178. func refreshAllCalculateTbz(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  179. edbInfoIdStr := strconv.Itoa(edbInfoId)
  180. //计算数据
  181. // 获取来源指标数据
  182. dataList, err := GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  183. EdbInfoId: fromEdbInfo.EdbInfoId,
  184. //StartDataTime: startDate,
  185. //StartDataTimeCond: ">=",
  186. }, 0)
  187. if err != nil {
  188. return err
  189. }
  190. // 来源指标数据参与计算
  191. calculateDataList, err := EdbInfoSearchDataToEdbInfoData(dataList)
  192. if err != nil {
  193. return err
  194. }
  195. baseCalculate := BaseCalculate{
  196. DataList: calculateDataList,
  197. Frequency: fromEdbInfo.Frequency,
  198. Source: 3,
  199. }
  200. dateDataMap, err, _ := baseCalculate.Tbz()
  201. if err != nil {
  202. return err
  203. }
  204. dataTableName := GetEdbDataTableName(source, subSource)
  205. //获取指标所有数据
  206. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  207. if err != nil {
  208. return err
  209. }
  210. existDataMap := make(map[string]string)
  211. removeDataTimeMap := make(map[string]bool) //需要移除的日期数据
  212. for _, v := range existDataList {
  213. existDataMap[v.DataTime] = v.Value
  214. removeDataTimeMap[v.DataTime] = true
  215. }
  216. //fmt.Println("existDataMap:", existDataMap)
  217. addSql := ` INSERT INTO edb_data_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  218. var isAdd bool
  219. existAddDataMap := make(map[string]string)
  220. for currentDate, valFloat := range dateDataMap {
  221. currentDateStr := currentDate.Format(utils.FormatDate)
  222. timestamp := currentDate.UnixNano() / 1e6
  223. timestampStr := fmt.Sprintf("%d", timestamp)
  224. val := decimal.NewFromFloat(valFloat).String()
  225. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  226. delete(removeDataTimeMap, currentDateStr)
  227. if existVal, ok := existDataMap[currentDateStr]; !ok {
  228. if _, existOk := existAddDataMap[currentDateStr]; !existOk {
  229. addSql += GetAddSql(edbInfoIdStr, edbCode, currentDateStr, timestampStr, val)
  230. isAdd = true
  231. }
  232. existAddDataMap[currentDateStr] = currentDateStr
  233. } else {
  234. existValDecimal, err := decimal.NewFromString(existVal)
  235. existStr := existValDecimal.String()
  236. if existStr != val {
  237. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  238. sql = fmt.Sprintf(sql, dataTableName)
  239. err = to.Exec(sql, val, edbInfoId, currentDateStr).Error
  240. if err != nil {
  241. return err
  242. }
  243. }
  244. }
  245. }
  246. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  247. {
  248. removeDateList := make([]string, 0)
  249. for dateTime := range removeDataTimeMap {
  250. removeDateList = append(removeDateList, dateTime)
  251. }
  252. removeNum := len(removeDateList)
  253. if removeNum > 0 {
  254. //如果拼接指标变更了,那么需要删除所有的指标数据
  255. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  256. err = to.Exec(sql, edbInfoId, removeDateList).Error
  257. if err != nil {
  258. err = fmt.Errorf("删除自有数据的明细数据失败,Err:" + err.Error())
  259. return
  260. }
  261. }
  262. }
  263. if isAdd {
  264. addSql = strings.TrimRight(addSql, ",")
  265. err = to.Exec(addSql).Error
  266. if err != nil {
  267. return err
  268. }
  269. }
  270. return
  271. }