predict_edb_data_calculate_hbz.go 9.0 KB

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