predict_edb_data_calculate_hbz.go 8.9 KB

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