edb_data_calculate_zsxy.go 11 KB

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