feat 添加计算过程实现

This commit is contained in:
timerzz 2024-08-31 16:01:46 +08:00
parent 6063310bb3
commit adcb9ed31b
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package utils
import (
"strings"
v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2"
)
func CalculateProviderPrice(calculates []v2.CalculateProcess, env map[string]int) (p v2.ProviderPrice) {
var calculateStrings = make([]string, 0, len(calculates))
for _, c := range calculates {
process, price := c.Run(env)
if process != "" {
calculateStrings = append(calculateStrings, process)
if p.FinalPrice == 0 {
p.FinalPrice = price
}
p.FinalPrice = min(p.FinalPrice, price)
}
}
p.CalMark = strings.Join(calculateStrings, "\n")
return
}
func CalculateSellerPrice(calculates []v2.CalculateProcess, env map[string]int) (p v2.SellerPrice) {
var calculateStrings = make([]string, 0, len(calculates))
for _, c := range calculates {
process, price := c.Run(env)
if process != "" {
calculateStrings = append(calculateStrings, process)
if p.FinalPrice == 0 {
p.FinalPrice = price
}
p.FinalPrice = min(p.FinalPrice, price)
}
}
p.CalMark = strings.Join(calculateStrings, "\n")
return
}

View File

@ -1,7 +1,11 @@
package v2
import (
"fmt"
"strings"
"time"
"github.com/expr-lang/expr"
)
type CalculateProcess struct {
@ -19,3 +23,34 @@ type CalculateProcess struct {
// 名称
Name string `json:"name"`
}
// 计算过程
func (c *CalculateProcess) Run(env map[string]int) (string, int) {
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.AsInt())
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", float64(v/100)))
}
replacer := strings.NewReplacer(replaceList...)
var resp = output.(int)
return replacer.Replace(fmt.Sprintf("【%s】 %s = %.2f", c.Name, c.Process, float64(resp/100))), resp
}