edb_data_calculate_nh.go 11 KB

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