edb_data_calculate_time_shift.go 14 KB

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