edb_data_calculate_standard_deviation.go 11 KB

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