edb_data_calculate_hbz.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. // AddCalculateHbz 新增环比值指标
  13. func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (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("AddCalculateHbz,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_HBZ
  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. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  45. if tmpErr != nil {
  46. err = tmpErr
  47. return
  48. }
  49. edbInfo.EdbInfoId = int(newEdbInfoId)
  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. _, err = to.Insert(calculateMappingItem)
  67. if err != nil {
  68. return
  69. }
  70. }
  71. } else {
  72. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  73. if err != nil {
  74. return
  75. }
  76. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HBZ)
  77. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  78. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  79. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  80. if err != nil {
  81. return
  82. }
  83. }
  84. //计算数据
  85. err = refreshAllCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  86. return
  87. }
  88. // EditCalculateHbz 环比值
  89. func EditCalculateHbz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
  90. o := orm.NewOrm()
  91. to, err := o.Begin()
  92. if err != nil {
  93. return
  94. }
  95. defer func() {
  96. if err != nil {
  97. fmt.Println("EditCalculateHbz,Err:" + err.Error())
  98. _ = to.Rollback()
  99. } else {
  100. _ = to.Commit()
  101. }
  102. }()
  103. //修改指标信息
  104. edbInfo.EdbName = req.EdbName
  105. edbInfo.EdbNameSource = req.EdbName
  106. edbInfo.Frequency = req.Frequency
  107. edbInfo.Unit = req.Unit
  108. edbInfo.ClassifyId = req.ClassifyId
  109. edbInfo.CalculateFormula = req.Formula
  110. edbInfo.ModifyTime = time.Now()
  111. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  112. if err != nil {
  113. return
  114. }
  115. var existCondition string
  116. var existPars []interface{}
  117. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  118. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  119. //判断计算指标是否被更换
  120. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  121. if err != nil {
  122. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  123. return
  124. }
  125. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  126. return
  127. }
  128. //删除,计算指标关联的,基础指标的关联关系
  129. if count <= 0 {
  130. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  131. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  132. if err != nil {
  133. return
  134. }
  135. //关联关系
  136. {
  137. calculateMappingItem := &EdbInfoCalculateMapping{
  138. EdbInfoCalculateMappingId: 0,
  139. EdbInfoId: edbInfo.EdbInfoId,
  140. Source: utils.DATA_SOURCE_CALCULATE_HBZ,
  141. SourceName: "环比值",
  142. EdbCode: edbInfo.EdbCode,
  143. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  144. FromEdbCode: fromEdbInfo.EdbCode,
  145. FromEdbName: fromEdbInfo.EdbName,
  146. FromSource: fromEdbInfo.Source,
  147. FromSourceName: fromEdbInfo.SourceName,
  148. FromTag: "",
  149. Sort: 1,
  150. CreateTime: time.Now(),
  151. ModifyTime: time.Now(),
  152. }
  153. _, err = to.Insert(calculateMappingItem)
  154. if err != nil {
  155. return
  156. }
  157. }
  158. }
  159. //清空原有数据
  160. sql := ` DELETE FROM edb_data_calculate_hbz WHERE edb_info_id = ? `
  161. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  162. if err != nil {
  163. return
  164. }
  165. //计算数据
  166. err = refreshAllCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  167. return
  168. }
  169. // RefreshAllCalculateHbz 刷新所有环比值数据
  170. func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  171. o := orm.NewOrm()
  172. to, err := o.Begin()
  173. if err != nil {
  174. return
  175. }
  176. defer func() {
  177. if err != nil {
  178. fmt.Println("EditCalculateHbz,Err:" + err.Error())
  179. _ = to.Rollback()
  180. } else {
  181. _ = to.Commit()
  182. }
  183. }()
  184. //计算数据
  185. err = refreshAllCalculateHbz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  186. return
  187. }
  188. // refreshAllCalculateHbz 刷新所有环比值数据
  189. func refreshAllCalculateHbz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  190. edbInfoIdStr := strconv.Itoa(edbInfoId)
  191. //计算数据
  192. var condition string
  193. var pars []interface{}
  194. condition += " AND edb_info_id=? "
  195. pars = append(pars, fromEdbInfo.EdbInfoId)
  196. //if startDate != "" {
  197. // condition += " AND data_time>=? "
  198. // pars = append(pars, startDate)
  199. //}
  200. //if endDate != "" {
  201. // condition += " AND data_time<=? "
  202. // pars = append(pars, endDate)
  203. //}
  204. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
  205. if err != nil {
  206. return err
  207. }
  208. var dateArr []string
  209. dataMap := make(map[string]*EdbInfoSearchData)
  210. for _, v := range dataList {
  211. dateArr = append(dateArr, v.DataTime)
  212. dataMap[v.DataTime] = v
  213. }
  214. fmt.Println("source:", source)
  215. //获取指标所有数据
  216. existDataList := make([]*EdbData, 0)
  217. dataTableName := GetEdbDataTableName(source)
  218. fmt.Println("dataTableName:", dataTableName)
  219. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  220. sql = fmt.Sprintf(sql, dataTableName)
  221. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  222. if err != nil {
  223. return err
  224. }
  225. existDataMap := make(map[string]string)
  226. for _, v := range existDataList {
  227. existDataMap[v.DataTime] = v.Value
  228. }
  229. addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  230. var isAdd bool
  231. existMap := make(map[string]string)
  232. dataLen := len(dataList)
  233. fmt.Println("dataLen:", dataLen)
  234. for i := 0; i < dataLen; i++ {
  235. j := i + formulaInt
  236. if j < dataLen {
  237. //当期
  238. currentItem := dataList[i]
  239. preItem := dataList[j]
  240. if currentItem != nil && preItem != nil {
  241. existKey := edbCode + currentItem.DataTime
  242. if _, ok := existMap[existKey]; !ok {
  243. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  244. timestamp := currentDate.UnixNano() / 1e6
  245. timestampStr := fmt.Sprintf("%d", timestamp)
  246. val := HbzDiv(currentItem.Value, preItem.Value)
  247. if val != "" {
  248. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  249. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  250. isAdd = true
  251. } else {
  252. existValDecimal, err := decimal.NewFromString(existVal)
  253. existStr := existValDecimal.String()
  254. if existStr != val {
  255. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  256. sql = fmt.Sprintf(sql, dataTableName)
  257. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  258. if err != nil {
  259. return err
  260. }
  261. }
  262. }
  263. }
  264. }
  265. existMap[existKey] = currentItem.DataTime
  266. }
  267. }
  268. }
  269. if isAdd {
  270. addSql = strings.TrimRight(addSql, ",")
  271. _, err = to.Raw(addSql).Exec()
  272. if err != nil {
  273. return err
  274. }
  275. }
  276. return
  277. }
  278. // HbzDiv 环比值计算,current:当期,pre:上期 公式: (当期-上期)/上期
  279. func HbzDiv(current, pre float64) string {
  280. if pre == 0 {
  281. return ""
  282. }
  283. currentVal := decimal.NewFromFloat(current)
  284. preVal := decimal.NewFromFloat(pre)
  285. val, _ := currentVal.Sub(preVal).Div(preVal).Float64()
  286. valStr := decimal.NewFromFloat(val).RoundCeil(4).String() //utils.SubFloatToString(val, 4)
  287. return valStr
  288. }