edb_data_calculate_zsxy.go 11 KB

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