predict_edb_data_calculate_hcz.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // SavePredictCalculateHcz 新增环差值指标
  13. func SavePredictCalculateHcz(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("AddCalculateHcz,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_HCZ
  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. //修改指标信息
  81. edbInfo.EdbName = req.EdbName
  82. edbInfo.EdbNameSource = req.EdbName
  83. edbInfo.Frequency = req.Frequency
  84. edbInfo.Unit = req.Unit
  85. edbInfo.ClassifyId = req.ClassifyId
  86. edbInfo.CalculateFormula = req.Formula
  87. edbInfo.ModifyTime = time.Now()
  88. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  89. if err != nil {
  90. return
  91. }
  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. var count int
  98. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  99. if err != nil {
  100. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  101. return
  102. }
  103. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  104. return
  105. }
  106. //删除,计算指标关联的,基础指标的关联关系
  107. if count <= 0 {
  108. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  109. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  110. if err != nil {
  111. return
  112. }
  113. //关联关系
  114. {
  115. calculateMappingItem := &EdbInfoCalculateMapping{
  116. EdbInfoCalculateMappingId: 0,
  117. EdbInfoId: edbInfo.EdbInfoId,
  118. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_HCZ,
  119. SourceName: "预测环差值",
  120. EdbCode: edbInfo.EdbCode,
  121. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  122. FromEdbCode: fromEdbInfo.EdbCode,
  123. FromEdbName: fromEdbInfo.EdbName,
  124. FromSource: fromEdbInfo.Source,
  125. FromSourceName: fromEdbInfo.SourceName,
  126. FromTag: "",
  127. Sort: 1,
  128. CreateTime: time.Now(),
  129. ModifyTime: time.Now(),
  130. }
  131. _, err = to.Insert(calculateMappingItem)
  132. if err != nil {
  133. return
  134. }
  135. }
  136. }
  137. //清空原有数据
  138. sql := ` DELETE FROM edb_data_predict_calculate_hcz WHERE edb_info_id = ? `
  139. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  140. if err != nil {
  141. return
  142. }
  143. }
  144. //计算数据
  145. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  146. return
  147. }
  148. // RefreshAllPredictCalculateHcz 刷新所有环差值数据
  149. func RefreshAllPredictCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  150. o := orm.NewOrm()
  151. to, err := o.Begin()
  152. if err != nil {
  153. return
  154. }
  155. defer func() {
  156. if err != nil {
  157. fmt.Println("refreshAllPredictCalculateHcz,Err:" + err.Error())
  158. _ = to.Rollback()
  159. } else {
  160. _ = to.Commit()
  161. }
  162. }()
  163. //计算数据
  164. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  165. return
  166. }
  167. // refreshAllPredictCalculateHcz 刷新所有环差值数据
  168. func refreshAllPredictCalculateHcz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  169. edbInfoIdStr := strconv.Itoa(edbInfoId)
  170. // 获取关联指标数据
  171. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, "")
  172. if err != nil {
  173. return
  174. }
  175. latestDateStr = fromEdbInfo.LatestDate
  176. var dateArr []string
  177. dataMap := make(map[string]*EdbInfoSearchData)
  178. for _, v := range dataList {
  179. dateArr = append(dateArr, v.DataTime)
  180. dataMap[v.DataTime] = v
  181. }
  182. fmt.Println("source:", source)
  183. //获取指标所有数据
  184. existDataList := make([]*EdbData, 0)
  185. dataTableName := GetEdbDataTableName(source)
  186. fmt.Println("dataTableName:", dataTableName)
  187. var existPars []interface{}
  188. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  189. //if startDate != "" {
  190. // sql += " AND data_time>=? "
  191. // existPars = append(existPars, startDate)
  192. //}
  193. sql = fmt.Sprintf(sql, dataTableName)
  194. _, err = to.Raw(sql, edbInfoId, existPars).QueryRows(&existDataList)
  195. if err != nil {
  196. return
  197. }
  198. existDataMap := make(map[string]string)
  199. removeDateMap := make(map[string]string) //需要移除的日期
  200. for _, v := range existDataList {
  201. existDataMap[v.DataTime] = v.Value
  202. removeDateMap[v.DataTime] = v.DataTime
  203. }
  204. //fmt.Println("existDataMap:", existDataMap)
  205. addSql := ` INSERT INTO edb_data_predict_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  206. var isAdd bool
  207. existMap := make(map[string]string)
  208. dataLen := len(dataList)
  209. fmt.Println("dataLen:", dataLen)
  210. for i := 0; i < dataLen; i++ {
  211. j := i + formulaInt
  212. if j < dataLen {
  213. //当期
  214. currentItem := dataList[i]
  215. preItem := dataList[j]
  216. if currentItem != nil && preItem != nil {
  217. existKey := edbCode + currentItem.DataTime
  218. if _, ok := existMap[existKey]; !ok {
  219. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  220. //fmt.Println(currentDate)
  221. timestamp := currentDate.UnixNano() / 1e6
  222. timestampStr := fmt.Sprintf("%d", timestamp)
  223. val := HczDiv(currentItem.Value, preItem.Value)
  224. if val != "" {
  225. if fromEdbInfo.LatestDate == currentItem.DataTime {
  226. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  227. if tmpErr != nil {
  228. err = tmpErr
  229. return
  230. }
  231. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  232. }
  233. // 有计算出来值,那么就从待删除指标中移除
  234. delete(removeDateMap, currentItem.DataTime)
  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. //fmt.Println(removeDateMap)
  268. if len(removeDateMap) > 0 {
  269. removeDateList := make([]string, 0) //需要移除的日期
  270. for k := range removeDateMap {
  271. removeDateList = append(removeDateList, k)
  272. }
  273. removeDateStr := strings.Join(removeDateList, `","`)
  274. removeDateStr = `"` + removeDateStr + `"`
  275. //如果拼接指标变更了,那么需要删除所有的指标数据
  276. tableName := GetEdbDataTableName(source)
  277. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  278. _, err = to.Raw(sql, edbInfoId).Exec()
  279. if err != nil {
  280. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  281. return
  282. }
  283. }
  284. return
  285. }