predict_edb_data_calculate_bp.go 11 KB

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