edb_data_calculate_time_shift.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. package data_manage
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "eta/eta_api/utils"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. //时间移位
  13. type EdbInfoCalculateMove struct {
  14. EdbInfoCalculateBpId int `orm:"column(edb_info_calculate_bp_id);pk"`
  15. EdbInfoId int `description:"指标id"`
  16. EdbCode string `description:"指标编码"`
  17. FromEdbInfoId int `description:"计算指标id"`
  18. FromEdbCode string `description:"计算指标编码"`
  19. FromEdbName string `description:"计算指标名称"`
  20. FromSource int `description:"计算指标来源"`
  21. FromSourceName string `description:"计算指标来源名称"`
  22. FromTag string `description:"来源指标标签"`
  23. Sort int `description:"计算指标名称排序"`
  24. CreateTime time.Time `description:"创建时间"`
  25. ModifyTime time.Time `description:"修改时间"`
  26. }
  27. // 时间移位
  28. func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
  29. fmt.Println("AddCalculateTimeShift")
  30. o := orm.NewOrmUsingDB("data")
  31. to, err := o.Begin()
  32. if err != nil {
  33. return
  34. }
  35. defer func() {
  36. if err != nil {
  37. fmt.Println("AddCalculateTimeShift,Err:" + err.Error())
  38. _ = to.Rollback()
  39. } else {
  40. _ = to.Commit()
  41. }
  42. }()
  43. if req.EdbInfoId <= 0 {
  44. edbInfo := new(EdbInfo)
  45. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
  46. edbInfo.SourceName = "时间移位"
  47. edbInfo.EdbCode = edbCode
  48. edbInfo.EdbName = req.EdbName
  49. edbInfo.EdbNameSource = req.EdbName
  50. edbInfo.Frequency = req.Frequency
  51. edbInfo.Unit = req.Unit
  52. edbInfo.ClassifyId = req.ClassifyId
  53. edbInfo.SysUserId = sysUserId
  54. edbInfo.SysUserRealName = sysUserRealName
  55. edbInfo.CreateTime = time.Now()
  56. edbInfo.ModifyTime = time.Now()
  57. edbInfo.UniqueCode = uniqueCode
  58. edbInfo.CalculateFormula = req.Formula
  59. edbInfo.EdbType = 2
  60. edbInfo.MoveType = req.MoveType
  61. edbInfo.MoveFrequency = req.MoveFrequency
  62. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  63. if tmpErr != nil {
  64. return edbInfoId, tmpErr
  65. }
  66. edbInfoId = int(newEdbInfoId)
  67. //关联关系
  68. {
  69. calculateMappingItem := new(EdbInfoCalculateMapping)
  70. calculateMappingItem.CreateTime = time.Now()
  71. calculateMappingItem.ModifyTime = time.Now()
  72. calculateMappingItem.Sort = 1
  73. calculateMappingItem.EdbCode = edbCode
  74. calculateMappingItem.EdbInfoId = edbInfoId
  75. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  76. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  77. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  78. calculateMappingItem.FromSource = fromEdbInfo.Source
  79. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  80. calculateMappingItem.FromTag = ""
  81. calculateMappingItem.Source = edbInfo.Source
  82. calculateMappingItem.SourceName = edbInfo.SourceName
  83. _, err = to.Insert(calculateMappingItem)
  84. if err != nil {
  85. return
  86. }
  87. }
  88. } else {
  89. edbInfoId = req.EdbInfoId
  90. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TIME_SHIFT)
  91. fmt.Println("dataTableName:" + dataTableName)
  92. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  93. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  94. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  95. if err != nil {
  96. return 0, err
  97. }
  98. }
  99. var shiftDay int
  100. formulaInt, _ := strconv.Atoi(req.Formula)
  101. switch req.MoveFrequency {
  102. case "天":
  103. shiftDay = formulaInt
  104. case "周":
  105. shiftDay = formulaInt * 7
  106. case "月":
  107. shiftDay = formulaInt * 30
  108. case "季":
  109. shiftDay = formulaInt * 90
  110. case "年":
  111. shiftDay = formulaInt * 365
  112. default:
  113. shiftDay = formulaInt
  114. }
  115. edbInfoIdStr := strconv.Itoa(edbInfoId)
  116. //计算数据
  117. var condition string
  118. var pars []interface{}
  119. condition += " AND edb_info_id=? "
  120. if req.EdbInfoId <= 0 {
  121. pars = append(pars, req.FromEdbInfoId)
  122. } else {
  123. pars = append(pars, fromEdbInfo.EdbInfoId)
  124. }
  125. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  126. if err != nil {
  127. return edbInfoId, err
  128. }
  129. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  130. var isAdd bool
  131. existMap := make(map[string]string)
  132. dataLen := len(dataList)
  133. if req.MoveType == 2 {
  134. shiftDay = -shiftDay
  135. }
  136. for i := 0; i < dataLen; i++ {
  137. //当期
  138. currentItem := dataList[i]
  139. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  140. existKey := edbCode + currentItem.DataTime
  141. if _, ok := existMap[existKey]; !ok {
  142. newDate := currentDate.AddDate(0, 0, shiftDay)
  143. timestamp := newDate.UnixNano() / 1e6
  144. timestampStr := fmt.Sprintf("%d", timestamp)
  145. valStr := decimal.NewFromFloat(currentItem.Value).String()
  146. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  147. isAdd = true
  148. }
  149. existMap[existKey] = currentItem.DataTime
  150. }
  151. if isAdd {
  152. addSql = strings.TrimRight(addSql, ",")
  153. _, err = to.Raw(addSql).Exec()
  154. if err != nil {
  155. return edbInfoId, err
  156. }
  157. }
  158. return
  159. }
  160. // 环比值
  161. func EditCalculateTimeShift(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, oldEdbInfo *EdbInfo) (edbInfoId int, err error) {
  162. edbInfoId = req.EdbInfoId
  163. o := orm.NewOrmUsingDB("data")
  164. to, err := o.Begin()
  165. if err != nil {
  166. return
  167. }
  168. defer func() {
  169. if err != nil {
  170. _ = to.Rollback()
  171. } else {
  172. _ = to.Commit()
  173. }
  174. }()
  175. //修改指标信息
  176. sql := ` UPDATE edb_info
  177. SET
  178. edb_name =?,
  179. edb_name_source=?,
  180. frequency = ?,
  181. unit = ?,
  182. classify_id = ?,
  183. move_type=?,
  184. move_frequency=?,
  185. calculate_formula=?,
  186. modify_time = NOW()
  187. WHERE edb_info_id = ? `
  188. _, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.MoveType, req.MoveFrequency, req.Formula, edbInfoId).Exec()
  189. if err != nil {
  190. return
  191. }
  192. var existCondition string
  193. var existPars []interface{}
  194. existCondition += " AND edb_info_id=? "
  195. existPars = append(existPars, edbInfoId)
  196. existCondition += " AND from_edb_info_id=? "
  197. existPars = append(existPars, req.FromEdbInfoId)
  198. //判断计算指标是否被更换
  199. count, err := GetEdbInfoCalculateCountByCondition(req.Source, existCondition, existPars)
  200. if err != nil {
  201. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  202. return
  203. }
  204. if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
  205. if count <= 0 {
  206. //删除,计算指标关联的,基础指标的关联关系
  207. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  208. _, err = to.Raw(sql, edbInfoId).Exec()
  209. if err != nil {
  210. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  211. return
  212. }
  213. //关联关系
  214. {
  215. calculateMappingItem := new(EdbInfoCalculateMapping)
  216. calculateMappingItem.CreateTime = time.Now()
  217. calculateMappingItem.ModifyTime = time.Now()
  218. calculateMappingItem.Sort = 1
  219. calculateMappingItem.EdbCode = edbCode
  220. calculateMappingItem.EdbInfoId = edbInfoId
  221. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  222. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  223. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  224. calculateMappingItem.FromSource = fromEdbInfo.Source
  225. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  226. calculateMappingItem.FromTag = ""
  227. calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
  228. calculateMappingItem.SourceName = "时间移位"
  229. _, err = to.Insert(calculateMappingItem)
  230. if err != nil {
  231. return
  232. }
  233. }
  234. }
  235. //清空原有数据
  236. sql = ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
  237. _, err = to.Raw(sql, edbInfoId).Exec()
  238. if err != nil {
  239. return edbInfoId, err
  240. }
  241. edbInfoIdStr := strconv.Itoa(edbInfoId)
  242. var shiftDay int
  243. formulaInt, _ := strconv.Atoi(req.Formula)
  244. switch req.MoveFrequency {
  245. case "天":
  246. shiftDay = formulaInt
  247. case "周":
  248. shiftDay = formulaInt * 7
  249. case "月":
  250. shiftDay = formulaInt * 30
  251. case "季":
  252. shiftDay = formulaInt * 90
  253. case "年":
  254. shiftDay = formulaInt * 365
  255. default:
  256. shiftDay = formulaInt
  257. }
  258. //计算数据
  259. var condition string
  260. var pars []interface{}
  261. condition += " AND edb_info_id=? "
  262. pars = append(pars, req.FromEdbInfoId)
  263. fmt.Println("EdbInfoId:", req.FromEdbInfoId)
  264. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  265. if err != nil {
  266. return edbInfoId, err
  267. }
  268. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  269. var isAdd bool
  270. existMap := make(map[string]string)
  271. dataLen := len(dataList)
  272. if req.MoveType == 2 {
  273. shiftDay = -shiftDay
  274. }
  275. for i := 0; i < dataLen; i++ {
  276. //当期
  277. currentItem := dataList[i]
  278. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  279. newDate := currentDate.AddDate(0, 0, shiftDay)
  280. existKey := edbCode + newDate.Format(utils.FormatDate)
  281. if _, ok := existMap[existKey]; !ok {
  282. timestamp := newDate.UnixNano() / 1e6
  283. timestampStr := fmt.Sprintf("%d", timestamp)
  284. valStr := decimal.NewFromFloat(currentItem.Value).String()
  285. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  286. isAdd = true
  287. }
  288. existMap[existKey] = currentItem.DataTime
  289. }
  290. if isAdd {
  291. addSql = strings.TrimRight(addSql, ",")
  292. _, err = to.Raw(addSql).Exec()
  293. if err != nil {
  294. return edbInfoId, err
  295. }
  296. }
  297. }
  298. return
  299. }
  300. // 变频
  301. func RefreshCalculateTimeShift(edbInfoId, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  302. o := orm.NewOrmUsingDB("data")
  303. to, err := o.Begin()
  304. if err != nil {
  305. return
  306. }
  307. defer func() {
  308. if err != nil {
  309. _ = to.Rollback()
  310. } else {
  311. _ = to.Commit()
  312. }
  313. }()
  314. if err != nil {
  315. return
  316. }
  317. edbInfoIdStr := strconv.Itoa(edbInfoId)
  318. //计算数据
  319. //计算数据
  320. var condition string
  321. var pars []interface{}
  322. condition += " AND edb_info_id=? "
  323. pars = append(pars, fromEdbInfo.EdbInfoId)
  324. if startDate != "" {
  325. condition += " AND data_time>=? "
  326. pars = append(pars, startDate)
  327. }
  328. if endDate != "" {
  329. condition += " AND data_time<=? "
  330. pars = append(pars, endDate)
  331. }
  332. var shiftDay int
  333. switch moveFrequency {
  334. case "天":
  335. shiftDay = formulaInt
  336. case "周":
  337. shiftDay = formulaInt * 7
  338. case "月":
  339. shiftDay = formulaInt * 30
  340. case "季":
  341. shiftDay = formulaInt * 90
  342. case "年":
  343. shiftDay = formulaInt * 365
  344. default:
  345. shiftDay = formulaInt
  346. }
  347. if moveType == 2 {
  348. shiftDay = -shiftDay
  349. }
  350. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  351. if err != nil {
  352. return err
  353. }
  354. existMap := make(map[string]string)
  355. dataLen := len(dataList)
  356. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  357. var isAdd bool
  358. for i := 0; i < dataLen; i++ {
  359. //当期
  360. currentItem := dataList[i]
  361. existKey := edbCode + currentItem.DataTime
  362. if _, ok := existMap[existKey]; !ok {
  363. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  364. newDate := currentDate.AddDate(0, 0, -shiftDay)
  365. timestamp := newDate.UnixNano() / 1e6
  366. timestampStr := fmt.Sprintf("%d", timestamp)
  367. valStr := decimal.NewFromFloat(currentItem.Value).String()
  368. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  369. }
  370. existMap[existKey] = currentItem.DataTime
  371. }
  372. if isAdd {
  373. addSql = strings.TrimRight(addSql, ",")
  374. _, err = to.Raw(addSql).Exec()
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. return
  380. }
  381. type EdbInfoCalculateTimeShiftDetail struct {
  382. EdbInfoCalculateBpId int `orm:"column(edb_info_calculate_bp_id);pk"`
  383. EdbInfoId int `description:"指标id"`
  384. EdbCode string `description:"指标编码"`
  385. FromEdbInfoId int `description:"计算指标id"`
  386. FromEdbCode string `description:"计算指标编码"`
  387. FromEdbName string `description:"计算指标名称"`
  388. FromSource int `description:"计算指标来源"`
  389. FromSourceName string `description:"计算指标来源名称"`
  390. FromTag string `description:"来源指标标签"`
  391. Sort int `description:"计算指标名称排序"`
  392. CreateTime time.Time `description:"创建时间"`
  393. ModifyTime time.Time `description:"修改时间"`
  394. StartDate string `description:"开始日期"`
  395. EndDate string `description:"结束日期"`
  396. }
  397. func GetEdbInfoCalculateTimeShiftDetail(edbInfoId int) (item *EdbInfoCalculateTbzDetail, err error) {
  398. o := orm.NewOrmUsingDB("data")
  399. sql := ` SELECT a.*,b.start_date,b.end_date FROM edb_info_calculate_mapping AS a
  400. INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
  401. WHERE a.edb_info_id=? `
  402. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  403. return
  404. }
  405. // 刷新所有变频数据
  406. func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  407. o := orm.NewOrmUsingDB("data")
  408. to, err := o.Begin()
  409. if err != nil {
  410. return
  411. }
  412. defer func() {
  413. if err != nil {
  414. _ = to.Rollback()
  415. } else {
  416. _ = to.Commit()
  417. }
  418. }()
  419. if err != nil {
  420. return
  421. }
  422. edbInfoIdStr := strconv.Itoa(edbInfoId)
  423. //计算数据
  424. //计算数据
  425. var condition string
  426. var pars []interface{}
  427. condition += " AND edb_info_id=? "
  428. pars = append(pars, fromEdbInfo.EdbInfoId)
  429. if startDate != "" {
  430. condition += " AND data_time>=? "
  431. pars = append(pars, startDate)
  432. }
  433. if endDate != "" {
  434. condition += " AND data_time<=? "
  435. pars = append(pars, endDate)
  436. }
  437. var shiftDay int
  438. switch moveFrequency {
  439. case "天":
  440. shiftDay = formulaInt
  441. case "周":
  442. shiftDay = formulaInt * 7
  443. case "月":
  444. shiftDay = formulaInt * 30
  445. case "季":
  446. shiftDay = formulaInt * 90
  447. case "年":
  448. shiftDay = formulaInt * 365
  449. default:
  450. shiftDay = formulaInt
  451. }
  452. if moveType == 2 {
  453. shiftDay = -shiftDay
  454. }
  455. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  456. if err != nil {
  457. return err
  458. }
  459. var dateArr []string
  460. dataMap := make(map[string]*EdbInfoSearchData)
  461. for _, v := range dataList {
  462. dateArr = append(dateArr, v.DataTime)
  463. dataMap[v.DataTime] = v
  464. }
  465. fmt.Println("source:", source)
  466. //获取指标所有数据
  467. existDataList := make([]*EdbDataBase, 0)
  468. dataTableName := GetEdbDataTableName(source)
  469. fmt.Println("dataTableName:", dataTableName)
  470. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  471. sql = fmt.Sprintf(sql, dataTableName)
  472. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  473. if err != nil {
  474. return err
  475. }
  476. existDataMap := make(map[string]string)
  477. for _, v := range existDataList {
  478. existDataMap[v.DataTime] = v.Value
  479. }
  480. fmt.Println("existDataMap:", existDataMap)
  481. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  482. var isAdd bool
  483. existMap := make(map[string]string)
  484. dataLen := len(dataList)
  485. for i := 0; i < dataLen; i++ {
  486. //当期
  487. currentItem := dataList[i]
  488. existKey := edbCode + currentItem.DataTime
  489. if _, ok := existMap[existKey]; !ok {
  490. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  491. newDate := currentDate.AddDate(0, 0, shiftDay)
  492. timestamp := newDate.UnixNano() / 1e6
  493. timestampStr := fmt.Sprintf("%d", timestamp)
  494. valStr := decimal.NewFromFloat(currentItem.Value).String()
  495. if existVal, ok := existDataMap[newDate.Format(utils.FormatDate)]; !ok {
  496. isAdd = true
  497. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  498. } else {
  499. if existVal != valStr {
  500. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  501. sql = fmt.Sprintf(sql, dataTableName)
  502. _, err = to.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
  503. if err != nil {
  504. return err
  505. }
  506. }
  507. }
  508. }
  509. existMap[existKey] = currentItem.DataTime
  510. }
  511. if isAdd {
  512. addSql = strings.TrimRight(addSql, ",")
  513. _, err = to.Raw(addSql).Exec()
  514. if err != nil {
  515. return err
  516. }
  517. }
  518. return
  519. }