predict_edb_data_calculate_time_shift.go 10 KB

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