predict_edb_data_calculate_jp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 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: "",
  57. UnitEn: "",
  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. edbInfo.EdbName = edbName
  109. edbInfo.EdbNameSource = edbName
  110. edbInfo.Frequency = frequency
  111. edbInfo.Unit = unit
  112. edbInfo.ClassifyId = classifyId
  113. edbInfo.CalculateFormula = formula
  114. edbInfo.ModifyTime = time.Now()
  115. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  116. if err != nil {
  117. return
  118. }
  119. //判断计算指标是否被更换
  120. var existCondition string
  121. var existPars []interface{}
  122. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  123. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  124. count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  125. if tmpErr != nil {
  126. err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
  127. return
  128. }
  129. if count > 0 && formula == oldCalculateFormula { // 指标未被替换,无需重新计算
  130. return
  131. }
  132. //删除,计算指标关联的,基础指标的关联关系
  133. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  134. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  135. if err != nil {
  136. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  137. return
  138. }
  139. //清空原有已经入库的数据
  140. tableName := GetEdbDataTableName(edbInfo.Source)
  141. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  142. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  143. if err != nil {
  144. return
  145. }
  146. //关联关系
  147. {
  148. calculateMappingItem := &EdbInfoCalculateMapping{
  149. EdbInfoCalculateMappingId: 0,
  150. EdbInfoId: edbInfo.EdbInfoId,
  151. Source: edbInfo.Source,
  152. SourceName: edbInfo.SourceName,
  153. EdbCode: edbCode,
  154. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  155. FromEdbCode: fromEdbInfo.EdbCode,
  156. FromEdbName: fromEdbInfo.EdbName,
  157. FromSource: fromEdbInfo.Source,
  158. FromSourceName: fromEdbInfo.SourceName,
  159. FromTag: "",
  160. Sort: 1,
  161. CreateTime: time.Now(),
  162. ModifyTime: time.Now(),
  163. }
  164. _, err = to.Insert(calculateMappingItem)
  165. if err != nil {
  166. return
  167. }
  168. }
  169. }
  170. // 计算数据
  171. latestDateStr, latestValue, err = refreshAllPredictCalculateJp(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbCode, edbInfo.Frequency, formula)
  172. return
  173. }
  174. // RefreshAllPredictCalculateJp 刷新全部预测降频值数据
  175. func RefreshAllPredictCalculateJp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (latestDateStr string, latestValue float64, err error) {
  176. o := orm.NewOrm()
  177. to, err := o.Begin()
  178. if err != nil {
  179. return
  180. }
  181. defer func() {
  182. if err != nil {
  183. fmt.Println("RefreshAllCalculateJp,Err:" + err.Error())
  184. _ = to.Rollback()
  185. } else {
  186. _ = to.Commit()
  187. }
  188. }()
  189. // 计算数据
  190. latestDateStr, latestValue, err = refreshAllPredictCalculateJp(to, edbInfoId, source, fromEdbInfo, edbCode, edbFrequency, formula)
  191. return
  192. }
  193. // refreshAllPredictCalculateJp 刷新预测降频数据
  194. func refreshAllPredictCalculateJp(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (latestDateStr string, latestValue float64, err error) {
  195. edbInfoIdStr := strconv.Itoa(edbInfoId)
  196. //获取源指标数据
  197. fmt.Println("EdbInfoId:", fromEdbInfo.EdbInfoId)
  198. dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  199. if err != nil {
  200. return
  201. }
  202. var dateArr []string
  203. dataMap := make(map[string]*EdbInfoSearchData)
  204. fromDataMap := make(map[string]float64)
  205. //来源指指标数据
  206. for _, v := range dataList {
  207. dateArr = append(dateArr, v.DataTime)
  208. dataMap[v.DataTime] = v
  209. fromDataMap[v.DataTime] = v.Value
  210. }
  211. fmt.Println("source:", source)
  212. //获取降频指标所有数据
  213. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source)
  214. if err != nil {
  215. return
  216. }
  217. //计算指标的map
  218. existDataMap := make(map[string]*EdbData, 0)
  219. for _, v := range existDataList {
  220. existDataMap[v.DataTime] = v
  221. }
  222. latestDateStr = fromEdbInfo.LatestDate
  223. tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_JP)
  224. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  225. var isAdd bool
  226. //existMap := make(map[string]string)
  227. dataLen := len(dataList)
  228. if dataLen <= 0 {
  229. return
  230. }
  231. startDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  232. endDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[dataLen-1].DataTime, time.Local)
  233. var lastValue float64 // 最近的值
  234. var nextEndDate time.Time // 下一个节点的日期
  235. weekDayDataList := make([]float64, 0)
  236. for currStartDataTime := startDataTime; !currStartDataTime.After(endDataTime); currStartDataTime = currStartDataTime.AddDate(0, 0, 1) {
  237. // 将当前数据加入到 weekDayDataList
  238. if tmpData, ok := dataMap[currStartDataTime.Format(utils.FormatDate)]; ok {
  239. tmpValue := decimal.NewFromFloat(tmpData.Value)
  240. tmpValueFloat, _ := tmpValue.Round(4).Float64()
  241. weekDayDataList = append(weekDayDataList, tmpValueFloat)
  242. }
  243. // 如果下个节点的日期不存在,那么就先给赋值(兼容时间区间内只有一组数据的情况)
  244. if nextEndDate.IsZero() {
  245. nextEndDate = utils.GetFrequencyEndDay(currStartDataTime, edbFrequency)
  246. }
  247. // 日期处理过滤
  248. switch edbFrequency {
  249. case "周度":
  250. if currStartDataTime.Weekday() != 0 {
  251. //不是周日,代表需要进入下一个循环获取数据并计算
  252. continue
  253. } else {
  254. //记录下一个结束节点的日期
  255. nextEndDate = currStartDataTime.AddDate(0, 0, 7)
  256. }
  257. case "旬度":
  258. nextDay := currStartDataTime.AddDate(0, 0, 1)
  259. if nextDay.Day() != 1 && nextDay.Day() != 11 && nextDay.Day() != 21 {
  260. //不是每月10、20、最后一天,代表需要进入下一个循环获取数据并计算
  261. continue
  262. } else {
  263. //记录下一个结束节点的日期
  264. if nextDay.Day() == 1 || nextDay.Day() == 11 {
  265. //月初或者月末的时候,加10天就好了
  266. nextEndDate = nextDay.AddDate(0, 0, 9)
  267. } else {
  268. tmpNextMonth := nextDay.AddDate(0, 1, 0)
  269. nextEndDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  270. }
  271. }
  272. case "月度":
  273. nextDay := currStartDataTime.AddDate(0, 0, 1)
  274. if nextDay.Day() != 1 {
  275. //不是每月最后一天,代表需要进入下一个循环获取数据并计算
  276. continue
  277. } else {
  278. //记录下一个结束节点的日期
  279. nextEndDate = nextDay.AddDate(0, 1, -1)
  280. }
  281. case "季度":
  282. nextDay := currStartDataTime.AddDate(0, 0, 1)
  283. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  284. //记录下一个结束节点的日期
  285. nextEndDate = nextDay.AddDate(0, 3, -1)
  286. } else {
  287. //不是3,6,9,12 月份的最后一天,代表需要进入下一个循环获取数据并计算
  288. continue
  289. }
  290. case "年度":
  291. if currStartDataTime.Month() == 12 && currStartDataTime.Day() == 31 {
  292. //记录下一个结束节点的日期
  293. nextEndDate = currStartDataTime.AddDate(1, 0, 0)
  294. } else {
  295. //不是每年的12-31日,代表需要进入下一个循环获取数据并计算
  296. continue
  297. }
  298. default:
  299. err = errors.New("错误的频度:" + edbFrequency)
  300. return
  301. }
  302. // 当前时间段内的数据计算,得出实际值
  303. var currVal float64
  304. lenWeekDayDataList := len(weekDayDataList)
  305. // 如果这个时间区间内没有数据,那么就采用上一个时间区间的值
  306. if len(weekDayDataList) <= 0 {
  307. currVal = lastValue
  308. } else {
  309. if formula == "期末值" {
  310. currVal = weekDayDataList[lenWeekDayDataList-1]
  311. } else {
  312. // 平均值
  313. sumValDeci := decimal.NewFromFloat(0)
  314. for _, v := range weekDayDataList {
  315. tmpValDeci := decimal.NewFromFloat(v)
  316. sumValDeci = sumValDeci.Add(tmpValDeci)
  317. }
  318. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  319. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  320. }
  321. }
  322. // 给实际日期数据的值赋值
  323. if fromEdbInfo.LatestDate == currStartDataTime.Format(utils.FormatDate) {
  324. latestValue = currVal
  325. }
  326. // 判断降频指标是否存在数据
  327. if existData, ok := existDataMap[currStartDataTime.Format(utils.FormatDate)]; ok {
  328. // 处理降频数据的值
  329. existValStr := existData.Value
  330. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  331. if tmpErr != nil {
  332. err = tmpErr
  333. return
  334. }
  335. existVal, _ := existValDeci.Round(4).Float64()
  336. // 判断降频数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  337. if existVal != currVal {
  338. err = ModifyEdbDataById(source, existData.EdbDataId, fmt.Sprint(currVal))
  339. if err != nil {
  340. return
  341. }
  342. }
  343. } else {
  344. // 直接入库
  345. timestamp := currStartDataTime.UnixNano() / 1e6
  346. timestampStr := fmt.Sprintf("%d", timestamp)
  347. addSql += GetAddSql(edbInfoIdStr, edbCode, currStartDataTime.Format(utils.FormatDate), timestampStr, fmt.Sprint(currVal))
  348. isAdd = true
  349. }
  350. // 一轮结束后,数据清空
  351. weekDayDataList = make([]float64, 0)
  352. }
  353. // 最后已有的日期处理完成后,需要对剩余不在时间段内的数据做处理
  354. if len(weekDayDataList) > 0 {
  355. // 当前时间段内的数据计算,得出实际值
  356. var currVal float64
  357. lenWeekDayDataList := len(weekDayDataList)
  358. // 如果这个时间区间内没有数据,那么就采用上一个时间区间的值
  359. if len(weekDayDataList) < 0 {
  360. currVal = lastValue
  361. } else {
  362. if formula == "期末值" {
  363. currVal = weekDayDataList[lenWeekDayDataList-1]
  364. } else {
  365. // 平均值
  366. sumValDeci := decimal.NewFromFloat(0)
  367. for _, v := range weekDayDataList {
  368. tmpValDeci := decimal.NewFromFloat(v)
  369. sumValDeci = sumValDeci.Add(tmpValDeci)
  370. }
  371. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  372. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  373. }
  374. }
  375. // 判断降频指标是否存在数据
  376. if existData, ok := existDataMap[nextEndDate.Format(utils.FormatDate)]; ok {
  377. // 处理降频数据的值
  378. existValStr := existData.Value
  379. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  380. if tmpErr != nil {
  381. err = tmpErr
  382. return
  383. }
  384. existVal, _ := existValDeci.Round(4).Float64()
  385. // 判断降频数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  386. if existVal != currVal {
  387. err = ModifyEdbDataById(source, existData.EdbDataId, fmt.Sprint(currVal))
  388. if err != nil {
  389. return
  390. }
  391. }
  392. } else {
  393. // 直接入库
  394. timestamp := nextEndDate.UnixNano() / 1e6
  395. timestampStr := fmt.Sprintf("%d", timestamp)
  396. addSql += GetAddSql(edbInfoIdStr, edbCode, nextEndDate.Format(utils.FormatDate), timestampStr, fmt.Sprint(currVal))
  397. isAdd = true
  398. }
  399. }
  400. if isAdd {
  401. addSql = strings.TrimRight(addSql, ",")
  402. _, err = to.Raw(addSql).Exec()
  403. }
  404. return
  405. }