edb_data_calculate_time_shift.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. // AddCalculateTimeShift 时间移位
  13. func AddCalculateTimeShift(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("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 := to.Insert(edbInfo)
  47. if tmpErr != nil {
  48. err = tmpErr
  49. return
  50. }
  51. edbInfo.EdbInfoId = int(newEdbInfoId)
  52. //关联关系
  53. {
  54. calculateMappingItem := new(EdbInfoCalculateMapping)
  55. calculateMappingItem.CreateTime = time.Now()
  56. calculateMappingItem.ModifyTime = time.Now()
  57. calculateMappingItem.Sort = 1
  58. calculateMappingItem.EdbCode = edbCode
  59. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  60. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  61. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  62. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  63. calculateMappingItem.FromSource = fromEdbInfo.Source
  64. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  65. calculateMappingItem.FromTag = ""
  66. calculateMappingItem.Source = edbInfo.Source
  67. calculateMappingItem.SourceName = edbInfo.SourceName
  68. calculateMappingItem.FromSubSource = edbInfo.SubSource
  69. _, err = to.Insert(calculateMappingItem)
  70. if err != nil {
  71. return
  72. }
  73. }
  74. } else {
  75. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  76. if err != nil {
  77. return
  78. }
  79. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TIME_SHIFT, utils.DATA_SUB_SOURCE_EDB)
  80. fmt.Println("dataTableName:" + dataTableName)
  81. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  82. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  83. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  84. if err != nil {
  85. return
  86. }
  87. }
  88. formulaInt, _ := strconv.Atoi(req.Formula)
  89. //计算数据
  90. err = refreshAllCalculateTimeShift(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
  91. return
  92. }
  93. // EditCalculateTimeShift 修改时间移位
  94. func EditCalculateTimeShift(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  95. o := orm.NewOrm()
  96. to, err := o.Begin()
  97. if err != nil {
  98. return
  99. }
  100. defer func() {
  101. if err != nil {
  102. fmt.Println("EditCalculateTimeShift,Err:" + err.Error())
  103. _ = to.Rollback()
  104. } else {
  105. _ = to.Commit()
  106. }
  107. }()
  108. oldEdbInfo := *edbInfo //旧的指标信息
  109. //修改指标信息
  110. edbInfo.EdbName = req.EdbName
  111. edbInfo.EdbNameSource = req.EdbName
  112. edbInfo.Frequency = req.Frequency
  113. edbInfo.Unit = req.Unit
  114. edbInfo.ClassifyId = req.ClassifyId
  115. edbInfo.MoveType = req.MoveType
  116. edbInfo.MoveFrequency = req.MoveFrequency
  117. edbInfo.CalculateFormula = req.Formula
  118. edbInfo.ModifyTime = time.Now()
  119. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "MoveType", "MoveFrequency", "CalculateFormula", "ModifyTime")
  120. if err != nil {
  121. return
  122. }
  123. //判断计算指标是否被更换
  124. var existCondition string
  125. var existPars []interface{}
  126. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  127. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  128. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  129. if err != nil {
  130. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  131. return
  132. }
  133. if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
  134. //如果是依赖指标变更,那么需要删除对应的关联指标,并添加新的关系
  135. if count <= 0 {
  136. //删除,计算指标关联的,基础指标的关联关系
  137. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  138. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  139. if err != nil {
  140. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  141. return
  142. }
  143. //关联关系
  144. {
  145. calculateMappingItem := &EdbInfoCalculateMapping{
  146. EdbInfoCalculateMappingId: 0,
  147. EdbInfoId: edbInfo.EdbInfoId,
  148. Source: utils.DATA_SOURCE_CALCULATE_TIME_SHIFT,
  149. SourceName: "时间移位",
  150. EdbCode: edbInfo.EdbCode,
  151. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  152. FromEdbCode: fromEdbInfo.EdbCode,
  153. FromEdbName: fromEdbInfo.EdbName,
  154. FromSource: fromEdbInfo.Source,
  155. FromSourceName: fromEdbInfo.SourceName,
  156. FromTag: "",
  157. Sort: 1,
  158. CreateTime: time.Now(),
  159. ModifyTime: time.Now(),
  160. FromSubSource: fromEdbInfo.SubSource,
  161. }
  162. _, err = to.Insert(calculateMappingItem)
  163. if err != nil {
  164. return
  165. }
  166. }
  167. }
  168. //清空原有数据
  169. sql := ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
  170. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  171. if err != nil {
  172. return
  173. }
  174. //计算数据
  175. formulaInt, _ := strconv.Atoi(req.Formula)
  176. err = refreshAllCalculateTimeShift(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
  177. }
  178. return
  179. }
  180. // RefreshAllCalculateTimeShift 刷新所有时间移位数据
  181. func RefreshAllCalculateTimeShift(edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  182. o := orm.NewOrm()
  183. to, err := o.Begin()
  184. if err != nil {
  185. return
  186. }
  187. defer func() {
  188. if err != nil {
  189. fmt.Println("RefreshAllCalculateTimeShift,Err:" + err.Error())
  190. _ = to.Rollback()
  191. } else {
  192. _ = to.Commit()
  193. }
  194. }()
  195. //计算数据
  196. err = refreshAllCalculateTimeShift(to, edbInfoId, source, subSource, formulaInt, moveType, fromEdbInfo, edbCode, startDate, endDate, moveFrequency)
  197. return
  198. }
  199. // refreshAllCalculateTimeShift 刷新所有时间移位数据
  200. func refreshAllCalculateTimeShift(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  201. edbInfoIdStr := strconv.Itoa(edbInfoId)
  202. //计算数据
  203. var condition string
  204. var pars []interface{}
  205. condition += " AND edb_info_id=? "
  206. pars = append(pars, fromEdbInfo.EdbInfoId)
  207. if startDate != "" {
  208. condition += " AND data_time>=? "
  209. pars = append(pars, startDate)
  210. }
  211. //if endDate != "" {
  212. // condition += " AND data_time<=? "
  213. // pars = append(pars, endDate)
  214. //}
  215. var shiftDay int
  216. switch moveFrequency {
  217. case "天":
  218. shiftDay = formulaInt
  219. case "周":
  220. shiftDay = formulaInt * 7
  221. case "月":
  222. shiftDay = formulaInt * 30
  223. case "季":
  224. shiftDay = formulaInt * 90
  225. case "年":
  226. shiftDay = formulaInt * 365
  227. default:
  228. shiftDay = formulaInt
  229. }
  230. if moveType == 2 {
  231. shiftDay = -shiftDay
  232. }
  233. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  234. if err != nil {
  235. return err
  236. }
  237. var dateArr []string
  238. dataMap := make(map[string]*EdbInfoSearchData)
  239. for _, v := range dataList {
  240. dateArr = append(dateArr, v.DataTime)
  241. dataMap[v.DataTime] = v
  242. }
  243. fmt.Println("source:", source)
  244. //获取指标所有数据
  245. existDataList := make([]*EdbData, 0)
  246. dataTableName := GetEdbDataTableName(source, subSource)
  247. fmt.Println("dataTableName:", dataTableName)
  248. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  249. sql = fmt.Sprintf(sql, dataTableName)
  250. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  251. if err != nil {
  252. return err
  253. }
  254. existDataMap := make(map[string]string)
  255. for _, v := range existDataList {
  256. existDataMap[v.DataTime] = v.Value
  257. }
  258. fmt.Println("existDataMap:", existDataMap)
  259. addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  260. var isAdd bool
  261. existMap := make(map[string]string)
  262. dataLen := len(dataList)
  263. for i := 0; i < dataLen; i++ {
  264. //当期
  265. currentItem := dataList[i]
  266. existKey := edbCode + currentItem.DataTime
  267. if _, ok := existMap[existKey]; !ok {
  268. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  269. newDate := currentDate.AddDate(0, 0, shiftDay)
  270. timestamp := newDate.UnixNano() / 1e6
  271. timestampStr := fmt.Sprintf("%d", timestamp)
  272. valStr := decimal.NewFromFloat(currentItem.Value).RoundCeil(4).String()
  273. if existVal, ok := existDataMap[newDate.Format(utils.FormatDate)]; !ok {
  274. isAdd = true
  275. addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
  276. } else {
  277. existValDecimal, err := decimal.NewFromString(existVal)
  278. existStr := existValDecimal.String()
  279. if existStr != valStr {
  280. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  281. sql = fmt.Sprintf(sql, dataTableName)
  282. _, err = to.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
  283. if err != nil {
  284. return err
  285. }
  286. }
  287. }
  288. }
  289. existMap[existKey] = currentItem.DataTime
  290. }
  291. if isAdd {
  292. addSql = strings.TrimRight(addSql, ",")
  293. _, err = to.Raw(addSql).Exec()
  294. if err != nil {
  295. return err
  296. }
  297. }
  298. return
  299. }