predict_edb_data_calculate_time_shift.go 9.9 KB

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