predict_edb_data_calculate_hcz.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package models
  2. import (
  3. "errors"
  4. "eta_gn/eta_index_lib/global"
  5. "eta_gn/eta_index_lib/utils"
  6. "fmt"
  7. "gorm.io/gorm"
  8. "github.com/shopspring/decimal"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // SavePredictCalculateHcz 新增环差值指标
  14. func SavePredictCalculateHcz(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_HCZ
  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. //修改指标信息
  79. switch lang {
  80. case utils.EnLangVersion:
  81. edbInfo.EdbNameEn = req.EdbName
  82. edbInfo.UnitEn = req.Unit
  83. default:
  84. edbInfo.EdbName = req.EdbName
  85. edbInfo.Unit = req.Unit
  86. edbInfo.EdbNameSource = req.EdbName
  87. }
  88. edbInfo.Frequency = req.Frequency
  89. edbInfo.ClassifyId = req.ClassifyId
  90. edbInfo.CalculateFormula = req.Formula
  91. edbInfo.ModifyTime = time.Now()
  92. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  93. if err != nil {
  94. return
  95. }
  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. var count int
  102. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  103. if err != nil {
  104. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  105. return
  106. }
  107. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  108. return
  109. }
  110. //删除,计算指标关联的,基础指标的关联关系
  111. if count <= 0 {
  112. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  113. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  114. if err != nil {
  115. return
  116. }
  117. //关联关系
  118. {
  119. calculateMappingItem := &EdbInfoCalculateMapping{
  120. EdbInfoCalculateMappingId: 0,
  121. EdbInfoId: edbInfo.EdbInfoId,
  122. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_HCZ,
  123. SourceName: "预测环差值",
  124. EdbCode: edbInfo.EdbCode,
  125. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  126. FromEdbCode: fromEdbInfo.EdbCode,
  127. FromEdbName: fromEdbInfo.EdbName,
  128. FromSource: fromEdbInfo.Source,
  129. FromSourceName: fromEdbInfo.SourceName,
  130. FromTag: "",
  131. Sort: 1,
  132. CreateTime: time.Now(),
  133. ModifyTime: time.Now(),
  134. }
  135. err = to.Create(calculateMappingItem).Error
  136. if err != nil {
  137. return
  138. }
  139. }
  140. }
  141. //清空原有数据
  142. sql := ` DELETE FROM edb_data_predict_calculate_hcz WHERE edb_info_id = ? `
  143. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  144. if err != nil {
  145. return
  146. }
  147. }
  148. //计算数据
  149. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  150. return
  151. }
  152. // RefreshAllPredictCalculateHcz 刷新所有环差值数据
  153. func RefreshAllPredictCalculateHcz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  154. to := global.DEFAULT_DmSQL.Begin()
  155. defer func() {
  156. if err != nil {
  157. to.Rollback()
  158. } else {
  159. to.Commit()
  160. }
  161. }()
  162. //计算数据
  163. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  164. return
  165. }
  166. // refreshAllPredictCalculateHcz 刷新所有环差值数据
  167. func refreshAllPredictCalculateHcz(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  168. edbInfoIdStr := strconv.Itoa(edbInfoId)
  169. // 获取关联指标数据
  170. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, "")
  171. if err != nil {
  172. return
  173. }
  174. latestDateStr = fromEdbInfo.LatestDate
  175. var dateArr []string
  176. dataMap := make(map[string]*EdbInfoSearchData)
  177. for _, v := range dataList {
  178. dateArr = append(dateArr, v.DataTime)
  179. dataMap[v.DataTime] = v
  180. }
  181. fmt.Println("source:", source)
  182. dataTableName := GetEdbDataTableName(source, subSource)
  183. //获取指标所有数据
  184. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  185. if err != nil {
  186. return
  187. }
  188. existDataMap := make(map[string]string)
  189. removeDateMap := make(map[string]string) //需要移除的日期
  190. for _, v := range existDataList {
  191. existDataMap[v.DataTime] = v.Value
  192. removeDateMap[v.DataTime] = v.DataTime
  193. }
  194. //fmt.Println("existDataMap:", existDataMap)
  195. addSql := ` INSERT INTO edb_data_predict_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  196. var isAdd bool
  197. existMap := make(map[string]string)
  198. dataLen := len(dataList)
  199. fmt.Println("dataLen:", dataLen)
  200. for i := 0; i < dataLen; i++ {
  201. j := i + formulaInt
  202. if j < dataLen {
  203. //当期
  204. currentItem := dataList[i]
  205. preItem := dataList[j]
  206. if currentItem != nil && preItem != nil {
  207. existKey := edbCode + currentItem.DataTime
  208. if _, ok := existMap[existKey]; !ok {
  209. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  210. //fmt.Println(currentDate)
  211. timestamp := currentDate.UnixNano() / 1e6
  212. timestampStr := fmt.Sprintf("%d", timestamp)
  213. val := HczDiv(currentItem.Value, preItem.Value)
  214. if val != "" {
  215. if fromEdbInfo.LatestDate == currentItem.DataTime {
  216. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  217. if tmpErr != nil {
  218. err = tmpErr
  219. return
  220. }
  221. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  222. }
  223. // 有计算出来值,那么就从待删除指标中移除
  224. delete(removeDateMap, currentItem.DataTime)
  225. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  226. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  227. isAdd = true
  228. } else {
  229. var existValDecimal decimal.Decimal
  230. existValDecimal, err = decimal.NewFromString(existVal)
  231. if err != nil {
  232. return
  233. }
  234. existStr := existValDecimal.String()
  235. if existStr != val {
  236. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  237. sql = fmt.Sprintf(sql, dataTableName)
  238. err = to.Exec(sql, val, edbInfoId, currentItem.DataTime).Error
  239. if err != nil {
  240. return
  241. }
  242. }
  243. }
  244. }
  245. }
  246. existMap[existKey] = currentItem.DataTime
  247. }
  248. }
  249. }
  250. if isAdd {
  251. addSql = strings.TrimRight(addSql, ",")
  252. err = to.Exec(addSql).Error
  253. if err != nil {
  254. return
  255. }
  256. }
  257. //fmt.Println(removeDateMap)
  258. if len(removeDateMap) > 0 {
  259. removeDateList := make([]string, 0) //需要移除的日期
  260. for k := range removeDateMap {
  261. removeDateList = append(removeDateList, k)
  262. }
  263. removeDateStr := strings.Join(removeDateList, `','`)
  264. removeDateStr = `'` + removeDateStr + `'`
  265. //如果拼接指标变更了,那么需要删除所有的指标数据
  266. tableName := GetEdbDataTableName(source, subSource)
  267. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  268. err = to.Exec(sql, edbInfoId).Error
  269. if err != nil {
  270. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  271. return
  272. }
  273. }
  274. return
  275. }