edb_data_calculate_nh.go 11 KB

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