edb_data_calculate_bp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. // AddCalculateBp 升频
  14. func AddCalculateBp(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_BP
  26. edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_BP
  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.EmptyType = req.EmptyType
  43. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  44. tmpErr := to.Create(edbInfo).Error
  45. if tmpErr != nil {
  46. err = tmpErr
  47. return
  48. }
  49. newEdbInfoId := edbInfo.EdbInfoId
  50. edbInfo.EdbInfoId = newEdbInfoId
  51. //关联关系
  52. {
  53. calculateMappingItem := new(EdbInfoCalculateMapping)
  54. calculateMappingItem.CreateTime = time.Now()
  55. calculateMappingItem.ModifyTime = time.Now()
  56. calculateMappingItem.Sort = 1
  57. calculateMappingItem.EdbCode = edbCode
  58. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  59. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  60. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  61. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  62. calculateMappingItem.FromSource = fromEdbInfo.Source
  63. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  64. calculateMappingItem.FromTag = ""
  65. calculateMappingItem.Source = edbInfo.Source
  66. calculateMappingItem.SourceName = edbInfo.SourceName
  67. calculateMappingItem.FromSubSource = edbInfo.SubSource
  68. err = to.Create(calculateMappingItem).Error
  69. if err != nil {
  70. return
  71. }
  72. }
  73. } else {
  74. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  75. if err != nil {
  76. return
  77. }
  78. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_BP, utils.DATA_SUB_SOURCE_EDB)
  79. fmt.Println("dataTableName:" + dataTableName)
  80. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  81. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  82. err = to.Exec(deleteSql, req.EdbInfoId).Error
  83. if err != nil {
  84. return
  85. }
  86. }
  87. //计算数据
  88. err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", 0, edbInfo.EmptyType)
  89. return
  90. }
  91. // EditCalculateBp 修改升频数据
  92. func EditCalculateBp(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  93. to := global.DEFAULT_DmSQL.Begin()
  94. defer func() {
  95. if err != nil {
  96. to.Rollback()
  97. } else {
  98. to.Commit()
  99. }
  100. }()
  101. oldEmptyType := edbInfo.EmptyType
  102. //修改指标信息
  103. edbInfo.EdbName = req.EdbName
  104. edbInfo.EdbNameSource = req.EdbName
  105. edbInfo.Frequency = req.Frequency
  106. edbInfo.Unit = req.Unit
  107. edbInfo.ClassifyId = req.ClassifyId
  108. edbInfo.EdbNameEn = req.EdbNameEn
  109. edbInfo.UnitEn = req.UnitEn
  110. edbInfo.ModifyTime = time.Now()
  111. edbInfo.EmptyType = req.EmptyType
  112. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn", "EmptyType"}).Updates(edbInfo).Error
  113. if err != nil {
  114. return
  115. }
  116. //判断计算指标是否被更换
  117. var existCondition string
  118. var existPars []interface{}
  119. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  120. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  121. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  122. if err != nil {
  123. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  124. return
  125. }
  126. if count > 0 && oldEmptyType == req.EmptyType { // 指标未被替换,无需重新计算
  127. return
  128. }
  129. //删除,计算指标关联的,基础指标的关联关系
  130. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  131. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  132. if err != nil {
  133. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  134. return
  135. }
  136. //清空原有数据
  137. sql = ` DELETE FROM edb_data_calculate_bp WHERE edb_info_id = ? `
  138. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  139. if err != nil {
  140. return
  141. }
  142. //关联关系
  143. {
  144. calculateMappingItem := &EdbInfoCalculateMapping{
  145. EdbInfoCalculateMappingId: 0,
  146. EdbInfoId: edbInfo.EdbInfoId,
  147. Source: utils.DATA_SOURCE_CALCULATE_BP,
  148. SourceName: utils.DATA_SOURCE_NAME_CALCULATE_BP,
  149. EdbCode: edbInfo.EdbCode,
  150. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  151. FromEdbCode: fromEdbInfo.EdbCode,
  152. FromEdbName: fromEdbInfo.EdbName,
  153. FromSource: fromEdbInfo.Source,
  154. FromSourceName: fromEdbInfo.SourceName,
  155. FromTag: "",
  156. Sort: 1,
  157. CreateTime: time.Now(),
  158. ModifyTime: time.Now(),
  159. FromSubSource: fromEdbInfo.SubSource,
  160. }
  161. err = to.Create(calculateMappingItem).Error
  162. if err != nil {
  163. return
  164. }
  165. }
  166. //计算数据
  167. err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", 0, edbInfo.EmptyType)
  168. return
  169. }
  170. func RefreshAllCalculateBp(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, emptyType int) (err error) {
  171. to := global.DEFAULT_DmSQL.Begin()
  172. defer func() {
  173. if err != nil {
  174. to.Rollback()
  175. } else {
  176. to.Commit()
  177. }
  178. }()
  179. // 计算数据
  180. err = refreshAllCalculateBp(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, 0, emptyType)
  181. return
  182. }
  183. // refreshAllCalculateBp 刷新升频数据
  184. func refreshAllCalculateBp(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, order int, emptyType int) (err error) {
  185. edbInfoIdStr := strconv.Itoa(edbInfoId)
  186. //计算数据
  187. //获取来源指标的数据
  188. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  189. EdbInfoId: fromEdbInfo.EdbInfoId,
  190. }, order)
  191. if err != nil {
  192. return
  193. }
  194. var dateArr []string
  195. dataMap := make(map[string]*EdbInfoSearchData)
  196. fromDataMap := make(map[string]float64)
  197. //来源指指标数据
  198. for _, v := range dataList {
  199. dateArr = append(dateArr, v.DataTime)
  200. dataMap[v.DataTime] = v
  201. fromDataMap[v.DataTime] = v.Value
  202. }
  203. fmt.Println("source:", source)
  204. //获取升频指标所有数据
  205. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  206. if err != nil {
  207. return
  208. }
  209. //计算指标的map
  210. existDataMap := make(map[string]*EdbData, 0)
  211. removeDateMap := make(map[string]struct{})
  212. addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  213. var isAdd bool
  214. //待删除的日期
  215. removeDateList := make([]string, 0)
  216. if len(existDataList) > 0 && len(dateArr) == 0 {
  217. //如果没有来源指标数据,那么已经入库的计算指标数据需要全部删除
  218. tableName := GetEdbDataTableName(source, subSource)
  219. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ?`, tableName)
  220. err = to.Exec(sql, edbInfoId).Error
  221. if err != nil {
  222. err = fmt.Errorf("删除所有的升频指标数据失败,Err:" + err.Error())
  223. return
  224. }
  225. return
  226. }
  227. existMap := make(map[string]string)
  228. dataLen := len(dataList)
  229. //第三步: 已经入库的数据处理
  230. for _, v := range existDataList {
  231. existDataMap[v.DataTime] = v
  232. removeDateMap[v.DataTime] = struct{}{}
  233. }
  234. for i := 0; i < dataLen; i++ {
  235. //当期
  236. currentItem := dataList[i]
  237. var prevItem *EdbInfoSearchData
  238. if emptyType == 3 { //3后值填充,其余前值填充
  239. if i >= 1 {
  240. prevItem = dataList[i-1]
  241. }
  242. }
  243. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  244. var day int
  245. var preItem *EdbInfoSearchData
  246. var preDate time.Time
  247. if i == 0 {
  248. if emptyType == 3 { //后值填充
  249. day = 0 //最新的时间就是来源指标的最新日期
  250. preDate = currentDate
  251. } else {
  252. day = int(time.Now().Sub(currentDate).Hours() / float64(24))
  253. preDate = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local)
  254. }
  255. } else {
  256. j := i - 1
  257. if j < dataLen {
  258. preItem = dataList[j]
  259. preDate, _ = time.ParseInLocation(utils.FormatDate, preItem.DataTime, time.Local)
  260. day = int(preDate.Sub(currentDate).Hours() / float64(24))
  261. utils.FileLog.Info("preItem.DataTime:" + preItem.DataTime + ";currentItem.DataTime" + currentItem.DataTime)
  262. }
  263. }
  264. for k := 0; k <= day; k++ {
  265. needDay := preDate.AddDate(0, 0, -k)
  266. needDayStr := needDay.Format(utils.FormatDate)
  267. delete(removeDateMap, needDayStr)
  268. existKey := edbCode + needDayStr
  269. if _, ok := existMap[existKey]; !ok {
  270. timestamp := needDay.UnixNano() / 1e6
  271. timestampStr := fmt.Sprintf("%d", timestamp)
  272. valStr := decimal.NewFromFloat(currentItem.Value).String()
  273. if prevItem != nil && needDayStr != currentItem.DataTime {
  274. valStr = decimal.NewFromFloat(prevItem.Value).String()
  275. }
  276. tmpExistData, ok2 := existDataMap[needDayStr]
  277. if !ok2 {
  278. addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
  279. isAdd = true
  280. } else {
  281. //如果对应的值不匹配
  282. if tmpExistData.Value != valStr {
  283. err = ModifyEdbDataById(source, subSource, tmpExistData.EdbDataId, valStr)
  284. if err != nil {
  285. return err
  286. }
  287. }
  288. }
  289. }
  290. existMap[existKey] = needDayStr
  291. }
  292. existKey := edbCode + currentItem.DataTime
  293. if _, ok := existMap[existKey]; !ok {
  294. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  295. timestamp := currentDate.UnixNano() / 1e6
  296. timestampStr := fmt.Sprintf("%d", timestamp)
  297. currValDeci := decimal.NewFromFloat(currentItem.Value)
  298. currValStr := currValDeci.String()
  299. tmpExistData, ok2 := existDataMap[currentItem.DataTime]
  300. if !ok2 {
  301. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, currValStr)
  302. isAdd = true
  303. } else {
  304. // 已经入库的数据值
  305. tmpExistVal, tmpErr := decimal.NewFromString(tmpExistData.Value)
  306. if tmpErr != nil {
  307. err = tmpErr
  308. return
  309. }
  310. // 如果已经入库的数据值 与 当前计算出来的值 不匹配,那么就去更新
  311. if !tmpExistVal.Equal(currValDeci) {
  312. err = ModifyEdbDataById(source, subSource, tmpExistData.EdbDataId, currValStr)
  313. if err != nil {
  314. return err
  315. }
  316. }
  317. }
  318. }
  319. existMap[existKey] = currentItem.DataTime
  320. }
  321. for k, _ := range removeDateMap {
  322. removeDateList = append(removeDateList, k)
  323. }
  324. // 删除不需要的指标数据
  325. if len(removeDateList) > 0 {
  326. //如果拼接指标变更了,那么需要删除所有的指标数据
  327. tableName := GetEdbDataTableName(source, subSource)
  328. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(len(removeDateList))+`) `, tableName)
  329. err = to.Exec(sql, edbInfoId, removeDateList).Error
  330. if err != nil {
  331. err = fmt.Errorf("删除不存在的升频指标数据失败,Err:" + err.Error())
  332. return
  333. }
  334. }
  335. if isAdd {
  336. addSql = strings.TrimRight(addSql, ",")
  337. err = to.Exec(addSql).Error
  338. }
  339. return
  340. }