predict_edb_data_calculate_hcz.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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, 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("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.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. //修改指标信息
  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. //判断计算指标是否被更换
  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. 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_HCZ,
  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 edb_data_predict_calculate_hcz WHERE edb_info_id = ? `
  148. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  149. if err != nil {
  150. return
  151. }
  152. }
  153. //计算数据
  154. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  155. return
  156. }
  157. // RefreshAllPredictCalculateHcz 刷新所有环差值数据
  158. func RefreshAllPredictCalculateHcz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  159. o := orm.NewOrm()
  160. to, err := o.Begin()
  161. if err != nil {
  162. return
  163. }
  164. defer func() {
  165. if err != nil {
  166. fmt.Println("refreshAllPredictCalculateHcz,Err:" + err.Error())
  167. _ = to.Rollback()
  168. } else {
  169. _ = to.Commit()
  170. }
  171. }()
  172. //计算数据
  173. latestDateStr, latestValue, err = refreshAllPredictCalculateHcz(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  174. return
  175. }
  176. // refreshAllPredictCalculateHcz 刷新所有环差值数据
  177. func refreshAllPredictCalculateHcz(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  178. edbInfoIdStr := strconv.Itoa(edbInfoId)
  179. // 获取关联指标数据
  180. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, "")
  181. if err != nil {
  182. return
  183. }
  184. latestDateStr = fromEdbInfo.LatestDate
  185. var dateArr []string
  186. dataMap := make(map[string]*EdbInfoSearchData)
  187. for _, v := range dataList {
  188. dateArr = append(dateArr, v.DataTime)
  189. dataMap[v.DataTime] = v
  190. }
  191. fmt.Println("source:", source)
  192. //获取指标所有数据
  193. existDataList := make([]*EdbData, 0)
  194. dataTableName := GetEdbDataTableName(source, subSource)
  195. fmt.Println("dataTableName:", dataTableName)
  196. var existPars []interface{}
  197. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  198. //if startDate != "" {
  199. // sql += " AND data_time>=? "
  200. // existPars = append(existPars, startDate)
  201. //}
  202. sql = fmt.Sprintf(sql, dataTableName)
  203. _, err = to.Raw(sql, edbInfoId, existPars).QueryRows(&existDataList)
  204. if err != nil {
  205. return
  206. }
  207. existDataMap := make(map[string]string)
  208. removeDateMap := make(map[string]string) //需要移除的日期
  209. for _, v := range existDataList {
  210. existDataMap[v.DataTime] = v.Value
  211. removeDateMap[v.DataTime] = v.DataTime
  212. }
  213. //fmt.Println("existDataMap:", existDataMap)
  214. addSql := ` INSERT INTO edb_data_predict_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  215. var isAdd bool
  216. existMap := make(map[string]string)
  217. dataLen := len(dataList)
  218. fmt.Println("dataLen:", dataLen)
  219. for i := 0; i < dataLen; i++ {
  220. j := i + formulaInt
  221. if j < dataLen {
  222. //当期
  223. currentItem := dataList[i]
  224. preItem := dataList[j]
  225. if currentItem != nil && preItem != nil {
  226. existKey := edbCode + currentItem.DataTime
  227. if _, ok := existMap[existKey]; !ok {
  228. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  229. //fmt.Println(currentDate)
  230. timestamp := currentDate.UnixNano() / 1e6
  231. timestampStr := fmt.Sprintf("%d", timestamp)
  232. val := HczDiv(currentItem.Value, preItem.Value)
  233. if val != "" {
  234. if fromEdbInfo.LatestDate == currentItem.DataTime {
  235. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  236. if tmpErr != nil {
  237. err = tmpErr
  238. return
  239. }
  240. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  241. }
  242. // 有计算出来值,那么就从待删除指标中移除
  243. delete(removeDateMap, currentItem.DataTime)
  244. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  245. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  246. isAdd = true
  247. } else {
  248. var existValDecimal decimal.Decimal
  249. existValDecimal, err = decimal.NewFromString(existVal)
  250. if err != nil {
  251. return
  252. }
  253. existStr := existValDecimal.String()
  254. if existStr != val {
  255. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  256. sql = fmt.Sprintf(sql, dataTableName)
  257. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  258. if err != nil {
  259. return
  260. }
  261. }
  262. }
  263. }
  264. }
  265. existMap[existKey] = currentItem.DataTime
  266. }
  267. }
  268. }
  269. if isAdd {
  270. addSql = strings.TrimRight(addSql, ",")
  271. _, err = to.Raw(addSql).Exec()
  272. if err != nil {
  273. return
  274. }
  275. }
  276. //fmt.Println(removeDateMap)
  277. if len(removeDateMap) > 0 {
  278. removeDateList := make([]string, 0) //需要移除的日期
  279. for k := range removeDateMap {
  280. removeDateList = append(removeDateList, k)
  281. }
  282. removeDateStr := strings.Join(removeDateList, `","`)
  283. removeDateStr = `"` + removeDateStr + `"`
  284. //如果拼接指标变更了,那么需要删除所有的指标数据
  285. tableName := GetEdbDataTableName(source, subSource)
  286. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  287. _, err = to.Raw(sql, edbInfoId).Exec()
  288. if err != nil {
  289. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  290. return
  291. }
  292. }
  293. return
  294. }