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