approveflow/app/provider/flow_definition/approval_condition.go

48 lines
1.3 KiB
Go

package flow_definition
import (
"encoding/json"
"fmt"
"github.com/Knetic/govaluate"
)
type ApprovalCondition interface {
EvaluateCondition(data map[string]interface{}) (bool, error) // 评估条件表达式
}
type ApprovalConditionCommon struct {
ApprovalCondition `gorm:"-"`
ConditionExpression string `gorm:"type:text" json:"condition_expression"` // 条件表达式
}
func (a *ApprovalConditionCommon) MarshalBinary() ([]byte, error) {
return json.Marshal(a)
}
func (a *ApprovalConditionCommon) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, a)
}
// EvaluateCondition 评估条件表达式
func (a *ApprovalConditionCommon) EvaluateCondition(data map[string]interface{}) (bool, error) {
if a.ConditionExpression == "" {
return true, nil // 空条件,默认满足
}
// 创建可评估的表达式
expression, err := govaluate.NewEvaluableExpression(a.ConditionExpression)
if err != nil {
return false, fmt.Errorf("failed to parse condition expression: %v", err)
}
// 评估表达式
result, err := expression.Evaluate(data)
if err != nil {
return false, fmt.Errorf("failed to evaluate condition: %v", err)
}
// 将结果转换为布尔值
boolResult, ok := result.(bool)
if !ok {
return false, fmt.Errorf("condition expression does not return a boolean value")
}
return boolResult, nil
}