predict_edb_data_calculate_hbz.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package models
  2. import (
  3. "errors"
  4. "eta_gn/eta_index_lib/global"
  5. "eta_gn/eta_index_lib/utils"
  6. "fmt"
  7. "github.com/shopspring/decimal"
  8. "gorm.io/gorm"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // SavePredictCalculateHbz 新增环比值指标
  14. func SavePredictCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error) {
  15. to := global.DEFAULT_DmSQL.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_HBZ
  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.EdbNameEn = req.EdbName
  41. edbInfo.UnitEn = req.Unit
  42. edbInfo.EdbType = 2
  43. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE)
  44. tmpErr := to.Create(edbInfo).Error
  45. if tmpErr != nil {
  46. err = tmpErr
  47. return
  48. }
  49. //关联关系
  50. {
  51. calculateMappingItem := new(EdbInfoCalculateMapping)
  52. calculateMappingItem.CreateTime = time.Now()
  53. calculateMappingItem.ModifyTime = time.Now()
  54. calculateMappingItem.Sort = 1
  55. calculateMappingItem.EdbCode = edbCode
  56. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  57. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  58. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  59. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  60. calculateMappingItem.FromSource = fromEdbInfo.Source
  61. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  62. calculateMappingItem.FromTag = ""
  63. calculateMappingItem.Source = edbInfo.Source
  64. calculateMappingItem.SourceName = edbInfo.SourceName
  65. err = to.Create(calculateMappingItem).Error
  66. if err != nil {
  67. return
  68. }
  69. }
  70. } else {
  71. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  72. if err != nil {
  73. return
  74. }
  75. latestDateStr = edbInfo.LatestDate
  76. latestValue = edbInfo.LatestValue
  77. oldCalculateFormula := edbInfo.CalculateFormula
  78. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_HBZ, utils.DATA_SUB_SOURCE_EDB)
  79. //修改指标信息
  80. switch lang {
  81. case utils.EnLangVersion:
  82. edbInfo.EdbNameEn = req.EdbName
  83. edbInfo.UnitEn = req.Unit
  84. default:
  85. edbInfo.EdbName = req.EdbName
  86. edbInfo.Unit = req.Unit
  87. edbInfo.EdbNameSource = req.EdbName
  88. }
  89. edbInfo.Frequency = req.Frequency
  90. edbInfo.ClassifyId = req.ClassifyId
  91. edbInfo.CalculateFormula = req.Formula
  92. edbInfo.ModifyTime = time.Now()
  93. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  94. if err != nil {
  95. return
  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. //判断计算指标是否被更换
  102. var count int
  103. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  104. if err != nil {
  105. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  106. return
  107. }
  108. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  109. return
  110. }
  111. //删除,计算指标关联的,基础指标的关联关系
  112. if count <= 0 {
  113. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  114. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  115. if err != nil {
  116. return
  117. }
  118. //关联关系
  119. {
  120. calculateMappingItem := &EdbInfoCalculateMapping{
  121. EdbInfoCalculateMappingId: 0,
  122. EdbInfoId: edbInfo.EdbInfoId,
  123. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_HBZ,
  124. SourceName: "预测环比值",
  125. EdbCode: edbInfo.EdbCode,
  126. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  127. FromEdbCode: fromEdbInfo.EdbCode,
  128. FromEdbName: fromEdbInfo.EdbName,
  129. FromSource: fromEdbInfo.Source,
  130. FromSourceName: fromEdbInfo.SourceName,
  131. FromTag: "",
  132. Sort: 1,
  133. CreateTime: time.Now(),
  134. ModifyTime: time.Now(),
  135. }
  136. err = to.Create(calculateMappingItem).Error
  137. if err != nil {
  138. return
  139. }
  140. }
  141. }
  142. //清空原有数据
  143. sql := ` DELETE FROM %s WHERE edb_info_id = ? `
  144. sql = fmt.Sprintf(sql, dataTableName)
  145. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  146. if err != nil {
  147. return
  148. }
  149. }
  150. //计算数据
  151. latestDateStr, latestValue, err = refreshAllPredictCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  152. return
  153. }
  154. // RefreshAllPredictCalculateHbz 刷新所有环比值数据
  155. func RefreshAllPredictCalculateHbz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  156. to := global.DEFAULT_DmSQL.Begin()
  157. defer func() {
  158. if err != nil {
  159. to.Rollback()
  160. } else {
  161. to.Commit()
  162. }
  163. }()
  164. //计算数据
  165. latestDateStr, latestValue, err = refreshAllPredictCalculateHbz(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  166. return
  167. }
  168. // refreshAllPredictCalculateHbz 刷新所有环比值数据
  169. func refreshAllPredictCalculateHbz(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  170. edbInfoIdStr := strconv.Itoa(edbInfoId)
  171. // 获取关联指标数据
  172. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, "")
  173. if err != nil {
  174. return
  175. }
  176. latestDateStr = fromEdbInfo.LatestDate
  177. var dateArr []string
  178. dataMap := make(map[string]*EdbInfoSearchData)
  179. for _, v := range dataList {
  180. dateArr = append(dateArr, v.DataTime)
  181. dataMap[v.DataTime] = v
  182. }
  183. dataTableName := GetEdbDataTableName(source, subSource)
  184. //获取指标所有数据
  185. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  186. if err != nil {
  187. return
  188. }
  189. existDataMap := make(map[string]string)
  190. for _, v := range existDataList {
  191. existDataMap[v.DataTime] = v.Value
  192. }
  193. addSql := ` INSERT INTO edb_data_predict_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  194. var isAdd bool
  195. existMap := make(map[string]string)
  196. dataLen := len(dataList)
  197. fmt.Println("dataLen:", dataLen)
  198. for i := 0; i < dataLen; i++ {
  199. j := i + formulaInt
  200. if j < dataLen {
  201. //当期
  202. currentItem := dataList[i]
  203. preItem := dataList[j]
  204. if currentItem != nil && preItem != nil {
  205. existKey := edbCode + currentItem.DataTime
  206. if _, ok := existMap[existKey]; !ok {
  207. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  208. timestamp := currentDate.UnixNano() / 1e6
  209. timestampStr := fmt.Sprintf("%d", timestamp)
  210. val := HbzDiv(currentItem.Value, preItem.Value)
  211. if val != "" {
  212. if fromEdbInfo.LatestDate == currentItem.DataTime {
  213. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  214. if tmpErr != nil {
  215. err = tmpErr
  216. return
  217. }
  218. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  219. }
  220. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  221. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  222. isAdd = true
  223. } else {
  224. var existValDecimal decimal.Decimal
  225. existValDecimal, err = decimal.NewFromString(existVal)
  226. if err != nil {
  227. return
  228. }
  229. existStr := existValDecimal.String()
  230. if existStr != val {
  231. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  232. sql = fmt.Sprintf(sql, dataTableName)
  233. err = to.Exec(sql, val, edbInfoId, currentItem.DataTime).Error
  234. if err != nil {
  235. return
  236. }
  237. }
  238. }
  239. }
  240. }
  241. existMap[existKey] = currentItem.DataTime
  242. }
  243. }
  244. }
  245. if isAdd {
  246. addSql = strings.TrimRight(addSql, ",")
  247. err = to.Exec(addSql).Error
  248. if err != nil {
  249. return
  250. }
  251. }
  252. return
  253. }