predict_edb_data_calculate_ljznczj.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // PredictLjzNczj 预测累计值年初至今
  14. type PredictLjzNczj struct {
  15. }
  16. // Add 添加
  17. func (obj PredictLjzNczj) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  18. req := params.Req
  19. fromEdbInfo := params.FromEdbInfo
  20. edbCode := params.EdbCode
  21. if fromEdbInfo.Frequency == `年度` {
  22. errMsg = "年初至今累计值计算中,可选指标范围为非年度指标"
  23. err = errors.New(errMsg)
  24. return
  25. }
  26. if fromEdbInfo.Frequency != req.Frequency {
  27. errMsg = "生成指标频度与原指标频度不同"
  28. err = errors.New(errMsg)
  29. return
  30. }
  31. o := orm.NewOrm()
  32. to, err := o.Begin()
  33. if err != nil {
  34. return
  35. }
  36. defer func() {
  37. if err != nil {
  38. _ = to.Rollback()
  39. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  40. } else {
  41. _ = to.Commit()
  42. }
  43. }()
  44. edbInfo = &EdbInfo{
  45. //EdbInfoId: 0,
  46. SourceName: obj.GetSourceName(),
  47. Source: obj.GetSource(),
  48. EdbCode: edbCode,
  49. EdbName: req.EdbName,
  50. EdbNameSource: req.EdbName,
  51. Frequency: req.Frequency,
  52. Unit: req.Unit,
  53. StartDate: "",
  54. EndDate: "",
  55. ClassifyId: req.ClassifyId,
  56. SysUserId: params.SysUserId,
  57. SysUserRealName: params.SysUserRealName,
  58. UniqueCode: params.UniqueCode,
  59. CreateTime: time.Now(),
  60. ModifyTime: time.Now(),
  61. MinValue: 0,
  62. MaxValue: 0,
  63. CalculateFormula: req.Formula,
  64. EdbType: 2,
  65. Sort: GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE),
  66. MoveType: 0,
  67. MoveFrequency: "",
  68. NoUpdate: 0,
  69. ServerUrl: "",
  70. EdbInfoType: 1,
  71. EdbNameEn: req.EdbName,
  72. UnitEn: req.Unit,
  73. LatestDate: "",
  74. LatestValue: 0,
  75. ChartImage: "",
  76. Calendar: "",
  77. }
  78. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  79. if tmpErr != nil {
  80. err = tmpErr
  81. return
  82. }
  83. edbInfo.EdbInfoId = int(newEdbInfoId)
  84. //关联关系
  85. {
  86. calculateMappingItem := new(EdbInfoCalculateMapping)
  87. calculateMappingItem.CreateTime = time.Now()
  88. calculateMappingItem.ModifyTime = time.Now()
  89. calculateMappingItem.Sort = 1
  90. calculateMappingItem.EdbCode = edbCode
  91. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  92. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  93. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  94. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  95. calculateMappingItem.FromSource = fromEdbInfo.Source
  96. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  97. calculateMappingItem.FromTag = ""
  98. calculateMappingItem.Source = edbInfo.Source
  99. calculateMappingItem.SourceName = edbInfo.SourceName
  100. _, err = to.Insert(calculateMappingItem)
  101. if err != nil {
  102. return
  103. }
  104. }
  105. //计算数据
  106. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  107. return
  108. }
  109. // Edit 编辑
  110. func (obj PredictLjzNczj) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  111. req := params.Req
  112. edbInfo := params.EdbInfo
  113. fromEdbInfo := params.FromEdbInfo
  114. if fromEdbInfo.Frequency == `年度` {
  115. errMsg = "年初至今累计值计算中,可选指标范围为非年度指标"
  116. err = errors.New(errMsg)
  117. return
  118. }
  119. if fromEdbInfo.Frequency != req.Frequency {
  120. errMsg = "生成指标频度与原指标频度不同"
  121. err = errors.New(errMsg)
  122. return
  123. }
  124. latestDateStr = edbInfo.LatestDate
  125. latestValue = edbInfo.LatestValue
  126. o := orm.NewOrm()
  127. to, err := o.Begin()
  128. if err != nil {
  129. return
  130. }
  131. defer func() {
  132. if err != nil {
  133. _ = to.Rollback()
  134. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  135. } else {
  136. _ = to.Commit()
  137. }
  138. }()
  139. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  140. var isRecalculate bool
  141. if edbInfo.Frequency != req.Frequency {
  142. isRecalculate = true
  143. }
  144. //修改指标信息
  145. switch params.Lang {
  146. case utils.EnLangVersion:
  147. edbInfo.EdbNameEn = req.EdbName
  148. edbInfo.UnitEn = req.Unit
  149. default:
  150. edbInfo.EdbName = req.EdbName
  151. edbInfo.Unit = req.Unit
  152. edbInfo.EdbNameSource = req.EdbName
  153. }
  154. edbInfo.Frequency = req.Frequency
  155. edbInfo.ClassifyId = req.ClassifyId
  156. edbInfo.ModifyTime = time.Now()
  157. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  158. if err != nil {
  159. return
  160. }
  161. var existCondition string
  162. var existPars []interface{}
  163. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  164. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  165. //判断计算指标是否被更换
  166. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  167. if err != nil {
  168. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  169. return
  170. }
  171. if count > 0 { // 指标未被替换,无需删除关联数据
  172. // 频度被换了,需要重新计算
  173. if isRecalculate {
  174. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  175. }
  176. return
  177. }
  178. //删除,计算指标关联的,基础指标的关联关系
  179. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  180. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  181. if err != nil {
  182. return
  183. }
  184. //清空原有数据
  185. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  186. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  187. if err != nil {
  188. return
  189. }
  190. //关联关系
  191. {
  192. calculateMappingItem := &EdbInfoCalculateMapping{
  193. EdbInfoCalculateMappingId: 0,
  194. EdbInfoId: edbInfo.EdbInfoId,
  195. Source: obj.GetSource(),
  196. SourceName: obj.GetSourceName(),
  197. EdbCode: edbInfo.EdbCode,
  198. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  199. FromEdbCode: fromEdbInfo.EdbCode,
  200. FromEdbName: fromEdbInfo.EdbName,
  201. FromSource: fromEdbInfo.Source,
  202. FromSourceName: fromEdbInfo.SourceName,
  203. FromTag: "",
  204. Sort: 1,
  205. CreateTime: time.Now(),
  206. ModifyTime: time.Now(),
  207. }
  208. _, err = to.Insert(calculateMappingItem)
  209. if err != nil {
  210. return
  211. }
  212. }
  213. //计算数据
  214. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  215. return
  216. }
  217. // Refresh 刷新
  218. func (obj PredictLjzNczj) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  219. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  220. if err != nil {
  221. errMsg = "GetEdbInfoCalculatePredictLjzNczjzyDetail Err:" + err.Error()
  222. return
  223. }
  224. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  225. if err != nil {
  226. errMsg = "GetEdbInfoById Err:" + err.Error()
  227. return
  228. }
  229. o := orm.NewOrm()
  230. to, err := o.Begin()
  231. if err != nil {
  232. return
  233. }
  234. defer func() {
  235. if err != nil {
  236. _ = to.Rollback()
  237. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  238. } else {
  239. _ = to.Commit()
  240. }
  241. }()
  242. // 计算数据
  243. latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo.SubSource, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  244. return
  245. }
  246. // GetSource 获取来源编码id
  247. func (obj PredictLjzNczj) GetSource() int {
  248. return utils.DATA_SOURCE_PREDICT_CALCULATE_LJZNCZJ
  249. }
  250. // GetSourceName 获取来源名称
  251. func (obj PredictLjzNczj) GetSourceName() string {
  252. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_LJZNCZJ
  253. }
  254. func (obj PredictLjzNczj) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  255. dataTableName := GetEdbDataTableName(source, subSource)
  256. edbInfoIdStr := strconv.Itoa(edbInfoId)
  257. var isWeekData bool // 是否周度数据,如果是周度数据的话,是需要变频的,最后结果还需要除以7
  258. // 周度数据需要先变成日度的
  259. if fromEdbInfo.Frequency == `周度` {
  260. isWeekData = true
  261. }
  262. dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  263. if err != nil {
  264. return
  265. }
  266. fromEdbDataMap := make(map[string]float64)
  267. if isWeekData {
  268. dataList, err = HandleDataByLinearRegression(dataList, fromEdbDataMap)
  269. if err != nil {
  270. return
  271. }
  272. }
  273. //日度数据年初至今:日期同原日度数据。将每年1月1日(含)到日度数据所在日期含间的日度值,进行加总。
  274. //周度数据年初至今:日期同原周度数据。将周度值转成日度频率,空值用插值法插值,然后算法同日度年度至今,再除以7
  275. //月度/季度数据年初至今:日期同原月度/季度数据,将每年1月1日(含)到月度数据所在日期(含)之间的月度/季度值,进行加总
  276. //以此类推
  277. dateList := make([]time.Time, 0)
  278. valueMap := make(map[time.Time]float64)
  279. yearMap := make(map[int]float64)
  280. switch edbInfo.Frequency {
  281. case "周度":
  282. tmpDateDataMap := make(map[time.Time]float64)
  283. tmpDateList := make([]time.Time, 0)
  284. for _, item := range dataList {
  285. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  286. if tmpErr != nil {
  287. err = tmpErr
  288. return
  289. }
  290. var currTime time.Time
  291. // 周六周日,这是下一个周五的数据
  292. if itemDate.Weekday() == 0 {
  293. currTime = itemDate.AddDate(0, 0, 5)
  294. } else if itemDate.Weekday() == 6 {
  295. currTime = itemDate.AddDate(0, 0, 6)
  296. } else {
  297. currTime = itemDate.AddDate(0, 0, 5-int(itemDate.Weekday()))
  298. }
  299. year := itemDate.Year()
  300. yearVal, ok := yearMap[year]
  301. if ok {
  302. yearMap[year] = item.Value + yearVal
  303. } else {
  304. yearMap[year] = item.Value
  305. }
  306. if itemDate.Equal(currTime) {
  307. tmpDateDataMap[itemDate] = yearMap[year]
  308. tmpDateList = append(tmpDateList, itemDate)
  309. }
  310. }
  311. for _, currTime := range tmpDateList {
  312. dateList = append(dateList, currTime)
  313. valueMap[currTime] = tmpDateDataMap[currTime]
  314. }
  315. default:
  316. for _, item := range dataList {
  317. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  318. if tmpErr != nil {
  319. err = tmpErr
  320. return
  321. }
  322. year := itemDate.Year()
  323. yearVal, ok := yearMap[year]
  324. if ok {
  325. yearMap[year] = item.Value + yearVal
  326. } else {
  327. yearMap[year] = item.Value
  328. }
  329. valueMap[itemDate] = yearMap[year]
  330. dateList = append(dateList, itemDate)
  331. }
  332. }
  333. //获取指标所有数据
  334. existDataList := make([]*EdbData, 0)
  335. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  336. sql = fmt.Sprintf(sql, dataTableName)
  337. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  338. if err != nil {
  339. return
  340. }
  341. existDataMap := make(map[string]string)
  342. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  343. for _, v := range existDataList {
  344. existDataMap[v.DataTime] = v.Value
  345. removeDataTimeMap[v.DataTime] = 1
  346. }
  347. needAddDateMap := make(map[time.Time]int)
  348. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  349. var isAdd bool
  350. for _, currTime := range dateList {
  351. currDateStr := currTime.Format(utils.FormatDate)
  352. existVal, ok := existDataMap[currDateStr]
  353. tmpVal, ok2 := valueMap[currTime]
  354. if !ok2 {
  355. err = errors.New("数据异常,date:" + currDateStr)
  356. return
  357. }
  358. var saveValue string
  359. if isWeekData { //周度指标转的话,最后结果要除以7
  360. saveValue = decimal.NewFromFloat(tmpVal).Div(decimal.NewFromInt(7)).Round(4).String()
  361. } else {
  362. saveValue = decimal.NewFromFloat(tmpVal).Round(4).String()
  363. }
  364. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  365. if ok {
  366. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  367. delete(removeDataTimeMap, currDateStr)
  368. if existVal != saveValue {
  369. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  370. sql = fmt.Sprintf(sql, dataTableName)
  371. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  372. if err != nil {
  373. return
  374. }
  375. }
  376. continue
  377. }
  378. // 库中不存在该日期的数据
  379. timestamp := currTime.UnixNano() / 1e6
  380. timeStr := fmt.Sprintf("%d", timestamp)
  381. if _, existOk := needAddDateMap[currTime]; !existOk {
  382. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  383. isAdd = true
  384. }
  385. needAddDateMap[currTime] = 1
  386. }
  387. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  388. {
  389. removeDateList := make([]string, 0)
  390. for dateTime := range removeDataTimeMap {
  391. removeDateList = append(removeDateList, dateTime)
  392. }
  393. removeNum := len(removeDateList)
  394. if removeNum > 0 {
  395. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  396. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  397. if err != nil {
  398. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  399. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  400. return
  401. }
  402. }
  403. }
  404. if isAdd {
  405. addSql = strings.TrimRight(addSql, ",")
  406. _, err = to.Raw(addSql).Exec()
  407. if err != nil {
  408. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  409. return
  410. }
  411. }
  412. //确定实际数据的最终值
  413. {
  414. var finalLast EdbInfoSearchData
  415. sql = fmt.Sprintf(` SELECT data_time , value FROM %s WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `, dataTableName)
  416. err = to.Raw(sql, edbInfoId, fromEdbInfo.LatestDate).QueryRow(&finalLast)
  417. if err != nil && err.Error() != utils.ErrNoRow() {
  418. return
  419. } else {
  420. latestDateStr = finalLast.DataTime
  421. latestValue = finalLast.Value
  422. }
  423. if err != nil {
  424. err = nil
  425. } else {
  426. latestDateStr = finalLast.DataTime
  427. latestValue = finalLast.Value
  428. }
  429. }
  430. return
  431. }