edb_data_calculate_standard_deviation.go 11 KB

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