edb_data_calculate_phase_shift.go 11 KB

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