predict_edb_data_calculate_phase_shift.go 10 KB

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