edb_data_calculate_zsxy.go 11 KB

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