predict_edb_data_calculate_standard_deviation.go 12 KB

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