predict_edb_data_base.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. // PredictStandardBase 基础预测指标
  14. type PredictStandardBase struct {
  15. }
  16. // AddPredictEdb 添加预测指标
  17. // edbInfo, calculateMappingList, predictEdbConfList,calculateRule9List,trendsMappingList
  18. func AddPredictEdb(item *EdbInfo, calculateMappingList []*EdbInfoCalculateMapping, predictEdbConfList []*PredictEdbConf, calculateRuleMap map[int]CalculateRule) (err error, errMsg string) {
  19. var latestDateStr string
  20. var latestValue float64
  21. o := orm.NewOrm()
  22. tx, err := o.Begin()
  23. if err != nil {
  24. return
  25. }
  26. defer func() {
  27. if err != nil {
  28. tx.Rollback()
  29. } else {
  30. err = tx.Commit()
  31. // 更新指标最大最小值
  32. go UnifiedModifyPredictEdbInfoMaxAndMinInfo(item, latestDateStr, latestValue)
  33. }
  34. }()
  35. // 新增预测指标
  36. edbInfoId, err := tx.Insert(item)
  37. if err != nil {
  38. return
  39. }
  40. item.EdbInfoId = int(edbInfoId)
  41. // 新增预测指标的关联关系
  42. lenCalculateMapping := len(calculateMappingList)
  43. if lenCalculateMapping > 0 {
  44. for _, calculateMappingItem := range calculateMappingList {
  45. calculateMappingItem.EdbInfoId = item.EdbInfoId
  46. calculateMappingItem.EdbCode = item.EdbCode
  47. }
  48. _, err = tx.InsertMulti(lenCalculateMapping, calculateMappingList)
  49. if err != nil {
  50. return
  51. }
  52. }
  53. predictEdbConfAndDataList := make([]*PredictEdbConfAndData, 0)
  54. // 新增预测指标配置
  55. for k, v := range predictEdbConfList {
  56. v.PredictEdbInfoId = item.EdbInfoId
  57. configId, tmpErr := tx.Insert(v)
  58. if tmpErr != nil {
  59. err = tmpErr
  60. return
  61. }
  62. v.ConfigId = int(configId)
  63. // 每次规则计算的时候,产生的临时数据
  64. resultDataList := make([]*EdbInfoSearchData, 0)
  65. switch v.RuleType {
  66. case 9: //动态环差规则
  67. calculateRule := calculateRuleMap[k]
  68. calculateRule.ConfigId = v.ConfigId
  69. calculateRule.EdbInfoId = v.PredictEdbInfoId
  70. // 指标与规则的动态数据生成入库
  71. resultDataList, err = CalculateByRuleBy9(tx, calculateRule)
  72. if err != nil {
  73. return
  74. }
  75. // 规则与指标的关系入库
  76. lenTrendsCalculateMapping := len(calculateRule.TrendsCalculateMappingList)
  77. if lenTrendsCalculateMapping > 0 {
  78. for _, vv := range calculateRule.TrendsCalculateMappingList {
  79. vv.EdbInfoId = item.EdbInfoId
  80. vv.ConfigId = v.ConfigId
  81. }
  82. _, err = tx.InsertMulti(lenTrendsCalculateMapping, calculateRule.TrendsCalculateMappingList)
  83. if err != nil {
  84. return
  85. }
  86. }
  87. case 14: //14:根据 一元线性拟合 规则获取预测数据
  88. calculateRule := calculateRuleMap[k]
  89. calculateRule.ConfigId = v.ConfigId
  90. calculateRule.EdbInfoId = v.PredictEdbInfoId
  91. // 指标与规则的动态数据(拟合数据)生成入库
  92. err, errMsg = CalculateByRuleByRuleLineNh(tx, *item, predictEdbConfAndDataList, *v)
  93. if err != nil {
  94. return
  95. }
  96. // 规则与指标的关系入库
  97. lenTrendsCalculateMapping := len(calculateRule.TrendsCalculateMappingList)
  98. if lenTrendsCalculateMapping > 0 {
  99. for _, vv := range calculateRule.TrendsCalculateMappingList {
  100. vv.EdbInfoId = item.EdbInfoId
  101. vv.ConfigId = v.ConfigId
  102. }
  103. _, err = tx.InsertMulti(lenTrendsCalculateMapping, calculateRule.TrendsCalculateMappingList)
  104. if err != nil {
  105. return
  106. }
  107. }
  108. }
  109. // 规则配置(含数据)
  110. tmpPredictEdbConfAndData := &PredictEdbConfAndData{
  111. ConfigId: 0,
  112. PredictEdbInfoId: 0,
  113. SourceEdbInfoId: v.SourceEdbInfoId,
  114. RuleType: v.RuleType,
  115. FixedValue: v.FixedValue,
  116. Value: v.Value,
  117. EndDate: v.EndDate,
  118. ModifyTime: v.ModifyTime,
  119. CreateTime: v.CreateTime,
  120. DataList: resultDataList,
  121. }
  122. predictEdbConfAndDataList = append(predictEdbConfAndDataList, tmpPredictEdbConfAndData)
  123. }
  124. // 重新预测数据
  125. obj := new(PredictStandardBase)
  126. latestDateStr, latestValue, err, errMsg = obj.refresh(tx, item, predictEdbConfAndDataList, item.EdbCode, "")
  127. return
  128. }
  129. // EditPredictEdb 修改预测指标
  130. func EditPredictEdb(edbInfo *EdbInfo, updateEdbInfoCol []string, calculateMappingList []*EdbInfoCalculateMapping, predictEdbConfList []*PredictEdbConf, calculateRuleMap map[int]CalculateRule) (err error, errMsg string) {
  131. var latestDateStr string
  132. var latestValue float64
  133. o := orm.NewOrm()
  134. tx, err := o.Begin()
  135. if err != nil {
  136. return
  137. }
  138. defer func() {
  139. if err != nil {
  140. tx.Rollback()
  141. } else {
  142. err = tx.Commit()
  143. // 更新指标最大最小值
  144. go UnifiedModifyPredictEdbInfoMaxAndMinInfo(edbInfo, latestDateStr, latestValue)
  145. }
  146. }()
  147. // 修改预测指标
  148. _, err = tx.Update(edbInfo, updateEdbInfoCol...)
  149. if err != nil {
  150. return
  151. }
  152. // 先删除原有的预测指标 与 其他指标的 关联关系
  153. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ?`
  154. _, err = tx.Raw(sql, edbInfo.EdbInfoId).Exec()
  155. if err != nil {
  156. return
  157. }
  158. // 先删除原有的配置
  159. sql = ` DELETE FROM predict_edb_conf WHERE predict_edb_info_id = ?`
  160. _, err = tx.Raw(sql, edbInfo.EdbInfoId).Exec()
  161. if err != nil {
  162. return
  163. }
  164. // 删除基础预测指标 规则配置 与 其他指标的 关联关系
  165. sql = ` DELETE FROM predict_edb_conf_calculate_mapping WHERE edb_info_id = ?`
  166. _, err = tx.Raw(sql, edbInfo.EdbInfoId).Exec()
  167. if err != nil {
  168. return
  169. }
  170. // 删除基础预测指标 规则配置 生成的动态数据值
  171. sql = ` DELETE FROM predict_edb_rule_data WHERE edb_info_id = ?`
  172. _, err = tx.Raw(sql, edbInfo.EdbInfoId).Exec()
  173. if err != nil {
  174. return
  175. }
  176. // 新增预测指标的关联关系
  177. lenCalculateMapping := len(calculateMappingList)
  178. if lenCalculateMapping > 0 {
  179. for _, calculateMappingItem := range calculateMappingList {
  180. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  181. calculateMappingItem.EdbCode = edbInfo.EdbCode
  182. }
  183. _, err = tx.InsertMulti(lenCalculateMapping, calculateMappingList)
  184. if err != nil {
  185. return
  186. }
  187. }
  188. calculateRuleIndex := 0 // 预测计算规则下标
  189. predictEdbConfAndDataList := make([]*PredictEdbConfAndData, 0)
  190. // 新增预测指标配置
  191. for confIndex, v := range predictEdbConfList {
  192. configId, tmpErr := tx.Insert(v)
  193. if tmpErr != nil {
  194. err = tmpErr
  195. return
  196. }
  197. v.ConfigId = int(configId)
  198. // 每次规则计算的时候,产生的临时数据
  199. resultDataList := make([]*EdbInfoSearchData, 0)
  200. switch v.RuleType {
  201. case 9: //动态环差规则
  202. calculateRule := calculateRuleMap[confIndex]
  203. calculateRule.ConfigId = v.ConfigId
  204. calculateRule.EdbInfoId = v.PredictEdbInfoId
  205. // 指标与规则的动态数据生成入库
  206. resultDataList, err = CalculateByRuleBy9(tx, calculateRule)
  207. if err != nil {
  208. return
  209. }
  210. // 规则与指标的关系入库
  211. lenTrendsCalculateMapping := len(calculateRule.TrendsCalculateMappingList)
  212. if lenTrendsCalculateMapping > 0 {
  213. for _, vv := range calculateRule.TrendsCalculateMappingList {
  214. vv.EdbInfoId = edbInfo.EdbInfoId
  215. vv.ConfigId = v.ConfigId
  216. }
  217. _, err = tx.InsertMulti(lenTrendsCalculateMapping, calculateRule.TrendsCalculateMappingList)
  218. if err != nil {
  219. return
  220. }
  221. }
  222. case 14: //14:根据 一元线性拟合 规则获取预测数据
  223. calculateRule := calculateRuleMap[confIndex]
  224. calculateRule.ConfigId = v.ConfigId
  225. calculateRule.EdbInfoId = v.PredictEdbInfoId
  226. // 指标与规则的动态数据(拟合数据)生成入库
  227. err, errMsg = CalculateByRuleByRuleLineNh(tx, *edbInfo, predictEdbConfAndDataList, *v)
  228. if err != nil {
  229. return
  230. }
  231. // 规则与指标的关系入库
  232. lenTrendsCalculateMapping := len(calculateRule.TrendsCalculateMappingList)
  233. if lenTrendsCalculateMapping > 0 {
  234. for _, vv := range calculateRule.TrendsCalculateMappingList {
  235. vv.EdbInfoId = edbInfo.EdbInfoId
  236. vv.ConfigId = v.ConfigId
  237. }
  238. _, err = tx.InsertMulti(lenTrendsCalculateMapping, calculateRule.TrendsCalculateMappingList)
  239. if err != nil {
  240. return
  241. }
  242. }
  243. }
  244. calculateRuleIndex++
  245. // 规则配置(含数据)
  246. tmpPredictEdbConfAndData := &PredictEdbConfAndData{
  247. ConfigId: 0,
  248. PredictEdbInfoId: 0,
  249. SourceEdbInfoId: v.SourceEdbInfoId,
  250. RuleType: v.RuleType,
  251. FixedValue: v.FixedValue,
  252. Value: v.Value,
  253. EndDate: v.EndDate,
  254. ModifyTime: v.ModifyTime,
  255. CreateTime: v.CreateTime,
  256. DataList: resultDataList,
  257. }
  258. predictEdbConfAndDataList = append(predictEdbConfAndDataList, tmpPredictEdbConfAndData)
  259. }
  260. // 重新预测数据
  261. obj := new(PredictStandardBase)
  262. latestDateStr, latestValue, err, errMsg = obj.refresh(tx, edbInfo, predictEdbConfAndDataList, edbInfo.EdbCode, "")
  263. return
  264. }
  265. // Add 添加
  266. func (obj PredictStandardBase) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  267. err = errors.New("暂不支持该方法")
  268. return
  269. }
  270. // Edit 编辑
  271. func (obj PredictStandardBase) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  272. err = errors.New("暂不支持该方法")
  273. return
  274. }
  275. // Refresh 刷新
  276. func (obj PredictStandardBase) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  277. edbInfo := params.EdbInfo
  278. if edbInfo == nil {
  279. errMsg = `错误的指标`
  280. err = errors.New(errMsg)
  281. return
  282. }
  283. // 查找该预测指标配置
  284. predictEdbConfList, err := GetPredictEdbConfAndDataListById(edbInfo.EdbInfoId)
  285. if err != nil && err.Error() != utils.ErrNoRow() {
  286. errMsg = "获取预测指标配置信息失败"
  287. return
  288. }
  289. if len(predictEdbConfList) == 0 {
  290. errMsg = "获取预测指标配置信息失败"
  291. err = errors.New(errMsg)
  292. return
  293. }
  294. o := orm.NewOrm()
  295. to, err := o.Begin()
  296. if err != nil {
  297. return
  298. }
  299. defer func() {
  300. if err != nil {
  301. _ = to.Rollback()
  302. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  303. } else {
  304. _ = to.Commit()
  305. }
  306. }()
  307. // 重新预测数据
  308. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo, predictEdbConfList, edbInfo.EdbCode, "")
  309. return
  310. }
  311. // GetSource 获取来源编码id
  312. func (obj PredictStandardBase) GetSource() int {
  313. return utils.DATA_SOURCE_PREDICT
  314. }
  315. // GetSourceName 获取来源名称
  316. func (obj PredictStandardBase) GetSourceName() string {
  317. return utils.DATA_SOURCE_NAME_PREDICT
  318. }
  319. func (obj PredictStandardBase) refresh(to orm.TxOrmer, edbInfo *EdbInfo, predictEdbConfAndDataList []*PredictEdbConfAndData, edbCode, startDate string) (latestDateStr string, latestValue float64, err error, errMsg string) {
  320. edbInfoId := edbInfo.EdbInfoId
  321. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  322. edbInfoIdStr := strconv.Itoa(edbInfoId)
  323. // 获取标准差图表的指标数据
  324. fromDataList, fromEdbInfo, err, errMsg := obj.GetCalculateDataList(edbInfo, predictEdbConfAndDataList, 1, startDate)
  325. if err != nil {
  326. return
  327. }
  328. latestDateStr = fromEdbInfo.LatestDate
  329. //获取指标所有数据
  330. existDataList := make([]*EdbData, 0)
  331. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  332. sql = fmt.Sprintf(sql, dataTableName)
  333. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  334. if err != nil {
  335. return
  336. }
  337. existDataMap := make(map[string]string)
  338. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  339. for _, v := range existDataList {
  340. existDataMap[v.DataTime] = v.Value
  341. removeDataTimeMap[v.DataTime] = 1
  342. }
  343. needAddDateMap := make(map[time.Time]int)
  344. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  345. var isAdd bool
  346. for _, tmpData := range fromDataList {
  347. currDateStr := tmpData.DataTime
  348. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  349. if tmpErr != nil {
  350. err = tmpErr
  351. return
  352. }
  353. // 当前的实际值
  354. saveValue := decimal.NewFromFloat(tmpData.Value).Round(4).String()
  355. existVal, ok := existDataMap[currDateStr]
  356. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  357. if ok {
  358. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  359. delete(removeDataTimeMap, currDateStr)
  360. // 格式化库中的指标数据,并保留4位小数
  361. existValDec, tmpErr := decimal.NewFromString(existVal)
  362. if tmpErr != nil {
  363. err = tmpErr
  364. return
  365. }
  366. existVal = existValDec.Round(4).String()
  367. if existVal != saveValue {
  368. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  369. sql = fmt.Sprintf(sql, dataTableName)
  370. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  371. if err != nil {
  372. return
  373. }
  374. }
  375. continue
  376. }
  377. // 库中不存在该日期的数据
  378. timestamp := currTime.UnixNano() / 1e6
  379. timeStr := fmt.Sprintf("%d", timestamp)
  380. if _, existOk := needAddDateMap[currTime]; !existOk {
  381. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  382. isAdd = true
  383. }
  384. needAddDateMap[currTime] = 1
  385. }
  386. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  387. {
  388. removeDateList := make([]string, 0)
  389. for dateTime := range removeDataTimeMap {
  390. removeDateList = append(removeDateList, dateTime)
  391. }
  392. removeNum := len(removeDateList)
  393. if removeNum > 0 {
  394. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  395. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  396. if err != nil {
  397. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  398. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  399. return
  400. }
  401. }
  402. }
  403. if isAdd {
  404. addSql = strings.TrimRight(addSql, ",")
  405. _, err = to.Raw(addSql).Exec()
  406. if err != nil {
  407. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  408. return
  409. }
  410. }
  411. //确定实际数据的最终值
  412. {
  413. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
  414. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  415. return
  416. }
  417. if tmpErr == nil {
  418. latestDateStr = finalLast.DataTime
  419. latestValue = finalLast.Value
  420. }
  421. }
  422. return
  423. }
  424. // GetCalculateDataList
  425. // @Description: 获取计算后的数据
  426. // @author: Roc
  427. // @receiver obj
  428. // @datetime 2024-04-24 10:42:51
  429. // @param edbInfo *EdbInfo
  430. // @param predictEdbConfList []*PredictEdbConfAndData
  431. // @param order int order:1升序,其余值为降序
  432. // @param startDate string
  433. // @return dataList []*EdbInfoSearchData
  434. // @return sourceEdbInfoItem *EdbInfo
  435. // @return err error
  436. // @return errMsg string
  437. func (obj PredictStandardBase) GetCalculateDataList(edbInfo *EdbInfo, predictEdbConfList []*PredictEdbConfAndData, order int, startDate string) (dataList []*EdbInfoSearchData, sourceEdbInfoItem *EdbInfo, err error, errMsg string) {
  438. if len(predictEdbConfList) == 0 {
  439. errMsg = "获取预测指标配置信息失败"
  440. err = errors.New(errMsg)
  441. return
  442. }
  443. predictEdbConf := predictEdbConfList[0]
  444. // 来源指标
  445. sourceEdbInfoItem, err = GetEdbInfoById(predictEdbConf.SourceEdbInfoId)
  446. if err != nil {
  447. if err.Error() == utils.ErrNoRow() {
  448. errMsg = "找不到来源指标信息"
  449. err = errors.New(errMsg)
  450. }
  451. return
  452. }
  453. dataList, err, errMsg = GetPredictDataListByPredictEdbConfList(edbInfo, sourceEdbInfoItem, predictEdbConfList, order, startDate)
  454. return
  455. }
  456. // RefreshPredictStandardBaseByGeneralEdbInfoId
  457. // @Description: 根据普通指标id刷新预测标准基础数据
  458. // @author: Roc
  459. // @datetime 2024-04-24 13:40:59
  460. // @param sourceEdbInfoId int
  461. // @return err error
  462. func RefreshPredictStandardBaseByGeneralEdbInfoId(sourceEdbInfoId int) {
  463. errList := make([]string, 0)
  464. defer func() {
  465. if len(errList) > 0 {
  466. fmt.Println(errList)
  467. utils.FileLog.Info("RefreshPredictStandardBaseByGeneralEdbInfoId更新失败,来源ID: ErrMsg:" + strings.Join(errList, "\n"))
  468. }
  469. }()
  470. o := orm.NewOrm()
  471. var list []*PredictEdbConf
  472. sql := ` SELECT * FROM predict_edb_conf WHERE source_edb_info_id=? `
  473. total, err := o.Raw(sql, sourceEdbInfoId).QueryRows(&list)
  474. if err != nil {
  475. errList = append(errList, fmt.Sprintf("根据来源换指标id获取配置项失败,来源指标ID:%d;err:%s", sourceEdbInfoId, err.Error()))
  476. return
  477. }
  478. if total > 0 {
  479. idList := make([]int, 0)
  480. for _, v := range list {
  481. idList = append(idList, v.PredictEdbInfoId)
  482. edbInfo, tmpErr := GetEdbInfoById(v.PredictEdbInfoId)
  483. if tmpErr != nil {
  484. errList = append(errList, fmt.Sprintf("获取预测指标配置信息失败,预测指标配置ID:%d;err:%s", v.PredictEdbInfoId, tmpErr.Error()))
  485. continue
  486. }
  487. refreshParams := RefreshParams{
  488. EdbInfo: edbInfo,
  489. }
  490. obj := new(PredictStandardBase)
  491. latestDateStr, latestValue, tmpErr, errMsg := obj.Refresh(refreshParams)
  492. if tmpErr != nil {
  493. errList = append(errList, fmt.Sprintf("更新失败,预测指标配置ID:%d;err:%s;errMsg:%s", v.PredictEdbInfoId, tmpErr.Error(), errMsg))
  494. continue
  495. }
  496. // 更新指标最大最小值
  497. tmpErr, errMsg = UnifiedModifyPredictEdbInfoMaxAndMinInfo(edbInfo, latestDateStr, latestValue)
  498. if tmpErr != nil {
  499. errList = append(errList, fmt.Sprintf("更新指标最大最小值失败,预测指标配置ID:%d;err:%s;errMsg:%s", v.PredictEdbInfoId, tmpErr.Error(), errMsg))
  500. continue
  501. }
  502. }
  503. }
  504. return
  505. }