base_from_calculate.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package utils
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "time"
  8. )
  9. // CheckFormula 检测计算公式是否异常
  10. func CheckFormula(formula string) (byteMap map[string]string, err error) {
  11. mathFormula := []string{"MAX", "MIN", "ABS", "ACOS", "ASIN", "CEIL", "MOD", "POW", "ROUND", "SIGN", "SIN", "TAN", "LOG10", "LOG2", "LOG", "LN", "EXP"}
  12. str := strings.ToUpper(formula)
  13. for _, v := range mathFormula {
  14. str = strings.Replace(str, v, "", -1)
  15. }
  16. str = strings.Replace(str, "(", "", -1)
  17. str = strings.Replace(str, ")", "", -1)
  18. byteMap = make(map[string]string)
  19. for i := 0; i < len(str); i++ {
  20. byteInt := str[i]
  21. if byteInt >= 65 && byteInt <= 90 {
  22. // 判断前一位是否是数字,如果是数字就报错
  23. if i > 0 {
  24. if str[i-1] >= '0' && str[i-1] <= '9' {
  25. err = fmt.Errorf("计算公式异常,请检查公式:%s", formula)
  26. return
  27. }
  28. }
  29. byteStr := string(byteInt) //获取计算公式中的占位符A,B, AA,AB
  30. if i+1 < len(str) {
  31. next := str[i+1]
  32. if next >= 65 && next <= 90 {
  33. byteStr += string(next)
  34. i++
  35. }
  36. }
  37. if _, ok := byteMap[byteStr]; !ok {
  38. byteMap[byteStr] = byteStr
  39. }
  40. }
  41. }
  42. return
  43. }
  44. type FormulaListItem struct {
  45. Formula string `json:"f"`
  46. Date string `json:"d"`
  47. }
  48. // HandleFormulaJson 处理计算公式json串是否异常
  49. func HandleFormulaJson(formula string, endDate time.Time) (dateSlice []string, formulaMap map[string]string, err error) {
  50. list := make([]FormulaListItem, 0)
  51. err = json.Unmarshal([]byte(formula), &list)
  52. if err != nil {
  53. err = fmt.Errorf("公式串解析失败: json.Unmarshal Err: %v", err)
  54. return
  55. }
  56. formulaMap = make(map[string]string)
  57. dateSlice = make([]string, 0)
  58. // 查找最后的一天作为首个公式的起始日期
  59. maxDate := endDate.AddDate(0, 0, 1).Format(FormatDate)
  60. // 日期排序
  61. for k, v := range list {
  62. if k == 0 { // 首个日期均为起始日
  63. v.Date = maxDate
  64. }
  65. formulaMap[v.Date] = v.Formula
  66. dateSlice = append(dateSlice, v.Date)
  67. }
  68. // 得到的日期序列是从大到小,还是从小到大?
  69. sort.Slice(dateSlice, func(i, j int) bool {
  70. return dateSlice[i] < dateSlice[j]
  71. })
  72. return
  73. }
  74. // CheckFormulaJson 检测计算公式json串是否异常
  75. func CheckFormulaJson(formula string) (formulaSlice []string, err error) {
  76. list := make([]FormulaListItem, 0)
  77. err = json.Unmarshal([]byte(formula), &list)
  78. if err != nil {
  79. err = fmt.Errorf("公式串解析失败: json.Unmarshal Err: %v", err)
  80. return
  81. }
  82. formulaSlice = make([]string, 0)
  83. // 日期排序
  84. for _, v := range list {
  85. formulaSlice = append(formulaSlice, v.Formula)
  86. }
  87. return
  88. }