predict_edb_data_calculate_bp.go 11 KB

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