coach-spider/product/option.go
timerzz 1ba8b29a77
All checks were successful
Build image / build (push) Successful in 1m7s
fix 修复updateRate会更新其他网站的bug
2024-06-16 10:51:22 +08:00

64 lines
1.8 KiB
Go

package product
import (
productv1 "gitea.timerzz.com/kedaya_haitao/common/model/product"
"gorm.io/gorm"
"time"
)
type Option struct {
ID uint `gorm:"primary_key" json:"id"`
Interval time.Duration `yaml:"interval" json:"interval"`
ExchangeRate float64 `yaml:"exchangeRate" json:"exchangeRate"` //汇率
Freight float64 `yaml:"freight" json:"freight"` //运费
}
func (c *Controller) LoadOption() {
c.db.Where("id = ?", 1).Attrs(Option{Interval: time.Hour * 12, ExchangeRate: 7.3, Freight: 100}).FirstOrCreate(&c.Option)
}
func (c *Controller) SaveOption(opt Option) {
if opt.Interval > 0 {
c.Option.Interval = opt.Interval
}
var change bool
var oldFreight float64
if opt.ExchangeRate > 0 && opt.ExchangeRate != c.Option.ExchangeRate {
c.Option.ExchangeRate = opt.ExchangeRate
change = true
}
if opt.Freight > 0 && opt.Freight != c.Option.Freight {
c.Option.Freight, oldFreight = opt.Freight, c.Option.Freight
change = true
}
opt.ID = 1
c.db.Updates(opt)
if change {
go c.updateRate(oldFreight)
}
}
func (c *Controller) updateRate(oldFreight float64) {
var results []*productv1.Product
c.db.Where("website = ?", productv1.WebSite_US_Coach_Outlet).FindInBatches(&results, 20, func(tx *gorm.DB, batch int) error {
for _, result := range results {
if result.Freight == oldFreight {
result.Freight = c.Option.Freight
}
result.ExchangeRate = c.Option.ExchangeRate
var calculate []productv1.CalculateProcess
c.db.Find(&calculate, "pid = ? AND website = ?", result.Pid, productv1.WebSite_US_Coach_Outlet)
result.CalCNY(append(calculate, c.calculates...))
}
// 保存对当前批记录的修改
tx.Save(&results)
return nil
})
}
func (c *Controller) GetOption() Option {
return c.Option
}