predict_edb_data_calculate_ljznczj.go 14 KB

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