edb_data_calculate_jp.go 15 KB

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