edb_data_calculate_jp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. // CheckFrequency 判断是否可以降频
  13. func CheckFrequency(fromEdbFrequency, edbFrequency string) (ok bool) {
  14. frequencyList := make([]string, 0)
  15. switch fromEdbFrequency {
  16. case "日度":
  17. frequencyList = []string{"日度"}
  18. case "周度":
  19. frequencyList = []string{"日度", "周度"}
  20. case "旬度":
  21. frequencyList = []string{"日度", "周度", "旬度"}
  22. case "月度":
  23. frequencyList = []string{"日度", "周度", "旬度", "月度"}
  24. case "季度":
  25. frequencyList = []string{"日度", "周度", "旬度", "月度", "季度"}
  26. default:
  27. return
  28. }
  29. // 如果存在,那么就标识不允许降频
  30. if utils.InArrayByStr(frequencyList, edbFrequency) {
  31. return
  32. }
  33. ok = true
  34. return
  35. }
  36. // AddCalculateJp 降频
  37. func AddCalculateJp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  38. o := orm.NewOrm()
  39. to, err := o.Begin()
  40. if err != nil {
  41. return
  42. }
  43. defer func() {
  44. if err != nil {
  45. fmt.Println("AddCalculateJp,Err:" + err.Error())
  46. _ = to.Rollback()
  47. } else {
  48. _ = to.Commit()
  49. }
  50. }()
  51. if req.EdbInfoId <= 0 {
  52. edbInfo = new(EdbInfo)
  53. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_JP
  54. edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_JP
  55. edbInfo.EdbCode = edbCode
  56. edbInfo.EdbName = req.EdbName
  57. edbInfo.EdbNameSource = req.EdbName
  58. edbInfo.Frequency = req.Frequency
  59. edbInfo.Unit = req.Unit
  60. edbInfo.ClassifyId = req.ClassifyId
  61. edbInfo.SysUserId = sysUserId
  62. edbInfo.SysUserRealName = sysUserRealName
  63. edbInfo.CreateTime = time.Now()
  64. edbInfo.ModifyTime = time.Now()
  65. edbInfo.UniqueCode = uniqueCode
  66. edbInfo.CalculateFormula = req.Formula
  67. edbInfo.EdbType = 2
  68. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  69. if tmpErr != nil {
  70. err = tmpErr
  71. return
  72. }
  73. edbInfo.EdbInfoId = int(newEdbInfoId)
  74. //关联关系
  75. {
  76. calculateMappingItem := new(EdbInfoCalculateMapping)
  77. calculateMappingItem.CreateTime = time.Now()
  78. calculateMappingItem.ModifyTime = time.Now()
  79. calculateMappingItem.Sort = 1
  80. calculateMappingItem.EdbCode = edbCode
  81. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  82. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  83. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  84. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  85. calculateMappingItem.FromSource = fromEdbInfo.Source
  86. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  87. calculateMappingItem.FromTag = ""
  88. calculateMappingItem.Source = edbInfo.Source
  89. calculateMappingItem.SourceName = edbInfo.SourceName
  90. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  91. _, err = to.Insert(calculateMappingItem)
  92. if err != nil {
  93. return
  94. }
  95. }
  96. } else {
  97. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  98. if err != nil {
  99. return
  100. }
  101. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_JP, utils.DATA_SUB_SOURCE_EDB)
  102. fmt.Println("dataTableName:" + dataTableName)
  103. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  104. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  105. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  106. if err != nil {
  107. return
  108. }
  109. }
  110. //计算数据
  111. err = refreshAllCalculateJp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.Frequency, edbInfo.CalculateFormula)
  112. return
  113. }
  114. // EditCalculateJp 修改降频数据
  115. func EditCalculateJp(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  116. o := orm.NewOrm()
  117. to, err := o.Begin()
  118. if err != nil {
  119. return
  120. }
  121. defer func() {
  122. if err != nil {
  123. fmt.Println("EditCalculateJp,Err:" + err.Error())
  124. _ = to.Rollback()
  125. } else {
  126. _ = to.Commit()
  127. }
  128. }()
  129. //修改指标信息
  130. edbInfo.EdbName = req.EdbName
  131. edbInfo.EdbNameSource = req.EdbName
  132. edbInfo.Frequency = req.Frequency
  133. edbInfo.Unit = req.Unit
  134. edbInfo.ClassifyId = req.ClassifyId
  135. edbInfo.CalculateFormula = req.Formula
  136. edbInfo.ModifyTime = time.Now()
  137. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  138. if err != nil {
  139. return
  140. }
  141. //判断计算指标是否被更换
  142. var existCondition string
  143. var existPars []interface{}
  144. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  145. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  146. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  147. if err != nil {
  148. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  149. return
  150. }
  151. if count > 0 { // 指标未被替换,无需重新计算
  152. return
  153. }
  154. //删除,计算指标关联的,基础指标的关联关系
  155. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  156. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  157. if err != nil {
  158. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  159. return
  160. }
  161. //清空原有数据
  162. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  163. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  164. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  165. if err != nil {
  166. return
  167. }
  168. //关联关系
  169. {
  170. calculateMappingItem := &EdbInfoCalculateMapping{
  171. EdbInfoCalculateMappingId: 0,
  172. EdbInfoId: edbInfo.EdbInfoId,
  173. Source: edbInfo.Source,
  174. SourceName: edbInfo.SourceName,
  175. EdbCode: edbInfo.EdbCode,
  176. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  177. FromEdbCode: fromEdbInfo.EdbCode,
  178. FromEdbName: fromEdbInfo.EdbName,
  179. FromSource: fromEdbInfo.Source,
  180. FromSourceName: fromEdbInfo.SourceName,
  181. FromTag: "",
  182. Sort: 1,
  183. CreateTime: time.Now(),
  184. ModifyTime: time.Now(),
  185. FromSubSource: fromEdbInfo.SubSource,
  186. }
  187. _, err = to.Insert(calculateMappingItem)
  188. if err != nil {
  189. return
  190. }
  191. }
  192. //计算数据
  193. err = refreshAllCalculateJp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.Frequency, edbInfo.CalculateFormula)
  194. return
  195. }
  196. func RefreshAllCalculateJp(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (err error) {
  197. o := orm.NewOrm()
  198. to, err := o.Begin()
  199. if err != nil {
  200. return
  201. }
  202. defer func() {
  203. if err != nil {
  204. fmt.Println("RefreshAllCalculateJp,Err:" + err.Error())
  205. _ = to.Rollback()
  206. } else {
  207. _ = to.Commit()
  208. }
  209. }()
  210. // 计算数据
  211. err = refreshAllCalculateJp(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, edbFrequency, formula)
  212. return
  213. }
  214. // refreshAllCalculateJp 刷新降频数据
  215. func refreshAllCalculateJp(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (err error) {
  216. edbInfoIdStr := strconv.Itoa(edbInfoId)
  217. //计算数据
  218. var condition string
  219. var pars []interface{}
  220. condition += " AND edb_info_id=? "
  221. pars = append(pars, fromEdbInfo.EdbInfoId)
  222. //if startDate != "" {
  223. // condition += " AND data_time>=? "
  224. // pars = append(pars, startDate)
  225. //}
  226. //if endDate != "" {
  227. // condition += " AND data_time<=? "
  228. // pars = append(pars, endDate)
  229. //}
  230. //获取来源指标的数据
  231. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 1)
  232. if err != nil {
  233. return err
  234. }
  235. var dateArr []string
  236. dataMap := make(map[string]*EdbInfoSearchData)
  237. fromDataMap := make(map[string]float64)
  238. //来源指指标数据
  239. for _, v := range dataList {
  240. dateArr = append(dateArr, v.DataTime)
  241. dataMap[v.DataTime] = v
  242. fromDataMap[v.DataTime] = v.Value
  243. }
  244. fmt.Println("source:", source)
  245. //获取降频指标所有数据
  246. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  247. if err != nil {
  248. return
  249. }
  250. //计算指标的map
  251. existDataMap := make(map[string]*EdbData, 0)
  252. //existDataMap := make(map[string]string, 0)
  253. for _, v := range existDataList {
  254. existDataMap[v.DataTime] = v
  255. }
  256. tableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_JP, subSource)
  257. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  258. var isAdd bool
  259. //existMap := make(map[string]string)
  260. dataLen := len(dataList)
  261. if dataLen <= 0 {
  262. return
  263. }
  264. startDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  265. endDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[dataLen-1].DataTime, time.Local)
  266. var lastValue float64 // 最近的值
  267. var nextEndDate time.Time // 下一个节点的日期
  268. weekDayDataList := make([]float64, 0)
  269. for tmpStartDataTime := startDataTime; !tmpStartDataTime.After(endDataTime); tmpStartDataTime = tmpStartDataTime.AddDate(0, 0, 1) {
  270. // 将当前数据加入到 weekDayDataList
  271. if tmpData, ok := dataMap[tmpStartDataTime.Format(utils.FormatDate)]; ok {
  272. tmpValue := decimal.NewFromFloat(tmpData.Value)
  273. tmpValueFloat, _ := tmpValue.Round(4).Float64()
  274. weekDayDataList = append(weekDayDataList, tmpValueFloat)
  275. }
  276. // 如果下个节点的日期不存在,那么就先给赋值(兼容时间区间内只有一组数据的情况)
  277. if nextEndDate.IsZero() {
  278. nextEndDate = utils.GetFrequencyEndDay(tmpStartDataTime, edbFrequency)
  279. }
  280. // 日期处理过滤
  281. switch edbFrequency {
  282. case "周度":
  283. if tmpStartDataTime.Weekday() != 0 {
  284. //不是周日,代表需要进入下一个循环获取数据并计算
  285. continue
  286. } else {
  287. //记录下一个结束节点的日期
  288. nextEndDate = tmpStartDataTime.AddDate(0, 0, 7)
  289. }
  290. case "旬度":
  291. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  292. if nextDay.Day() != 1 && nextDay.Day() != 11 && nextDay.Day() != 21 {
  293. //不是每月10、20、最后一天,代表需要进入下一个循环获取数据并计算
  294. continue
  295. } else {
  296. //记录下一个结束节点的日期
  297. if nextDay.Day() == 1 || nextDay.Day() == 11 {
  298. //月初或者月末的时候,加10天就好了
  299. nextEndDate = nextDay.AddDate(0, 0, 9)
  300. } else {
  301. tmpNextMonth := nextDay.AddDate(0, 1, 0)
  302. nextEndDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  303. }
  304. }
  305. case "月度":
  306. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  307. if nextDay.Day() != 1 {
  308. //不是每月最后一天,代表需要进入下一个循环获取数据并计算
  309. continue
  310. } else {
  311. //记录下一个结束节点的日期
  312. nextEndDate = nextDay.AddDate(0, 1, -1)
  313. }
  314. case "季度":
  315. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  316. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  317. //记录下一个结束节点的日期
  318. nextEndDate = nextDay.AddDate(0, 3, -1)
  319. } else {
  320. //不是3,6,9,12 月份的最后一天,代表需要进入下一个循环获取数据并计算
  321. continue
  322. }
  323. case "年度":
  324. if tmpStartDataTime.Month() == 12 && tmpStartDataTime.Day() == 31 {
  325. //记录下一个结束节点的日期
  326. nextEndDate = tmpStartDataTime.AddDate(1, 0, 0)
  327. } else {
  328. //不是每年的12-31日,代表需要进入下一个循环获取数据并计算
  329. continue
  330. }
  331. default:
  332. err = errors.New("错误的频度:" + edbFrequency)
  333. return
  334. }
  335. // 当前时间段内的数据计算,得出实际值
  336. var currVal float64
  337. lenWeekDayDataList := len(weekDayDataList)
  338. // 如果这个时间区间内没有数据,那么就采用上一个时间区间的值
  339. if len(weekDayDataList) <= 0 {
  340. currVal = lastValue
  341. } else {
  342. if formula == "期末值" {
  343. currVal = weekDayDataList[lenWeekDayDataList-1]
  344. } else {
  345. // 平均值
  346. sumValDeci := decimal.NewFromFloat(0)
  347. for _, v := range weekDayDataList {
  348. tmpValDeci := decimal.NewFromFloat(v)
  349. sumValDeci = sumValDeci.Add(tmpValDeci)
  350. }
  351. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  352. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  353. }
  354. }
  355. // 判断降频指标是否存在数据
  356. if existData, ok := existDataMap[tmpStartDataTime.Format(utils.FormatDate)]; ok {
  357. // 处理降频数据的值
  358. existValStr := existData.Value
  359. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  360. if tmpErr != nil {
  361. err = tmpErr
  362. return
  363. }
  364. existVal, _ := existValDeci.Round(4).Float64()
  365. // 判断降频数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  366. if existVal != currVal {
  367. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  368. if err != nil {
  369. return err
  370. }
  371. }
  372. } else {
  373. // 直接入库
  374. timestamp := tmpStartDataTime.UnixNano() / 1e6
  375. timestampStr := fmt.Sprintf("%d", timestamp)
  376. addSql += GetAddSql(edbInfoIdStr, edbCode, tmpStartDataTime.Format(utils.FormatDate), timestampStr, fmt.Sprint(currVal))
  377. isAdd = true
  378. }
  379. // 一轮结束后,数据清空
  380. weekDayDataList = make([]float64, 0)
  381. }
  382. // 最后已有的日期处理完成后,需要对剩余不在时间段内的数据做处理
  383. if len(weekDayDataList) > 0 {
  384. // 当前时间段内的数据计算,得出实际值
  385. var currVal float64
  386. lenWeekDayDataList := len(weekDayDataList)
  387. // 如果这个时间区间内没有数据,那么就采用上一个时间区间的值
  388. if len(weekDayDataList) < 0 {
  389. currVal = lastValue
  390. } else {
  391. if formula == "期末值" {
  392. currVal = weekDayDataList[lenWeekDayDataList-1]
  393. } else {
  394. // 平均值
  395. sumValDeci := decimal.NewFromFloat(0)
  396. for _, v := range weekDayDataList {
  397. tmpValDeci := decimal.NewFromFloat(v)
  398. sumValDeci = sumValDeci.Add(tmpValDeci)
  399. }
  400. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  401. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  402. }
  403. }
  404. // 判断降频指标是否存在数据
  405. if existData, ok := existDataMap[nextEndDate.Format(utils.FormatDate)]; ok {
  406. // 处理降频数据的值
  407. existValStr := existData.Value
  408. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  409. if tmpErr != nil {
  410. err = tmpErr
  411. return
  412. }
  413. existVal, _ := existValDeci.Round(4).Float64()
  414. // 判断降频数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  415. if existVal != currVal {
  416. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  417. if err != nil {
  418. return err
  419. }
  420. }
  421. } else {
  422. // 直接入库
  423. timestamp := nextEndDate.UnixNano() / 1e6
  424. timestampStr := fmt.Sprintf("%d", timestamp)
  425. addSql += GetAddSql(edbInfoIdStr, edbCode, nextEndDate.Format(utils.FormatDate), timestampStr, fmt.Sprint(currVal))
  426. isAdd = true
  427. }
  428. }
  429. if isAdd {
  430. addSql = strings.TrimRight(addSql, ",")
  431. _, err = to.Raw(addSql).Exec()
  432. }
  433. return
  434. }