edb_data_calculate_standard_deviation.go 10 KB

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