common/structs/v2/calculate-process.go

57 lines
1.6 KiB
Go
Raw Normal View History

2024-08-05 17:21:58 +08:00
package v2
import (
2024-08-31 16:01:46 +08:00
"fmt"
"strings"
2024-08-05 17:21:58 +08:00
"time"
2024-08-31 16:01:46 +08:00
"github.com/expr-lang/expr"
2024-08-05 17:21:58 +08:00
)
type CalculateProcess struct {
2024-08-27 14:19:31 +08:00
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
2024-08-05 17:21:58 +08:00
//所有人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"`
}
2024-08-31 16:01:46 +08:00
// 计算过程
2024-09-01 14:16:21 +08:00
func (c *CalculateProcess) Run(env map[string]float64) (string, float64) {
2024-08-31 16:01:46 +08:00
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
}
}
2024-09-01 16:28:17 +08:00
program, err := expr.Compile(c.Process, expr.AsFloat64())
2024-08-31 16:01:46 +08:00
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 {
2024-09-01 14:16:21 +08:00
replaceList = append(replaceList, k, fmt.Sprintf("%.2f", v))
2024-08-31 16:01:46 +08:00
}
replacer := strings.NewReplacer(replaceList...)
2024-09-01 14:16:21 +08:00
var resp = output.(float64)
return replacer.Replace(fmt.Sprintf("【%s】 %s = %.2f", c.Name, c.Process, resp)), resp
2024-08-31 16:01:46 +08:00
}