edb_data_calculate_time_shift.go 11 KB

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