predict_edb_data_calculate_nh.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. // SavePredictCalculateNh 预测年化值
  14. func SavePredictCalculateNh(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  15. to := global.DEFAULT_DmSQL.Begin()
  16. defer func() {
  17. if err != nil {
  18. to.Rollback()
  19. } else {
  20. to.Commit()
  21. }
  22. }()
  23. fmt.Println("reqEdbInfoId:", reqEdbInfoId)
  24. if reqEdbInfoId <= 0 {
  25. edbInfo = &EdbInfo{
  26. //EdbInfoId: 0,
  27. EdbInfoType: 1,
  28. SourceName: utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_NH,
  29. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_NH,
  30. EdbCode: edbCode,
  31. EdbName: edbName,
  32. EdbNameSource: edbName,
  33. Frequency: frequency,
  34. Unit: unit,
  35. //StartDate: "",
  36. //EndDate: "",
  37. ClassifyId: classifyId,
  38. SysUserId: sysUserId,
  39. SysUserRealName: sysUserRealName,
  40. UniqueCode: uniqueCode,
  41. CreateTime: time.Now(),
  42. ModifyTime: time.Now(),
  43. MinValue: 0,
  44. MaxValue: 0,
  45. CalculateFormula: formula,
  46. EdbType: 2,
  47. Sort: GetAddEdbMaxSortByClassifyId(classifyId, utils.PREDICT_EDB_INFO_TYPE),
  48. MoveType: 0,
  49. MoveFrequency: "",
  50. NoUpdate: 0,
  51. ServerUrl: "",
  52. EdbNameEn: edbName,
  53. UnitEn: unit,
  54. LatestDate: "",
  55. LatestValue: 0,
  56. ChartImage: "",
  57. }
  58. tmpErr := to.Create(edbInfo).Error
  59. if tmpErr != nil {
  60. err = tmpErr
  61. return
  62. }
  63. // 添加关联关系
  64. {
  65. calculateMappingItem := &EdbInfoCalculateMapping{
  66. EdbInfoCalculateMappingId: 0,
  67. EdbInfoId: edbInfo.EdbInfoId,
  68. Source: edbInfo.Source,
  69. SourceName: edbInfo.SourceName,
  70. EdbCode: edbCode,
  71. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  72. FromEdbCode: fromEdbInfo.EdbCode,
  73. FromEdbName: fromEdbInfo.EdbName,
  74. FromSource: fromEdbInfo.Source,
  75. FromSourceName: fromEdbInfo.SourceName,
  76. FromTag: "",
  77. Sort: 1,
  78. CreateTime: time.Now(),
  79. ModifyTime: time.Now(),
  80. }
  81. err = to.Create(calculateMappingItem).Error
  82. if err != nil {
  83. return
  84. }
  85. }
  86. } else {
  87. edbInfo, err = GetEdbInfoById(reqEdbInfoId)
  88. if err != nil {
  89. if err.Error() == utils.ErrNoRow() {
  90. errMsg = `获取指标信息失败`
  91. }
  92. return
  93. }
  94. if edbInfo.EdbInfoType != 1 {
  95. errMsg = `该指标不是预测指标`
  96. err = errors.New(errMsg)
  97. return
  98. }
  99. latestDateStr = edbInfo.LatestDate
  100. latestValue = edbInfo.LatestValue
  101. //修改指标信息
  102. switch lang {
  103. case utils.EnLangVersion:
  104. edbInfo.EdbNameEn = edbName
  105. edbInfo.UnitEn = unit
  106. default:
  107. edbInfo.EdbName = edbName
  108. edbInfo.Unit = unit
  109. edbInfo.EdbNameSource = edbName
  110. }
  111. edbInfo.Frequency = frequency
  112. edbInfo.ClassifyId = classifyId
  113. edbInfo.CalculateFormula = formula
  114. edbInfo.ModifyTime = time.Now()
  115. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  116. if err != nil {
  117. return
  118. }
  119. //判断计算指标是否被更换
  120. var existCondition string
  121. var existPars []interface{}
  122. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  123. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  124. count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  125. if tmpErr != nil {
  126. err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
  127. return
  128. }
  129. if count > 0 { // 指标未被替换,无需重新计算
  130. return
  131. }
  132. //删除,计算指标关联的,基础指标的关联关系
  133. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  134. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  135. if err != nil {
  136. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  137. return
  138. }
  139. //清空原有已经入库的数据
  140. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  141. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  142. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  143. if err != nil {
  144. return
  145. }
  146. //关联关系
  147. {
  148. calculateMappingItem := &EdbInfoCalculateMapping{
  149. EdbInfoCalculateMappingId: 0,
  150. EdbInfoId: edbInfo.EdbInfoId,
  151. Source: edbInfo.Source,
  152. SourceName: edbInfo.SourceName,
  153. EdbCode: edbCode,
  154. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  155. FromEdbCode: fromEdbInfo.EdbCode,
  156. FromEdbName: fromEdbInfo.EdbName,
  157. FromSource: fromEdbInfo.Source,
  158. FromSourceName: fromEdbInfo.SourceName,
  159. FromTag: "",
  160. Sort: 1,
  161. CreateTime: time.Now(),
  162. ModifyTime: time.Now(),
  163. }
  164. err = to.Create(calculateMappingItem).Error
  165. if err != nil {
  166. return
  167. }
  168. }
  169. }
  170. // 计算数据
  171. latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbCode)
  172. return
  173. }
  174. // RefreshAllPredictCalculateNh 刷新全部预测年化值数据
  175. func RefreshAllPredictCalculateNh(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (latestDateStr string, latestValue float64, err error) {
  176. to := global.DEFAULT_DmSQL.Begin()
  177. defer func() {
  178. if err != nil {
  179. to.Rollback()
  180. } else {
  181. to.Commit()
  182. }
  183. }()
  184. // 计算数据
  185. latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfoId, source, subSource, fromEdbInfo, edbCode)
  186. return
  187. }
  188. // refreshAllPredictCalculateNh 刷新预测年化数据
  189. func refreshAllPredictCalculateNh(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode string) (latestDateStr string, latestValue float64, err error) {
  190. edbInfoIdStr := strconv.Itoa(edbInfoId)
  191. tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NH, subSource)
  192. //获取年化指标所有数据
  193. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  194. if err != nil {
  195. return
  196. }
  197. //计算指标的map
  198. existDataMap := make(map[string]*EdbData, 0)
  199. removeDateMap := make(map[string]string)
  200. for _, v := range existDataList {
  201. existDataMap[v.DataTime] = v
  202. removeDateMap[v.DataTime] = ``
  203. }
  204. //获取源指标数据
  205. fmt.Println("EdbInfoId:", fromEdbInfo.EdbInfoId)
  206. fromDataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  207. if err != nil {
  208. return
  209. }
  210. // 插值法数据处理
  211. handleDataMap := make(map[string]float64)
  212. _, err = HandleDataByLinearRegression(fromDataList, handleDataMap)
  213. if err != nil {
  214. return
  215. }
  216. var dateArr []string
  217. dataMap := make(map[string]*EdbInfoSearchData)
  218. fromDataMap := make(map[string]float64)
  219. //来源指指标数据
  220. for _, v := range fromDataList {
  221. dateArr = append(dateArr, v.DataTime)
  222. dataMap[v.DataTime] = v
  223. fromDataMap[v.DataTime] = v.Value
  224. }
  225. lenFromDataList := len(fromDataList)
  226. // 如果来源指标没有数据,那么就直接返回得了
  227. if lenFromDataList <= 0 {
  228. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  229. err = to.Exec(sql, edbInfoId).Error
  230. if err != nil {
  231. err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
  232. return
  233. }
  234. return
  235. }
  236. fmt.Println("source:", source)
  237. // 真实数据的最后日期
  238. latestDateStr = fromEdbInfo.LatestDate
  239. // 每年的最后一天的数据值
  240. yearLastValMap := make(map[int]float64)
  241. startDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[0].DataTime, time.Local)
  242. endDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[lenFromDataList-1].DataTime, time.Local)
  243. for i := startDataTime.Year(); i <= endDataTime.Year(); i++ {
  244. tmpDateStr := fmt.Sprintf("%d-12-31", i)
  245. if tmpVal, ok := handleDataMap[tmpDateStr]; ok {
  246. yearLastValMap[i] = tmpVal
  247. }
  248. }
  249. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  250. var isAdd bool
  251. //来源指指标数据
  252. for _, v := range fromDataList {
  253. currDateStr := v.DataTime
  254. currDate, _ := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  255. perValMap := make(map[time.Time]float64)
  256. //前3年当日的数据
  257. for i := 1; i <= 3; i++ {
  258. tmpDateTime := currDate.AddDate(-i, 0, 0)
  259. if tmpVal, ok := handleDataMap[tmpDateTime.Format(utils.FormatDate)]; ok {
  260. perValMap[tmpDateTime] = tmpVal
  261. }
  262. }
  263. lenPerValMap := len(perValMap)
  264. // 如果数据少于2年,那么就不参与计算,结束当前循环,进入下一个循环
  265. if lenPerValMap < 2 {
  266. continue
  267. }
  268. // N年 当前值占全年比重 的值列表
  269. divValList := make([]decimal.Decimal, 0)
  270. for tmpDateTime, tmpVal := range perValMap {
  271. yearLastVal, ok2 := yearLastValMap[tmpDateTime.Year()]
  272. // 如果当年最后一天没有数据
  273. if !ok2 {
  274. continue
  275. }
  276. // 当前值占全年比重
  277. divVal := decimal.NewFromFloat(tmpVal).Div(decimal.NewFromFloat(yearLastVal))
  278. divValList = append(divValList, divVal)
  279. }
  280. lenDivValList := len(divValList)
  281. // 如果 N年 当前值占全年比重 的值 小于 2个,那么就不参与计算,结束当前循环,进入下一个循环
  282. if lenDivValList < 2 {
  283. continue
  284. }
  285. divValSum := decimal.NewFromFloat(0)
  286. for _, divVal := range divValList {
  287. divValSum = divValSum.Add(divVal)
  288. }
  289. // 当前计算出来的结果
  290. currVal, _ := decimal.NewFromFloat(v.Value).Div(divValSum.Div(decimal.NewFromInt(int64(lenDivValList)))).Round(4).Float64()
  291. // 给实际日期数据的值赋值
  292. if fromEdbInfo.LatestDate == currDateStr {
  293. latestValue = currVal
  294. }
  295. // 判断年化指标是否存在数据
  296. if existData, ok := existDataMap[currDateStr]; ok {
  297. // 处理年化数据的值
  298. existValStr := existData.Value
  299. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  300. if tmpErr != nil {
  301. err = tmpErr
  302. return
  303. }
  304. existVal, _ := existValDeci.Round(4).Float64()
  305. // 判断年化数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  306. if existVal != currVal {
  307. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  308. if err != nil {
  309. return
  310. }
  311. }
  312. } else {
  313. // 直接入库
  314. timestamp := currDate.UnixNano() / 1e6
  315. timestampStr := fmt.Sprintf("%d", timestamp)
  316. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  317. isAdd = true
  318. }
  319. delete(removeDateMap, currDateStr)
  320. }
  321. if isAdd {
  322. addSql = strings.TrimRight(addSql, ",")
  323. err = to.Exec(addSql).Error
  324. }
  325. // 移除不存在的日期数据
  326. if len(removeDateMap) > 0 {
  327. removeDateList := make([]string, 0) //需要移除的日期
  328. for k := range removeDateMap {
  329. removeDateList = append(removeDateList, k)
  330. }
  331. removeDateStr := strings.Join(removeDateList, `','`)
  332. removeDateStr = `'` + removeDateStr + `'`
  333. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  334. err = to.Exec(sql, edbInfoId).Error
  335. if err != nil {
  336. err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
  337. return
  338. }
  339. }
  340. return
  341. }