predict_edb_data_calculate_hbz.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. // SavePredictCalculateHbz 新增环比值指标
  13. func SavePredictCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (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("SavePredictCalculateHbz,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_HBZ
  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. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  46. if tmpErr != nil {
  47. err = tmpErr
  48. return
  49. }
  50. edbInfo.EdbInfoId = int(newEdbInfoId)
  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.Insert(calculateMappingItem)
  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. oldCalculateFormula := edbInfo.CalculateFormula
  80. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_HBZ)
  81. //修改指标信息
  82. edbInfo.EdbName = req.EdbName
  83. edbInfo.EdbNameSource = req.EdbName
  84. edbInfo.Frequency = req.Frequency
  85. edbInfo.Unit = req.Unit
  86. edbInfo.ClassifyId = req.ClassifyId
  87. edbInfo.CalculateFormula = req.Formula
  88. edbInfo.ModifyTime = time.Now()
  89. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  90. if err != nil {
  91. return
  92. }
  93. var existCondition string
  94. var existPars []interface{}
  95. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  96. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  97. //判断计算指标是否被更换
  98. var count int
  99. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  100. if err != nil {
  101. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  102. return
  103. }
  104. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  105. return
  106. }
  107. //删除,计算指标关联的,基础指标的关联关系
  108. if count <= 0 {
  109. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  110. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  111. if err != nil {
  112. return
  113. }
  114. //关联关系
  115. {
  116. calculateMappingItem := &EdbInfoCalculateMapping{
  117. EdbInfoCalculateMappingId: 0,
  118. EdbInfoId: edbInfo.EdbInfoId,
  119. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_HBZ,
  120. SourceName: "预测环比值",
  121. EdbCode: edbInfo.EdbCode,
  122. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  123. FromEdbCode: fromEdbInfo.EdbCode,
  124. FromEdbName: fromEdbInfo.EdbName,
  125. FromSource: fromEdbInfo.Source,
  126. FromSourceName: fromEdbInfo.SourceName,
  127. FromTag: "",
  128. Sort: 1,
  129. CreateTime: time.Now(),
  130. ModifyTime: time.Now(),
  131. }
  132. _, err = to.Insert(calculateMappingItem)
  133. if err != nil {
  134. return
  135. }
  136. }
  137. }
  138. //清空原有数据
  139. sql := ` DELETE FROM %s WHERE edb_info_id = ? `
  140. sql = fmt.Sprintf(sql, dataTableName)
  141. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  142. if err != nil {
  143. return
  144. }
  145. }
  146. //计算数据
  147. latestDateStr, latestValue, err = refreshAllPredictCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  148. return
  149. }
  150. // RefreshAllPredictCalculateHbz 刷新所有环比值数据
  151. func RefreshAllPredictCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  152. o := orm.NewOrm()
  153. to, err := o.Begin()
  154. if err != nil {
  155. return
  156. }
  157. defer func() {
  158. if err != nil {
  159. fmt.Println("RefreshAllPredictCalculateHbz,Err:" + err.Error())
  160. _ = to.Rollback()
  161. } else {
  162. _ = to.Commit()
  163. }
  164. }()
  165. //计算数据
  166. latestDateStr, latestValue, err = refreshAllPredictCalculateHbz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  167. return
  168. }
  169. // refreshAllPredictCalculateHbz 刷新所有环比值数据
  170. func refreshAllPredictCalculateHbz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  171. edbInfoIdStr := strconv.Itoa(edbInfoId)
  172. // 获取关联指标数据
  173. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, "")
  174. if err != nil {
  175. return
  176. }
  177. latestDateStr = fromEdbInfo.LatestDate
  178. var dateArr []string
  179. dataMap := make(map[string]*EdbInfoSearchData)
  180. for _, v := range dataList {
  181. dateArr = append(dateArr, v.DataTime)
  182. dataMap[v.DataTime] = v
  183. }
  184. fmt.Println("source:", source)
  185. //获取指标所有数据
  186. existDataList := make([]*EdbData, 0)
  187. dataTableName := GetEdbDataTableName(source)
  188. fmt.Println("dataTableName:", dataTableName)
  189. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  190. sql = fmt.Sprintf(sql, dataTableName)
  191. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  192. if err != nil {
  193. return
  194. }
  195. existDataMap := make(map[string]string)
  196. for _, v := range existDataList {
  197. existDataMap[v.DataTime] = v.Value
  198. }
  199. addSql := ` INSERT INTO edb_data_predict_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  200. var isAdd bool
  201. existMap := make(map[string]string)
  202. dataLen := len(dataList)
  203. fmt.Println("dataLen:", dataLen)
  204. for i := 0; i < dataLen; i++ {
  205. j := i + formulaInt
  206. if j < dataLen {
  207. //当期
  208. currentItem := dataList[i]
  209. preItem := dataList[j]
  210. if currentItem != nil && preItem != nil {
  211. existKey := edbCode + currentItem.DataTime
  212. if _, ok := existMap[existKey]; !ok {
  213. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  214. timestamp := currentDate.UnixNano() / 1e6
  215. timestampStr := fmt.Sprintf("%d", timestamp)
  216. val := HbzDiv(currentItem.Value, preItem.Value)
  217. if val != "" {
  218. if fromEdbInfo.LatestDate == currentItem.DataTime {
  219. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  220. if tmpErr != nil {
  221. err = tmpErr
  222. return
  223. }
  224. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  225. }
  226. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  227. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  228. isAdd = true
  229. } else {
  230. var existValDecimal decimal.Decimal
  231. existValDecimal, err = decimal.NewFromString(existVal)
  232. if err != nil {
  233. return
  234. }
  235. existStr := existValDecimal.String()
  236. if existStr != val {
  237. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  238. sql = fmt.Sprintf(sql, dataTableName)
  239. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  240. if err != nil {
  241. return
  242. }
  243. }
  244. }
  245. }
  246. }
  247. existMap[existKey] = currentItem.DataTime
  248. }
  249. }
  250. }
  251. if isAdd {
  252. addSql = strings.TrimRight(addSql, ",")
  253. _, err = to.Raw(addSql).Exec()
  254. if err != nil {
  255. return
  256. }
  257. }
  258. return
  259. }