predict_edb_data_calculate_ljznczj.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  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: 0,
  66. MoveType: 0,
  67. MoveFrequency: "",
  68. NoUpdate: 0,
  69. ServerUrl: "",
  70. EdbInfoType: 1,
  71. EdbNameEn: "",
  72. UnitEn: "",
  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, 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)
  140. var isRecalculate bool
  141. if edbInfo.Frequency != req.Frequency {
  142. isRecalculate = true
  143. }
  144. //修改指标信息
  145. edbInfo.EdbName = req.EdbName
  146. edbInfo.EdbNameSource = req.EdbName
  147. edbInfo.Frequency = req.Frequency
  148. edbInfo.Unit = req.Unit
  149. edbInfo.ClassifyId = req.ClassifyId
  150. edbInfo.ModifyTime = time.Now()
  151. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  152. if err != nil {
  153. return
  154. }
  155. var existCondition string
  156. var existPars []interface{}
  157. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  158. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  159. //判断计算指标是否被更换
  160. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  161. if err != nil {
  162. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  163. return
  164. }
  165. if count > 0 { // 指标未被替换,无需删除关联数据
  166. // 频度被换了,需要重新计算
  167. if isRecalculate {
  168. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  169. }
  170. return
  171. }
  172. //删除,计算指标关联的,基础指标的关联关系
  173. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  174. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  175. if err != nil {
  176. return
  177. }
  178. //清空原有数据
  179. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  180. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  181. if err != nil {
  182. return
  183. }
  184. //关联关系
  185. {
  186. calculateMappingItem := &EdbInfoCalculateMapping{
  187. EdbInfoCalculateMappingId: 0,
  188. EdbInfoId: edbInfo.EdbInfoId,
  189. Source: obj.GetSource(),
  190. SourceName: obj.GetSourceName(),
  191. EdbCode: edbInfo.EdbCode,
  192. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  193. FromEdbCode: fromEdbInfo.EdbCode,
  194. FromEdbName: fromEdbInfo.EdbName,
  195. FromSource: fromEdbInfo.Source,
  196. FromSourceName: fromEdbInfo.SourceName,
  197. FromTag: "",
  198. Sort: 1,
  199. CreateTime: time.Now(),
  200. ModifyTime: time.Now(),
  201. }
  202. _, err = to.Insert(calculateMappingItem)
  203. if err != nil {
  204. return
  205. }
  206. }
  207. //计算数据
  208. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  209. return
  210. }
  211. // Refresh 刷新
  212. func (obj PredictLjzNczj) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  213. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  214. if err != nil {
  215. errMsg = "GetEdbInfoCalculatePredictLjzNczjzyDetail Err:" + err.Error()
  216. return
  217. }
  218. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  219. if err != nil {
  220. errMsg = "GetEdbInfoById Err:" + err.Error()
  221. return
  222. }
  223. o := orm.NewOrm()
  224. to, err := o.Begin()
  225. if err != nil {
  226. return
  227. }
  228. defer func() {
  229. if err != nil {
  230. _ = to.Rollback()
  231. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  232. } else {
  233. _ = to.Commit()
  234. }
  235. }()
  236. // 计算数据
  237. latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  238. return
  239. }
  240. // GetSource 获取来源编码id
  241. func (obj PredictLjzNczj) GetSource() int {
  242. return utils.DATA_SOURCE_PREDICT_CALCULATE_LJZNCZJ
  243. }
  244. // GetSourceName 获取来源名称
  245. func (obj PredictLjzNczj) GetSourceName() string {
  246. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_LJZNCZJ
  247. }
  248. func (obj PredictLjzNczj) refresh(to orm.TxOrmer, edbInfoId, source int, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  249. dataTableName := GetEdbDataTableName(source)
  250. edbInfoIdStr := strconv.Itoa(edbInfoId)
  251. var isWeekData bool // 是否周度数据,如果是周度数据的话,是需要变频的,最后结果还需要除以7
  252. // 周度数据需要先变成日度的
  253. if fromEdbInfo.Frequency == `周度` {
  254. isWeekData = true
  255. }
  256. dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  257. if err != nil {
  258. return
  259. }
  260. fromEdbDataMap := make(map[string]float64)
  261. if isWeekData {
  262. dataList, err = HandleDataByLinearRegression(dataList, fromEdbDataMap)
  263. if err != nil {
  264. return
  265. }
  266. }
  267. //日度数据年初至今:日期同原日度数据。将每年1月1日(含)到日度数据所在日期含间的日度值,进行加总。
  268. //周度数据年初至今:日期同原周度数据。将周度值转成日度频率,空值用插值法插值,然后算法同日度年度至今,再除以7
  269. //月度/季度数据年初至今:日期同原月度/季度数据,将每年1月1日(含)到月度数据所在日期(含)之间的月度/季度值,进行加总
  270. //以此类推
  271. dateList := make([]time.Time, 0)
  272. valueMap := make(map[time.Time]float64)
  273. yearMap := make(map[int]float64)
  274. switch edbInfo.Frequency {
  275. case "周度":
  276. tmpDateDataMap := make(map[time.Time]float64)
  277. tmpDateList := make([]time.Time, 0)
  278. for _, item := range dataList {
  279. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  280. if tmpErr != nil {
  281. err = tmpErr
  282. return
  283. }
  284. var currTime time.Time
  285. // 周六周日,这是下一个周五的数据
  286. if itemDate.Weekday() == 0 {
  287. currTime = itemDate.AddDate(0, 0, 5)
  288. } else if itemDate.Weekday() == 6 {
  289. currTime = itemDate.AddDate(0, 0, 6)
  290. } else {
  291. currTime = itemDate.AddDate(0, 0, 5-int(itemDate.Weekday()))
  292. }
  293. year := itemDate.Year()
  294. yearVal, ok := yearMap[year]
  295. if ok {
  296. yearMap[year] = item.Value + yearVal
  297. } else {
  298. yearMap[year] = item.Value
  299. }
  300. if itemDate.Equal(currTime) {
  301. tmpDateDataMap[itemDate] = yearMap[year]
  302. tmpDateList = append(tmpDateList, itemDate)
  303. }
  304. }
  305. for _, currTime := range tmpDateList {
  306. dateList = append(dateList, currTime)
  307. valueMap[currTime] = tmpDateDataMap[currTime]
  308. }
  309. default:
  310. for _, item := range dataList {
  311. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  312. if tmpErr != nil {
  313. err = tmpErr
  314. return
  315. }
  316. year := itemDate.Year()
  317. yearVal, ok := yearMap[year]
  318. if ok {
  319. yearMap[year] = item.Value + yearVal
  320. } else {
  321. yearMap[year] = item.Value
  322. }
  323. valueMap[itemDate] = yearMap[year]
  324. dateList = append(dateList, itemDate)
  325. }
  326. }
  327. //获取指标所有数据
  328. existDataList := make([]*EdbData, 0)
  329. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  330. sql = fmt.Sprintf(sql, dataTableName)
  331. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  332. if err != nil {
  333. return
  334. }
  335. existDataMap := make(map[string]string)
  336. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  337. for _, v := range existDataList {
  338. existDataMap[v.DataTime] = v.Value
  339. removeDataTimeMap[v.DataTime] = 1
  340. }
  341. needAddDateMap := make(map[time.Time]int)
  342. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  343. var isAdd bool
  344. for _, currTime := range dateList {
  345. currDateStr := currTime.Format(utils.FormatDate)
  346. existVal, ok := existDataMap[currDateStr]
  347. tmpVal, ok2 := valueMap[currTime]
  348. if !ok2 {
  349. err = errors.New("数据异常,date:" + currDateStr)
  350. return
  351. }
  352. var saveValue string
  353. if isWeekData { //周度指标转的话,最后结果要除以7
  354. saveValue = decimal.NewFromFloat(tmpVal).Div(decimal.NewFromInt(7)).Round(4).String()
  355. } else {
  356. saveValue = decimal.NewFromFloat(tmpVal).Round(4).String()
  357. }
  358. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  359. if ok {
  360. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  361. delete(removeDataTimeMap, currDateStr)
  362. if existVal != saveValue {
  363. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  364. sql = fmt.Sprintf(sql, dataTableName)
  365. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  366. if err != nil {
  367. return
  368. }
  369. }
  370. continue
  371. }
  372. // 库中不存在该日期的数据
  373. timestamp := currTime.UnixNano() / 1e6
  374. timeStr := fmt.Sprintf("%d", timestamp)
  375. if _, existOk := needAddDateMap[currTime]; !existOk {
  376. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  377. isAdd = true
  378. }
  379. needAddDateMap[currTime] = 1
  380. }
  381. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  382. {
  383. removeDateList := make([]string, 0)
  384. for dateTime := range removeDataTimeMap {
  385. removeDateList = append(removeDateList, dateTime)
  386. }
  387. removeNum := len(removeDateList)
  388. if removeNum > 0 {
  389. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  390. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  391. if err != nil {
  392. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  393. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  394. return
  395. }
  396. }
  397. }
  398. if isAdd {
  399. addSql = strings.TrimRight(addSql, ",")
  400. _, err = to.Raw(addSql).Exec()
  401. if err != nil {
  402. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  403. return
  404. }
  405. }
  406. //确定实际数据的最终值
  407. {
  408. var finalLast EdbInfoSearchData
  409. sql = fmt.Sprintf(` SELECT data_time , value FROM %s WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `, dataTableName)
  410. err = to.Raw(sql, edbInfoId, fromEdbInfo.LatestDate).QueryRow(&finalLast)
  411. if err != nil && err.Error() != utils.ErrNoRow() {
  412. return
  413. } else {
  414. latestDateStr = finalLast.DataTime
  415. latestValue = finalLast.Value
  416. }
  417. if err != nil {
  418. err = nil
  419. } else {
  420. latestDateStr = finalLast.DataTime
  421. latestValue = finalLast.Value
  422. }
  423. }
  424. return
  425. }