edb_data_calculate_hbz.go 9.4 KB

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