edb_data_calculate_time_shift.go 10 KB

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