edb_data_calculate_time_shift.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // AddCalculateTimeShift 时间移位
  13. func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, 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("AddCalculateTimeShift,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_TIME_SHIFT
  30. edbInfo.SourceName = "时间移位"
  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.EdbType = 2
  44. edbInfo.MoveType = req.MoveType
  45. edbInfo.MoveFrequency = req.MoveFrequency
  46. newEdbInfoId, tmpErr := o.Insert(edbInfo)
  47. if tmpErr != nil {
  48. return edbInfoId, tmpErr
  49. }
  50. edbInfoId = int(newEdbInfoId)
  51. //关联关系
  52. {
  53. calculateMappingItem := new(EdbInfoCalculateMapping)
  54. calculateMappingItem.CreateTime = time.Now()
  55. calculateMappingItem.ModifyTime = time.Now()
  56. calculateMappingItem.Sort = 1
  57. calculateMappingItem.EdbCode = edbCode
  58. calculateMappingItem.EdbInfoId = edbInfoId
  59. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  60. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  61. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  62. calculateMappingItem.FromSource = fromEdbInfo.Source
  63. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  64. calculateMappingItem.FromTag = ""
  65. calculateMappingItem.Source = edbInfo.Source
  66. calculateMappingItem.SourceName = edbInfo.SourceName
  67. _, err = to.Insert(calculateMappingItem)
  68. if err != nil {
  69. return
  70. }
  71. }
  72. } else {
  73. edbInfoId = req.EdbInfoId
  74. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TIME_SHIFT)
  75. fmt.Println("dataTableName:" + dataTableName)
  76. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  77. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  78. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  79. if err != nil {
  80. return 0, err
  81. }
  82. }
  83. var shiftDay int
  84. formulaInt, _ := strconv.Atoi(req.Formula)
  85. switch req.MoveFrequency {
  86. case "天":
  87. shiftDay = formulaInt
  88. case "周":
  89. shiftDay = formulaInt * 7
  90. case "月":
  91. shiftDay = formulaInt * 30
  92. case "季":
  93. shiftDay = formulaInt * 90
  94. case "年":
  95. shiftDay = formulaInt * 365
  96. default:
  97. shiftDay = formulaInt
  98. }
  99. edbInfoIdStr := strconv.Itoa(edbInfoId)
  100. //计算数据
  101. var condition string
  102. var pars []interface{}
  103. condition += " AND edb_info_id=? "
  104. if req.EdbInfoId <= 0 {
  105. pars = append(pars, req.FromEdbInfoId)
  106. } else {
  107. pars = append(pars, fromEdbInfo.EdbInfoId)
  108. }
  109. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  110. if err != nil {
  111. return edbInfoId, err
  112. }
  113. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  114. var isAdd bool
  115. existMap := make(map[string]string)
  116. dataLen := len(dataList)
  117. if req.MoveType == 2 {
  118. shiftDay = -shiftDay
  119. }
  120. for i := 0; i < dataLen; i++ {
  121. //当期
  122. currentItem := dataList[i]
  123. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  124. existKey := edbCode + currentItem.DataTime
  125. if _, ok := existMap[existKey]; !ok {
  126. newDate := currentDate.AddDate(0, 0, shiftDay)
  127. timestamp := newDate.UnixNano() / 1e6
  128. timestampStr := fmt.Sprintf("%d", timestamp)
  129. valStr := decimal.NewFromFloat(currentItem.Value).String()
  130. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  131. isAdd = true
  132. }
  133. existMap[existKey] = currentItem.DataTime
  134. }
  135. if isAdd {
  136. addSql = strings.TrimRight(addSql, ",")
  137. _, err = to.Raw(addSql).Exec()
  138. if err != nil {
  139. return edbInfoId, err
  140. }
  141. }
  142. return
  143. }
  144. // EditCalculateTimeShift 修改时间移位
  145. func EditCalculateTimeShift(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, oldEdbInfo *EdbInfo) (edbInfoId int, err error) {
  146. edbInfoId = req.EdbInfoId
  147. o := orm.NewOrm()
  148. to, err := o.Begin()
  149. if err != nil {
  150. return
  151. }
  152. defer func() {
  153. if err != nil {
  154. fmt.Println("EditCalculateTimeShift,Err:" + err.Error())
  155. _ = to.Rollback()
  156. } else {
  157. _ = to.Commit()
  158. }
  159. }()
  160. //修改指标信息
  161. sql := ` UPDATE edb_info
  162. SET
  163. edb_name =?,
  164. edb_name_source=?,
  165. frequency = ?,
  166. unit = ?,
  167. classify_id = ?,
  168. move_type=?,
  169. move_frequency=?,
  170. calculate_formula=?,
  171. modify_time = NOW()
  172. WHERE edb_info_id = ? `
  173. _, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.MoveType, req.MoveFrequency, req.Formula, edbInfoId).Exec()
  174. if err != nil {
  175. return
  176. }
  177. var existCondition string
  178. var existPars []interface{}
  179. existCondition += " AND edb_info_id=? "
  180. existPars = append(existPars, edbInfoId)
  181. existCondition += " AND from_edb_info_id=? "
  182. existPars = append(existPars, req.FromEdbInfoId)
  183. //判断计算指标是否被更换
  184. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  185. if err != nil {
  186. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  187. return
  188. }
  189. if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
  190. if count <= 0 {
  191. //删除,计算指标关联的,基础指标的关联关系
  192. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  193. _, err = o.Raw(sql, edbInfoId).Exec()
  194. if err != nil {
  195. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  196. return
  197. }
  198. //关联关系
  199. {
  200. calculateMappingItem := new(EdbInfoCalculateMapping)
  201. calculateMappingItem.CreateTime = time.Now()
  202. calculateMappingItem.ModifyTime = time.Now()
  203. calculateMappingItem.Sort = 1
  204. calculateMappingItem.EdbCode = edbCode
  205. calculateMappingItem.EdbInfoId = edbInfoId
  206. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  207. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  208. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  209. calculateMappingItem.FromSource = fromEdbInfo.Source
  210. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  211. calculateMappingItem.FromTag = ""
  212. calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
  213. calculateMappingItem.SourceName = "时间移位"
  214. _, err = o.Insert(calculateMappingItem)
  215. if err != nil {
  216. return
  217. }
  218. }
  219. }
  220. //清空原有数据
  221. sql = ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
  222. _, err = o.Raw(sql, edbInfoId).Exec()
  223. if err != nil {
  224. return edbInfoId, err
  225. }
  226. edbInfoIdStr := strconv.Itoa(edbInfoId)
  227. var shiftDay int
  228. formulaInt, _ := strconv.Atoi(req.Formula)
  229. switch req.MoveFrequency {
  230. case "天":
  231. shiftDay = formulaInt
  232. case "周":
  233. shiftDay = formulaInt * 7
  234. case "月":
  235. shiftDay = formulaInt * 30
  236. case "季":
  237. shiftDay = formulaInt * 90
  238. case "年":
  239. shiftDay = formulaInt * 365
  240. default:
  241. shiftDay = formulaInt
  242. }
  243. //计算数据
  244. var condition string
  245. var pars []interface{}
  246. condition += " AND edb_info_id=? "
  247. pars = append(pars, req.FromEdbInfoId)
  248. fmt.Println("EdbInfoId:", req.FromEdbInfoId)
  249. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  250. if err != nil {
  251. return edbInfoId, err
  252. }
  253. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  254. var isAdd bool
  255. existMap := make(map[string]string)
  256. dataLen := len(dataList)
  257. if req.MoveType == 2 {
  258. shiftDay = -shiftDay
  259. }
  260. for i := 0; i < dataLen; i++ {
  261. //当期
  262. currentItem := dataList[i]
  263. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  264. newDate := currentDate.AddDate(0, 0, shiftDay)
  265. existKey := edbCode + newDate.Format(utils.FormatDate)
  266. if _, ok := existMap[existKey]; !ok {
  267. timestamp := newDate.UnixNano() / 1e6
  268. timestampStr := fmt.Sprintf("%d", timestamp)
  269. valStr := decimal.NewFromFloat(currentItem.Value).String()
  270. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  271. isAdd = true
  272. }
  273. existMap[existKey] = currentItem.DataTime
  274. }
  275. if isAdd {
  276. addSql = strings.TrimRight(addSql, ",")
  277. _, err = o.Raw(addSql).Exec()
  278. if err != nil {
  279. return edbInfoId, err
  280. }
  281. }
  282. }
  283. return
  284. }
  285. // RefreshAllCalculateTimeShift 刷新所有时间移位数据
  286. func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  287. o := orm.NewOrm()
  288. to, err := o.Begin()
  289. if err != nil {
  290. return
  291. }
  292. defer func() {
  293. if err != nil {
  294. fmt.Println("RefreshAllCalculateTimeShift,Err:" + err.Error())
  295. _ = to.Rollback()
  296. } else {
  297. _ = to.Commit()
  298. }
  299. }()
  300. if err != nil {
  301. return
  302. }
  303. edbInfoIdStr := strconv.Itoa(edbInfoId)
  304. //计算数据
  305. //计算数据
  306. var condition string
  307. var pars []interface{}
  308. condition += " AND edb_info_id=? "
  309. pars = append(pars, fromEdbInfo.EdbInfoId)
  310. if startDate != "" {
  311. condition += " AND data_time>=? "
  312. pars = append(pars, startDate)
  313. }
  314. //if endDate != "" {
  315. // condition += " AND data_time<=? "
  316. // pars = append(pars, endDate)
  317. //}
  318. var shiftDay int
  319. switch moveFrequency {
  320. case "天":
  321. shiftDay = formulaInt
  322. case "周":
  323. shiftDay = formulaInt * 7
  324. case "月":
  325. shiftDay = formulaInt * 30
  326. case "季":
  327. shiftDay = formulaInt * 90
  328. case "年":
  329. shiftDay = formulaInt * 365
  330. default:
  331. shiftDay = formulaInt
  332. }
  333. if moveType == 2 {
  334. shiftDay = -shiftDay
  335. }
  336. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  337. if err != nil {
  338. return err
  339. }
  340. var dateArr []string
  341. dataMap := make(map[string]*EdbInfoSearchData)
  342. for _, v := range dataList {
  343. dateArr = append(dateArr, v.DataTime)
  344. dataMap[v.DataTime] = v
  345. }
  346. fmt.Println("source:", source)
  347. //获取指标所有数据
  348. existDataList := make([]*EdbData, 0)
  349. dataTableName := GetEdbDataTableName(source)
  350. fmt.Println("dataTableName:", dataTableName)
  351. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  352. sql = fmt.Sprintf(sql, dataTableName)
  353. _, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
  354. if err != nil {
  355. return err
  356. }
  357. existDataMap := make(map[string]string)
  358. for _, v := range existDataList {
  359. existDataMap[v.DataTime] = v.Value
  360. }
  361. fmt.Println("existDataMap:", existDataMap)
  362. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  363. var isAdd bool
  364. existMap := make(map[string]string)
  365. dataLen := len(dataList)
  366. for i := 0; i < dataLen; i++ {
  367. //当期
  368. currentItem := dataList[i]
  369. existKey := edbCode + currentItem.DataTime
  370. if _, ok := existMap[existKey]; !ok {
  371. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  372. newDate := currentDate.AddDate(0, 0, shiftDay)
  373. timestamp := newDate.UnixNano() / 1e6
  374. timestampStr := fmt.Sprintf("%d", timestamp)
  375. valStr := decimal.NewFromFloat(currentItem.Value).String()
  376. if existVal, ok := existDataMap[newDate.Format(utils.FormatDate)]; !ok {
  377. isAdd = true
  378. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  379. } else {
  380. if existVal != valStr {
  381. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  382. sql = fmt.Sprintf(sql, dataTableName)
  383. _, err = o.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
  384. if err != nil {
  385. return err
  386. }
  387. }
  388. }
  389. }
  390. existMap[existKey] = currentItem.DataTime
  391. }
  392. if isAdd {
  393. addSql = strings.TrimRight(addSql, ",")
  394. _, err = o.Raw(addSql).Exec()
  395. if err != nil {
  396. return err
  397. }
  398. }
  399. return
  400. }