predict_edb_data_calculate_standard_deviation.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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: GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE),
  56. MoveType: 0,
  57. MoveFrequency: "",
  58. NoUpdate: 0,
  59. ServerUrl: "",
  60. EdbInfoType: 1,
  61. EdbNameEn: req.EdbName,
  62. UnitEn: req.Unit,
  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. 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.CalculateFormula = req.Formula
  147. edbInfo.ModifyTime = time.Now()
  148. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  149. if err != nil {
  150. return
  151. }
  152. var existCondition string
  153. var existPars []interface{}
  154. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  155. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  156. //判断计算指标是否被更换
  157. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  158. if err != nil {
  159. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  160. return
  161. }
  162. if count > 0 { // 指标未被替换,无需删除关联数据
  163. // 频度被换了,需要重新计算
  164. if isRecalculate {
  165. latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  166. }
  167. return
  168. }
  169. //删除,计算指标关联的,基础指标的关联关系
  170. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  171. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  172. if err != nil {
  173. return
  174. }
  175. //清空原有数据
  176. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  177. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  178. if err != nil {
  179. return
  180. }
  181. //关联关系
  182. {
  183. calculateMappingItem := &EdbInfoCalculateMapping{
  184. EdbInfoCalculateMappingId: 0,
  185. EdbInfoId: edbInfo.EdbInfoId,
  186. Source: obj.GetSource(),
  187. SourceName: obj.GetSourceName(),
  188. EdbCode: edbInfo.EdbCode,
  189. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  190. FromEdbCode: fromEdbInfo.EdbCode,
  191. FromEdbName: fromEdbInfo.EdbName,
  192. FromSource: fromEdbInfo.Source,
  193. FromSourceName: fromEdbInfo.SourceName,
  194. FromTag: "",
  195. Sort: 1,
  196. CreateTime: time.Now(),
  197. ModifyTime: time.Now(),
  198. }
  199. _, err = to.Insert(calculateMappingItem)
  200. if err != nil {
  201. return
  202. }
  203. }
  204. //计算数据
  205. latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  206. return
  207. }
  208. // Refresh 刷新
  209. func (obj PredictStandardDeviation) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  210. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  211. if err != nil {
  212. return
  213. }
  214. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  215. if err != nil {
  216. errMsg = "GetEdbInfoById Err:" + err.Error()
  217. return
  218. }
  219. o := orm.NewOrm()
  220. to, err := o.Begin()
  221. if err != nil {
  222. return
  223. }
  224. defer func() {
  225. if err != nil {
  226. _ = to.Rollback()
  227. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  228. } else {
  229. _ = to.Commit()
  230. }
  231. }()
  232. // 计算数据
  233. latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  234. return
  235. }
  236. // GetSource 获取来源编码id
  237. func (obj PredictStandardDeviation) GetSource() int {
  238. return utils.DATA_SOURCE_PREDICT_CALCULATE_STANDARD_DEVIATION
  239. }
  240. // GetSourceName 获取来源名称
  241. func (obj PredictStandardDeviation) GetSourceName() string {
  242. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_STANDARD_DEVIATION
  243. }
  244. func (obj PredictStandardDeviation) refresh(to orm.TxOrmer, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  245. edbInfoId := edbInfo.EdbInfoId
  246. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  247. edbInfoIdStr := strconv.Itoa(edbInfoId)
  248. latestDateStr = fromEdbInfo.LatestDate
  249. calculateValue, err := strconv.Atoi(edbInfo.CalculateFormula)
  250. if err != nil {
  251. return
  252. }
  253. // 获取标准差图表的指标数据
  254. fromDataList, err := obj.getStandardDeviationData(fromEdbInfo, calculateValue)
  255. if err != nil {
  256. return
  257. }
  258. //获取指标所有数据
  259. existDataList := make([]*EdbData, 0)
  260. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  261. sql = fmt.Sprintf(sql, dataTableName)
  262. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  263. if err != nil {
  264. return
  265. }
  266. existDataMap := make(map[string]string)
  267. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  268. for _, v := range existDataList {
  269. existDataMap[v.DataTime] = v.Value
  270. removeDataTimeMap[v.DataTime] = 1
  271. }
  272. needAddDateMap := make(map[time.Time]int)
  273. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  274. var isAdd bool
  275. for _, tmpData := range fromDataList {
  276. currDateStr := tmpData.DataTime
  277. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  278. if tmpErr != nil {
  279. err = tmpErr
  280. return
  281. }
  282. // 当前的实际值
  283. saveValue := decimal.NewFromFloat(tmpData.Value).Round(4).String()
  284. existVal, ok := existDataMap[currDateStr]
  285. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  286. if ok {
  287. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  288. delete(removeDataTimeMap, currDateStr)
  289. if existVal != saveValue {
  290. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  291. sql = fmt.Sprintf(sql, dataTableName)
  292. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  293. if err != nil {
  294. return
  295. }
  296. }
  297. continue
  298. }
  299. // 库中不存在该日期的数据
  300. timestamp := currTime.UnixNano() / 1e6
  301. timeStr := fmt.Sprintf("%d", timestamp)
  302. if _, existOk := needAddDateMap[currTime]; !existOk {
  303. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  304. isAdd = true
  305. }
  306. needAddDateMap[currTime] = 1
  307. }
  308. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  309. {
  310. removeDateList := make([]string, 0)
  311. for dateTime := range removeDataTimeMap {
  312. removeDateList = append(removeDateList, dateTime)
  313. }
  314. removeNum := len(removeDateList)
  315. if removeNum > 0 {
  316. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  317. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  318. if err != nil {
  319. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  320. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  321. return
  322. }
  323. }
  324. }
  325. if isAdd {
  326. addSql = strings.TrimRight(addSql, ",")
  327. _, err = to.Raw(addSql).Exec()
  328. if err != nil {
  329. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  330. return
  331. }
  332. }
  333. //确定实际数据的最终值
  334. {
  335. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
  336. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  337. return
  338. }
  339. if tmpErr == nil {
  340. latestDateStr = finalLast.DataTime
  341. latestValue = finalLast.Value
  342. }
  343. }
  344. return
  345. }
  346. // GetStandardDeviationData 获取标准差图表的指标数据
  347. func (obj PredictStandardDeviation) getStandardDeviationData(fromEdbInfo *EdbInfo, calculateValue int) (newDataList []EdbInfoSearchData, err error) {
  348. // 获取时间基准指标在时间区间内的值
  349. dataList := make([]*EdbInfoSearchData, 0)
  350. switch fromEdbInfo.EdbInfoType {
  351. case 0:
  352. //获取来源指标的数据
  353. dataList, err = GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  354. EdbInfoId: fromEdbInfo.EdbInfoId,
  355. }, 1)
  356. case 1:
  357. dataList, err = GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, "")
  358. default:
  359. err = errors.New(fmt.Sprint("获取失败,指标base类型异常", fromEdbInfo.EdbInfoType))
  360. return
  361. }
  362. // 指标对应的所有数据
  363. newDataList = make([]EdbInfoSearchData, 0)
  364. lenData := len(dataList)
  365. if lenData >= calculateValue {
  366. tmpDataList := make([]float64, 0)
  367. for _, tmpData := range dataList {
  368. tmpDataList = append(tmpDataList, tmpData.Value)
  369. }
  370. for i := calculateValue; i <= lenData; i++ {
  371. tmpV := utils.CalculateStandardDeviation(tmpDataList[i-calculateValue : i])
  372. newDataList = append(newDataList, EdbInfoSearchData{
  373. EdbDataId: i,
  374. DataTime: dataList[i-1].DataTime,
  375. Value: tmpV,
  376. })
  377. }
  378. }
  379. return
  380. }