predict_edb_data_calculate_hbz.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. 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. removeDateMap := make(map[string]bool) //需要移除的日期
  206. for _, v := range existDataList {
  207. existDataMap[v.DataTime] = v.Value
  208. removeDateMap[v.DataTime] = true
  209. }
  210. addSql := ` INSERT INTO edb_data_predict_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  211. var isAdd bool
  212. existMap := make(map[string]string)
  213. dataLen := len(dataList)
  214. fmt.Println("dataLen:", dataLen)
  215. for i := 0; i < dataLen; i++ {
  216. j := i + formulaInt
  217. if j < dataLen {
  218. //当期
  219. currentItem := dataList[i]
  220. preItem := dataList[j]
  221. if currentItem != nil && preItem != nil {
  222. existKey := edbCode + currentItem.DataTime
  223. if _, ok := existMap[existKey]; !ok {
  224. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  225. timestamp := currentDate.UnixNano() / 1e6
  226. timestampStr := fmt.Sprintf("%d", timestamp)
  227. val := HbzDiv(currentItem.Value, preItem.Value)
  228. if val != "" {
  229. // 有计算出来值,那么就从待删除指标中移除
  230. delete(removeDateMap, currentItem.DataTime)
  231. if fromEdbInfo.LatestDate == currentItem.DataTime {
  232. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  233. if tmpErr != nil {
  234. err = tmpErr
  235. return
  236. }
  237. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  238. }
  239. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  240. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  241. isAdd = true
  242. } else {
  243. var existValDecimal decimal.Decimal
  244. existValDecimal, err = decimal.NewFromString(existVal)
  245. if err != nil {
  246. return
  247. }
  248. existStr := existValDecimal.String()
  249. if existStr != val {
  250. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  251. sql = fmt.Sprintf(sql, dataTableName)
  252. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  253. if err != nil {
  254. return
  255. }
  256. }
  257. }
  258. }
  259. }
  260. existMap[existKey] = currentItem.DataTime
  261. }
  262. }
  263. }
  264. if len(removeDateMap) > 0 {
  265. removeDateList := make([]string, 0) //需要移除的日期
  266. for k := range removeDateMap {
  267. removeDateList = append(removeDateList, k)
  268. }
  269. removeDateStr := strings.Join(removeDateList, `","`)
  270. removeDateStr = `"` + removeDateStr + `"`
  271. //如果拼接指标变更了,那么需要删除所有的指标数据
  272. tableName := GetEdbDataTableName(source, subSource)
  273. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  274. _, err = to.Raw(sql, edbInfoId).Exec()
  275. if err != nil {
  276. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  277. return
  278. }
  279. }
  280. if isAdd {
  281. addSql = strings.TrimRight(addSql, ",")
  282. _, err = to.Raw(addSql).Exec()
  283. if err != nil {
  284. return
  285. }
  286. }
  287. return
  288. }