57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package v2
|
||
|
||
import (
|
||
"fmt"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/expr-lang/expr"
|
||
)
|
||
|
||
type CalculateProcess struct {
|
||
ID uint `gorm:"primary_key" json:"id"`
|
||
CreatedAt time.Time `json:"createdAt"`
|
||
UpdatedAt time.Time `json:"updatedAt"`
|
||
//所有人ID
|
||
OwnerID uint `gorm:"index" json:"ownerID"`
|
||
// 所有者类型,是provider还是providerArticle还是Seller还是sellerArticle
|
||
Kind string `gorm:"index" json:"kind"`
|
||
// 条件
|
||
Condition string `json:"condition"`
|
||
// 计算过程
|
||
Process string `json:"process"`
|
||
// 名称
|
||
Name string `json:"name"`
|
||
}
|
||
|
||
// 计算过程
|
||
func (c *CalculateProcess) Run(env map[string]float64) (string, float64) {
|
||
if c.Condition != "" {
|
||
condition, err := expr.Compile(c.Condition, expr.AsBool())
|
||
if err != nil {
|
||
return fmt.Sprintf("【%s】 condition compile error: %v", c.Name, err), 0
|
||
}
|
||
if ok, err := expr.Run(condition, env); err != nil {
|
||
return fmt.Sprintf("【%s】 condition run error: %v", c.Name, err), 0
|
||
} else if !ok.(bool) {
|
||
return "", 0
|
||
}
|
||
}
|
||
program, err := expr.Compile(c.Process, expr.AsFloat64())
|
||
if err != nil {
|
||
return fmt.Sprintf("【%s】 process compile error: %v", c.Name, err), 0
|
||
}
|
||
|
||
output, err := expr.Run(program, env)
|
||
if err != nil {
|
||
return fmt.Sprintf("【%s】 process run error: %v", c.Name, err), 0
|
||
}
|
||
var replaceList = make([]string, 0, 2*len(env))
|
||
for k, v := range env {
|
||
replaceList = append(replaceList, k, fmt.Sprintf("%.2f", v))
|
||
}
|
||
replacer := strings.NewReplacer(replaceList...)
|
||
var resp = output.(float64)
|
||
return replacer.Replace(fmt.Sprintf("【%s】 %s = %.2f", c.Name, c.Process, resp)), resp
|
||
}
|