edb_data_calculate_bp.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // AddCalculateBp 升频
  13. func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("AddCalculateBp,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_BP
  30. edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_BP
  31. edbInfo.EdbCode = edbCode
  32. edbInfo.EdbName = req.EdbName
  33. edbInfo.EdbNameSource = req.EdbName
  34. edbInfo.Frequency = req.Frequency
  35. edbInfo.Unit = req.Unit
  36. edbInfo.ClassifyId = req.ClassifyId
  37. edbInfo.SysUserId = sysUserId
  38. edbInfo.SysUserRealName = sysUserRealName
  39. edbInfo.CreateTime = time.Now()
  40. edbInfo.ModifyTime = time.Now()
  41. edbInfo.UniqueCode = uniqueCode
  42. edbInfo.CalculateFormula = req.Formula
  43. edbInfo.EdbNameEn = req.EdbName
  44. edbInfo.UnitEn = req.Unit
  45. edbInfo.EdbType = 2
  46. edbInfo.EmptyType = req.EmptyType
  47. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  48. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  49. if tmpErr != nil {
  50. err = tmpErr
  51. return
  52. }
  53. edbInfo.EdbInfoId = int(newEdbInfoId)
  54. //关联关系
  55. {
  56. calculateMappingItem := new(EdbInfoCalculateMapping)
  57. calculateMappingItem.CreateTime = time.Now()
  58. calculateMappingItem.ModifyTime = time.Now()
  59. calculateMappingItem.Sort = 1
  60. calculateMappingItem.EdbCode = edbCode
  61. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  63. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  64. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  65. calculateMappingItem.FromSource = fromEdbInfo.Source
  66. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  67. calculateMappingItem.FromTag = ""
  68. calculateMappingItem.Source = edbInfo.Source
  69. calculateMappingItem.SourceName = edbInfo.SourceName
  70. calculateMappingItem.FromSubSource = edbInfo.SubSource
  71. _, err = to.Insert(calculateMappingItem)
  72. if err != nil {
  73. return
  74. }
  75. }
  76. } else {
  77. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  78. if err != nil {
  79. return
  80. }
  81. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_BP, utils.DATA_SUB_SOURCE_EDB)
  82. fmt.Println("dataTableName:" + dataTableName)
  83. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  84. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  85. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  86. if err != nil {
  87. return
  88. }
  89. }
  90. //计算数据
  91. err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", 0, edbInfo.EmptyType)
  92. return
  93. }
  94. // EditCalculateBp 修改升频数据
  95. func EditCalculateBp(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  96. o := orm.NewOrm()
  97. to, err := o.Begin()
  98. if err != nil {
  99. return
  100. }
  101. defer func() {
  102. if err != nil {
  103. fmt.Println("EditCalculateBp,Err:" + err.Error())
  104. _ = to.Rollback()
  105. } else {
  106. _ = to.Commit()
  107. }
  108. }()
  109. oldEmptyType := edbInfo.EmptyType
  110. //修改指标信息
  111. edbInfo.EdbName = req.EdbName
  112. edbInfo.EdbNameSource = req.EdbName
  113. edbInfo.Frequency = req.Frequency
  114. edbInfo.Unit = req.Unit
  115. edbInfo.ClassifyId = req.ClassifyId
  116. edbInfo.EdbNameEn = req.EdbNameEn
  117. edbInfo.UnitEn = req.UnitEn
  118. edbInfo.ModifyTime = time.Now()
  119. edbInfo.EmptyType = req.EmptyType
  120. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn", "EmptyType")
  121. if err != nil {
  122. return
  123. }
  124. //判断计算指标是否被更换
  125. var existCondition string
  126. var existPars []interface{}
  127. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  128. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  129. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  130. if err != nil {
  131. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  132. return
  133. }
  134. if count > 0 && oldEmptyType == req.EmptyType { // 指标未被替换,无需重新计算
  135. return
  136. }
  137. //删除,计算指标关联的,基础指标的关联关系
  138. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  139. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  140. if err != nil {
  141. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  142. return
  143. }
  144. //清空原有数据
  145. sql = ` DELETE FROM edb_data_calculate_bp WHERE edb_info_id = ? `
  146. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  147. if err != nil {
  148. return
  149. }
  150. //关联关系
  151. {
  152. calculateMappingItem := &EdbInfoCalculateMapping{
  153. EdbInfoCalculateMappingId: 0,
  154. EdbInfoId: edbInfo.EdbInfoId,
  155. Source: utils.DATA_SOURCE_CALCULATE_BP,
  156. SourceName: utils.DATA_SOURCE_NAME_CALCULATE_BP,
  157. EdbCode: edbInfo.EdbCode,
  158. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  159. FromEdbCode: fromEdbInfo.EdbCode,
  160. FromEdbName: fromEdbInfo.EdbName,
  161. FromSource: fromEdbInfo.Source,
  162. FromSourceName: fromEdbInfo.SourceName,
  163. FromTag: "",
  164. Sort: 1,
  165. CreateTime: time.Now(),
  166. ModifyTime: time.Now(),
  167. FromSubSource: fromEdbInfo.SubSource,
  168. }
  169. _, err = to.Insert(calculateMappingItem)
  170. if err != nil {
  171. return
  172. }
  173. }
  174. //计算数据
  175. err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", 0, edbInfo.EmptyType)
  176. return
  177. }
  178. // RefreshAllCalculateBpBak 刷新所有升频数据
  179. func RefreshAllCalculateBpBak(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  180. o := orm.NewOrm()
  181. to, err := o.Begin()
  182. if err != nil {
  183. return
  184. }
  185. defer func() {
  186. if err != nil {
  187. fmt.Println("RefreshAllCalculateBp,Err:" + err.Error())
  188. _ = to.Rollback()
  189. } else {
  190. _ = to.Commit()
  191. }
  192. }()
  193. if err != nil {
  194. return
  195. }
  196. edbInfoIdStr := strconv.Itoa(edbInfoId)
  197. //计算数据
  198. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  199. EdbInfoId: fromEdbInfo.EdbInfoId,
  200. StartDataTime: startDate,
  201. StartDataTimeCond: ">=",
  202. EndDataTime: endDate,
  203. EndDataTimeCond: "<=",
  204. }, 0)
  205. if err != nil {
  206. return err
  207. }
  208. var dateArr []string
  209. dataMap := make(map[string]*EdbInfoSearchData)
  210. for _, v := range dataList {
  211. dateArr = append(dateArr, v.DataTime)
  212. dataMap[v.DataTime] = v
  213. }
  214. fmt.Println("source:", source)
  215. //获取指标所有数据
  216. existDataList := make([]*EdbData, 0)
  217. dataTableName := GetEdbDataTableName(source, subSource)
  218. fmt.Println("dataTableName:", dataTableName)
  219. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  220. sql = fmt.Sprintf(sql, dataTableName)
  221. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  222. if err != nil {
  223. return err
  224. }
  225. existDataMap := make(map[string]string)
  226. for _, v := range existDataList {
  227. existDataMap[v.DataTime] = v.Value
  228. }
  229. fmt.Println("existDataMap:", existDataMap)
  230. addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  231. var isAdd bool
  232. existMap := make(map[string]string)
  233. dataLen := len(dataList)
  234. for i := 0; i < dataLen; i++ {
  235. //当期
  236. currentItem := dataList[i]
  237. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  238. var day int
  239. var preItem *EdbInfoSearchData
  240. var preDate time.Time
  241. if i == 0 {
  242. day = int(time.Now().Sub(currentDate).Hours() / float64(24))
  243. preDate = time.Now()
  244. } else {
  245. j := i + 1
  246. if j < dataLen {
  247. preItem = dataList[j]
  248. preDate, _ = time.ParseInLocation(utils.FormatDate, preItem.DataTime, time.Local)
  249. day = int(currentDate.Sub(preDate).Hours() / float64(24))
  250. }
  251. }
  252. for k := 0; k <= day; k++ {
  253. needDay := preDate.AddDate(0, 0, -k)
  254. needDayStr := needDay.Format(utils.FormatDate)
  255. existKey := edbCode + needDayStr
  256. if _, ok := existMap[existKey]; !ok {
  257. timestamp := needDay.UnixNano() / 1e6
  258. timestampStr := fmt.Sprintf("%d", timestamp)
  259. valStr := decimal.NewFromFloat(currentItem.Value).String()
  260. if existVal, ok := existDataMap[needDayStr]; !ok {
  261. addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
  262. } else {
  263. if existVal != valStr {
  264. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  265. sql = fmt.Sprintf(sql, dataTableName)
  266. _, err = to.Raw(sql, valStr, edbInfoId, needDay).Exec()
  267. if err != nil {
  268. return err
  269. }
  270. }
  271. }
  272. }
  273. existMap[existKey] = needDayStr
  274. }
  275. existKey := edbCode + currentItem.DataTime
  276. if _, ok := existMap[existKey]; !ok {
  277. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  278. timestamp := currentDate.UnixNano() / 1e6
  279. timestampStr := fmt.Sprintf("%d", timestamp)
  280. valStr := decimal.NewFromFloat(currentItem.Value).String()
  281. if existVal, ok := existDataMap[currentItem.DataTime]; !ok {
  282. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, valStr)
  283. } else {
  284. if existVal != valStr {
  285. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  286. sql = fmt.Sprintf(sql, dataTableName)
  287. _, err = to.Raw(sql, valStr, edbInfoId, currentItem.DataTime).Exec()
  288. if err != nil {
  289. return err
  290. }
  291. }
  292. }
  293. }
  294. existMap[existKey] = currentItem.DataTime
  295. }
  296. if isAdd {
  297. addSql = strings.TrimRight(addSql, ",")
  298. _, err = to.Raw(addSql).Exec()
  299. if err != nil {
  300. return err
  301. }
  302. }
  303. return
  304. }
  305. func RefreshAllCalculateBp(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, emptyType int) (err error) {
  306. o := orm.NewOrm()
  307. to, err := o.Begin()
  308. if err != nil {
  309. return
  310. }
  311. defer func() {
  312. if err != nil {
  313. fmt.Println("RefreshAllCalculateBp,Err:" + err.Error())
  314. _ = to.Rollback()
  315. } else {
  316. _ = to.Commit()
  317. }
  318. }()
  319. // 计算数据
  320. err = refreshAllCalculateBp(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, 0, emptyType)
  321. return
  322. }
  323. // refreshAllCalculateBp 刷新升频数据
  324. func refreshAllCalculateBp(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, order int, emptyType int) (err error) {
  325. edbInfoIdStr := strconv.Itoa(edbInfoId)
  326. //计算数据
  327. //获取来源指标的数据
  328. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  329. EdbInfoId: fromEdbInfo.EdbInfoId,
  330. }, order)
  331. if err != nil {
  332. return
  333. }
  334. var dateArr []string
  335. dataMap := make(map[string]*EdbInfoSearchData)
  336. fromDataMap := make(map[string]float64)
  337. //来源指指标数据
  338. for _, v := range dataList {
  339. dateArr = append(dateArr, v.DataTime)
  340. dataMap[v.DataTime] = v
  341. fromDataMap[v.DataTime] = v.Value
  342. }
  343. fmt.Println("source:", source)
  344. //获取升频指标所有数据
  345. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  346. if err != nil {
  347. return
  348. }
  349. //计算指标的map
  350. existDataMap := make(map[string]*EdbData, 0)
  351. removeDateMap := make(map[string]struct{})
  352. addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  353. var isAdd bool
  354. //待删除的日期
  355. removeDateList := make([]string, 0)
  356. if len(existDataList) > 0 && len(dateArr) == 0 {
  357. //如果没有来源指标数据,那么已经入库的计算指标数据需要全部删除
  358. tableName := GetEdbDataTableName(source, subSource)
  359. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ?`, tableName)
  360. _, err = to.Raw(sql, edbInfoId).Exec()
  361. if err != nil {
  362. err = fmt.Errorf("删除所有的升频指标数据失败,Err:" + err.Error())
  363. return
  364. }
  365. return
  366. }
  367. existMap := make(map[string]string)
  368. dataLen := len(dataList)
  369. //第三步: 已经入库的数据处理
  370. for _, v := range existDataList {
  371. existDataMap[v.DataTime] = v
  372. removeDateMap[v.DataTime] = struct{}{}
  373. }
  374. for i := 0; i < dataLen; i++ {
  375. //当期
  376. currentItem := dataList[i]
  377. var prevItem *EdbInfoSearchData
  378. if emptyType == 3 { //3后值填充,其余前值填充
  379. if i >= 1 {
  380. prevItem = dataList[i-1]
  381. }
  382. }
  383. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  384. var day int
  385. var preItem *EdbInfoSearchData
  386. var preDate time.Time
  387. if i == 0 {
  388. if emptyType == 3 { //后值填充
  389. day = 0 //最新的时间就是来源指标的最新日期
  390. preDate = currentDate
  391. } else {
  392. day = int(time.Now().Sub(currentDate).Hours() / float64(24))
  393. preDate = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local)
  394. }
  395. } else {
  396. j := i - 1
  397. if j < dataLen {
  398. preItem = dataList[j]
  399. preDate, _ = time.ParseInLocation(utils.FormatDate, preItem.DataTime, time.Local)
  400. day = int(preDate.Sub(currentDate).Hours() / float64(24))
  401. utils.FileLog.Info("preItem.DataTime:" + preItem.DataTime + ";currentItem.DataTime" + currentItem.DataTime)
  402. }
  403. }
  404. for k := 0; k <= day; k++ {
  405. needDay := preDate.AddDate(0, 0, -k)
  406. needDayStr := needDay.Format(utils.FormatDate)
  407. delete(removeDateMap, needDayStr)
  408. existKey := edbCode + needDayStr
  409. if _, ok := existMap[existKey]; !ok {
  410. timestamp := needDay.UnixNano() / 1e6
  411. timestampStr := fmt.Sprintf("%d", timestamp)
  412. currValDeci := decimal.NewFromFloat(currentItem.Value)
  413. if prevItem != nil && needDayStr != currentItem.DataTime {
  414. currValDeci = decimal.NewFromFloat(prevItem.Value)
  415. }
  416. currValStr := currValDeci.String()
  417. tmpExistData, ok2 := existDataMap[needDayStr]
  418. if !ok2 {
  419. addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, currValStr)
  420. isAdd = true
  421. } else {
  422. // 已经入库的数据值
  423. tmpExistVal, tmpErr := decimal.NewFromString(tmpExistData.Value)
  424. if tmpErr != nil {
  425. err = tmpErr
  426. return
  427. }
  428. // 如果已经入库的数据值 与 当前计算出来的值 不匹配,那么就去更新
  429. if !tmpExistVal.Equal(currValDeci) {
  430. err = ModifyEdbDataById(source, subSource, tmpExistData.EdbDataId, currValStr)
  431. if err != nil {
  432. return err
  433. }
  434. }
  435. }
  436. }
  437. existMap[existKey] = needDayStr
  438. }
  439. existKey := edbCode + currentItem.DataTime
  440. if _, ok := existMap[existKey]; !ok {
  441. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  442. timestamp := currentDate.UnixNano() / 1e6
  443. timestampStr := fmt.Sprintf("%d", timestamp)
  444. currValDeci := decimal.NewFromFloat(currentItem.Value)
  445. currValStr := currValDeci.String()
  446. tmpExistData, ok2 := existDataMap[currentItem.DataTime]
  447. if !ok2 {
  448. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, currValStr)
  449. isAdd = true
  450. } else {
  451. // 已经入库的数据值
  452. tmpExistVal, tmpErr := decimal.NewFromString(tmpExistData.Value)
  453. if tmpErr != nil {
  454. err = tmpErr
  455. return
  456. }
  457. // 如果已经入库的数据值 与 当前计算出来的值 不匹配,那么就去更新
  458. if !tmpExistVal.Equal(currValDeci) {
  459. err = ModifyEdbDataById(source, subSource, tmpExistData.EdbDataId, currValStr)
  460. if err != nil {
  461. return err
  462. }
  463. }
  464. }
  465. }
  466. existMap[existKey] = currentItem.DataTime
  467. }
  468. for k, _ := range removeDateMap {
  469. removeDateList = append(removeDateList, k)
  470. }
  471. // 删除不需要的指标数据
  472. if len(removeDateList) > 0 {
  473. //如果拼接指标变更了,那么需要删除所有的指标数据
  474. tableName := GetEdbDataTableName(source, subSource)
  475. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(len(removeDateList))+`) `, tableName)
  476. _, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
  477. if err != nil {
  478. err = fmt.Errorf("删除不存在的升频指标数据失败,Err:" + err.Error())
  479. return
  480. }
  481. }
  482. if isAdd {
  483. addSql = strings.TrimRight(addSql, ",")
  484. _, err = to.Raw(addSql).Exec()
  485. }
  486. return
  487. }