edb_data_calculate_nh.go 11 KB

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