base_from_calculate.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package services
  2. import (
  3. "github.com/yidane/formula"
  4. "hongze/hongze_edb_lib/models"
  5. "strings"
  6. )
  7. // CheckFormula 检测计算公式是否异常
  8. func CheckFormula(formula string) map[string]string {
  9. mathFormula := []string{"MAX", "MIN", "ABS", "ACOS", "ASIN", "CEIL", "MOD", "POW", "ROUND", "SIGN", "SIN", "TAN", "LOG10", "LOG2", "LOG"}
  10. str := strings.ToUpper(formula)
  11. for _, v := range mathFormula {
  12. str = strings.Replace(str, v, "", -1)
  13. }
  14. str = strings.Replace(str, "(", "", -1)
  15. str = strings.Replace(str, ")", "", -1)
  16. byteMap := make(map[string]string)
  17. for i := 0; i < len(str); i++ {
  18. byteInt := str[i]
  19. if byteInt >= 65 && byteInt <= 90 {
  20. byteStr := string(byteInt)
  21. if _, ok := byteMap[byteStr]; !ok {
  22. byteMap[byteStr] = byteStr
  23. }
  24. }
  25. }
  26. return byteMap
  27. }
  28. // CheckFormula2 校验公式是否正常(比如说除法的分母不能为0之类的,实际上就是用预设的字段数据做一次计算)
  29. func CheckFormula2(edbInfoArr []*models.EdbInfo, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) (ok bool, err error) {
  30. valArr := make(map[int]float64)
  31. for _, v := range edbInfoArr {
  32. valArr[v.EdbInfoId] = 100
  33. }
  34. formulaStr = strings.ToUpper(formulaStr)
  35. formulaFormStr := models.ReplaceFormula(edbInfoArr, valArr, formulaMap, formulaStr, edbInfoIdBytes)
  36. if formulaFormStr == "" {
  37. return
  38. }
  39. expression := formula.NewExpression(formulaFormStr)
  40. _, err = expression.Evaluate()
  41. if err != nil {
  42. } else {
  43. ok = true
  44. }
  45. return
  46. }