edb_data_calculate_nh.go 11 KB

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