predict_edb_data_calculate_zsxy.go 11 KB

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