predict_edb_data_calculate_time_shift.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. // SavePredictCalculateTimeShift 时间移位
  13. func SavePredictCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName 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("SavePredictCalculateTimeShift,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_TIME_SHIFT
  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.CalculateFormula = req.Formula
  44. edbInfo.EdbType = 2
  45. edbInfo.MoveType = req.MoveType
  46. edbInfo.MoveFrequency = req.MoveFrequency
  47. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  48. if tmpErr != nil {
  49. err = tmpErr
  50. return
  51. }
  52. edbInfo.EdbInfoId = int(newEdbInfoId)
  53. //关联关系
  54. {
  55. calculateMappingItem := new(EdbInfoCalculateMapping)
  56. calculateMappingItem.CreateTime = time.Now()
  57. calculateMappingItem.ModifyTime = time.Now()
  58. calculateMappingItem.Sort = 1
  59. calculateMappingItem.EdbCode = edbCode
  60. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  61. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  63. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  64. calculateMappingItem.FromSource = fromEdbInfo.Source
  65. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  66. calculateMappingItem.FromTag = ""
  67. calculateMappingItem.Source = edbInfo.Source
  68. calculateMappingItem.SourceName = edbInfo.SourceName
  69. _, err = to.Insert(calculateMappingItem)
  70. if err != nil {
  71. return
  72. }
  73. }
  74. } else {
  75. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  76. if err != nil {
  77. return
  78. }
  79. latestDateStr = edbInfo.LatestDate
  80. latestValue = edbInfo.LatestValue
  81. oldEdbInfo := *edbInfo //旧的指标信息
  82. //修改指标信息
  83. edbInfo.EdbName = req.EdbName
  84. edbInfo.EdbNameSource = req.EdbName
  85. edbInfo.Frequency = req.Frequency
  86. edbInfo.Unit = req.Unit
  87. edbInfo.ClassifyId = req.ClassifyId
  88. edbInfo.MoveType = req.MoveType
  89. edbInfo.MoveFrequency = req.MoveFrequency
  90. edbInfo.CalculateFormula = req.Formula
  91. edbInfo.ModifyTime = time.Now()
  92. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "MoveType", "MoveFrequency", "CalculateFormula", "ModifyTime")
  93. if err != nil {
  94. return
  95. }
  96. //判断计算指标是否被更换
  97. var existCondition string
  98. var existPars []interface{}
  99. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  100. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  101. var count int
  102. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  103. if err != nil {
  104. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  105. return
  106. }
  107. if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
  108. //如果是依赖指标变更,那么需要删除对应的关联指标,并添加新的关系
  109. if count <= 0 {
  110. //删除,计算指标关联的,基础指标的关联关系
  111. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  112. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  113. if err != nil {
  114. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  115. return
  116. }
  117. //关联关系
  118. {
  119. calculateMappingItem := &EdbInfoCalculateMapping{
  120. EdbInfoCalculateMappingId: 0,
  121. EdbInfoId: edbInfo.EdbInfoId,
  122. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_TIME_SHIFT,
  123. SourceName: "预测时间移位",
  124. EdbCode: edbInfo.EdbCode,
  125. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  126. FromEdbCode: fromEdbInfo.EdbCode,
  127. FromEdbName: fromEdbInfo.EdbName,
  128. FromSource: fromEdbInfo.Source,
  129. FromSourceName: fromEdbInfo.SourceName,
  130. FromTag: "",
  131. Sort: 1,
  132. CreateTime: time.Now(),
  133. ModifyTime: time.Now(),
  134. }
  135. _, err = to.Insert(calculateMappingItem)
  136. if err != nil {
  137. return
  138. }
  139. }
  140. }
  141. //清空原有数据
  142. sql := ` DELETE FROM edb_data_predict_calculate_time_shift WHERE edb_info_id = ? `
  143. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  144. if err != nil {
  145. return
  146. }
  147. } else {
  148. return
  149. }
  150. }
  151. formulaInt, _ := strconv.Atoi(req.Formula)
  152. //计算数据
  153. latestDateStr, latestValue, err = refreshAllPredictCalculateTimeShift(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
  154. return
  155. }
  156. // refreshAllPredictCalculateTimeShift 刷新所有时间移位数据
  157. func RefreshAllPredictCalculateTimeShift(edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (latestDateStr string, latestValue float64, err error) {
  158. o := orm.NewOrm()
  159. to, err := o.Begin()
  160. if err != nil {
  161. return
  162. }
  163. defer func() {
  164. if err != nil {
  165. fmt.Println("refreshAllPredictCalculateTimeShift,Err:" + err.Error())
  166. _ = to.Rollback()
  167. } else {
  168. _ = to.Commit()
  169. }
  170. }()
  171. //计算数据
  172. latestDateStr, latestValue, err = refreshAllPredictCalculateTimeShift(to, edbInfoId, source, subSource, formulaInt, moveType, fromEdbInfo, edbCode, startDate, endDate, moveFrequency)
  173. return
  174. }
  175. // refreshAllPredictCalculateTimeShift 刷新所有时间移位数据
  176. func refreshAllPredictCalculateTimeShift(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (latestDateStr string, latestValue float64, err error) {
  177. edbInfoIdStr := strconv.Itoa(edbInfoId)
  178. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
  179. if err != nil {
  180. return
  181. }
  182. var shiftDay int
  183. switch moveFrequency {
  184. case "天":
  185. shiftDay = formulaInt
  186. case "周":
  187. shiftDay = formulaInt * 7
  188. case "月":
  189. shiftDay = formulaInt * 30
  190. case "季":
  191. shiftDay = formulaInt * 90
  192. case "年":
  193. shiftDay = formulaInt * 365
  194. default:
  195. shiftDay = formulaInt
  196. }
  197. if moveType == 2 {
  198. shiftDay = -shiftDay
  199. }
  200. latestDate, _ := time.ParseInLocation(utils.FormatDate, fromEdbInfo.LatestDate, time.Local)
  201. latestDateStr = latestDate.AddDate(0, 0, shiftDay).Format(utils.FormatDate)
  202. var dateArr []string
  203. dataMap := make(map[string]*EdbInfoSearchData)
  204. for _, v := range dataList {
  205. dateArr = append(dateArr, v.DataTime)
  206. dataMap[v.DataTime] = v
  207. }
  208. fmt.Println("source:", source)
  209. //获取指标所有数据
  210. existDataList := make([]*EdbData, 0)
  211. dataTableName := GetEdbDataTableName(source, subSource)
  212. fmt.Println("dataTableName:", dataTableName)
  213. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  214. sql = fmt.Sprintf(sql, dataTableName)
  215. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  216. if err != nil {
  217. return
  218. }
  219. existDataMap := make(map[string]string)
  220. for _, v := range existDataList {
  221. existDataMap[v.DataTime] = v.Value
  222. }
  223. fmt.Println("existDataMap:", existDataMap)
  224. addSql := ` INSERT INTO edb_data_predict_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  225. var isAdd bool
  226. existMap := make(map[string]string)
  227. dataLen := len(dataList)
  228. for i := 0; i < dataLen; i++ {
  229. //当期
  230. currentItem := dataList[i]
  231. existKey := edbCode + currentItem.DataTime
  232. if _, ok := existMap[existKey]; !ok {
  233. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  234. newDate := currentDate.AddDate(0, 0, shiftDay)
  235. timestamp := newDate.UnixNano() / 1e6
  236. timestampStr := fmt.Sprintf("%d", timestamp)
  237. valStr := decimal.NewFromFloat(currentItem.Value).RoundCeil(4).String()
  238. if latestDateStr == newDate.Format(utils.FormatDate) {
  239. latestValue = currentItem.Value
  240. }
  241. if existVal, ok := existDataMap[newDate.Format(utils.FormatDate)]; !ok {
  242. isAdd = true
  243. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  244. } else {
  245. var existValDecimal decimal.Decimal
  246. existValDecimal, err = decimal.NewFromString(existVal)
  247. if err != nil {
  248. return
  249. }
  250. existStr := existValDecimal.String()
  251. if existStr != valStr {
  252. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  253. sql = fmt.Sprintf(sql, dataTableName)
  254. _, err = to.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
  255. if err != nil {
  256. return
  257. }
  258. }
  259. }
  260. }
  261. existMap[existKey] = currentItem.DataTime
  262. }
  263. if isAdd {
  264. addSql = strings.TrimRight(addSql, ",")
  265. _, err = to.Raw(addSql).Exec()
  266. if err != nil {
  267. return
  268. }
  269. }
  270. return
  271. }