edb_data_calculate_jp.go 15 KB

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