predict_edb_data_calculate_jp.go 15 KB

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