package database import ( "fmt" "gorm.io/gorm" "math" "strings" "time" ) const ( defaultExchangeRate float64 = 7.3 defaultFreight float64 = 100 ) type Product struct { ID uint `gorm:"primary_key" json:"id"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` DeletedAt gorm.DeletedAt `gorm:"index"` Name string `gorm:"index" json:"name"` Pid string `gorm:"unique;not null" json:"pid"` Color string `json:"color"` Link string `json:"link"` Image string `json:"image"` Orderable bool `json:"orderable"` USPrice float64 `json:"usPrice"` CNYPrice float64 `json:"cnyPrice"` CalMark string `json:"calMark"` //计算价格的过程 DWPrice float64 `json:"dwPrice"` Freight float64 `json:"freight"` //运费 ExchangeRate float64 `json:"exchangeRate" gorm:"-"` //汇率 Rate float64 `json:"rate"` //利润率 Remark string `json:"remark"` //备注 HistoryPrices []HistoryPrice `gorm:"foreignKey:Pid;references:Pid" json:"historyPrices"` } func (p *Product) TableName() string { return "products" } func (p *Product) BeforeSave(tx *gorm.DB) (err error) { tx.Model(&Product{}).Where("pid = ?", p.Pid).Pluck("freight", &p.Freight) p.CalRate() var lastPrice float64 tx.Model(&HistoryPrice{}).Where("pid = ?", p.Pid).Order("created_at desc").Limit(1).Pluck("us_price", &lastPrice) if p.USPrice != lastPrice { p.HistoryPrices = append(p.HistoryPrices, HistoryPrice{ USPrice: p.USPrice, }) } return } func (p *Product) CalRate() { calculationProcess := make([]string, 0, 2) //存放计算过程 if p.ExchangeRate == 0 { p.ExchangeRate = defaultExchangeRate } if p.Freight == 0 { p.Freight = defaultFreight } //先计算打九折的价格 tmpPrice := p.USPrice * 0.9 // 这是打九折的价格 p.CNYPrice = tmpPrice*p.ExchangeRate + p.Freight calculationProcess = append(calculationProcess, fmt.Sprintf("【九折】%.2f * 0.9 * %.2f + %.2f = %.2f", p.USPrice, p.ExchangeRate, p.Freight, p.CNYPrice)) if p.USPrice >= 150 { calculationProcess = append(calculationProcess, fmt.Sprintf("【150 -20 】(%.2f - 20) * %.2f + %.2f = %.2f", p.USPrice, p.ExchangeRate, p.Freight, (p.USPrice-20)*p.ExchangeRate+p.Freight)) if p.USPrice-20 < tmpPrice { // 符合满150-20,而且比九折便宜 tmpPrice = p.USPrice - 20 p.CNYPrice = tmpPrice*p.ExchangeRate + p.Freight } } else if p.USPrice >= 100 { calculationProcess = append(calculationProcess, fmt.Sprintf("【100 -10 】(%.2f - 10) * %.2f + %.2f = %.2f", p.USPrice, p.ExchangeRate, p.Freight, (p.USPrice-10)*p.ExchangeRate+p.Freight)) if p.USPrice-10 < tmpPrice { // 符合满100 -10,而且比九折便宜 tmpPrice = p.USPrice - 10 p.CNYPrice = tmpPrice*p.ExchangeRate + p.Freight } } p.CalMark = strings.Join(calculationProcess, "\n") if p.DWPrice > 0 { // 如果有得物价格,就计算收益率 p.Rate = Decimal((p.DWPrice - p.CNYPrice) / p.CNYPrice * 100) } p.CNYPrice = Decimal(p.CNYPrice) } // Decimal 保留两位小数 func Decimal(value float64) float64 { return math.Trunc(value*1e2+0.5) * 1e-2 } type HistoryPrice struct { ID uint `gorm:"primary_key" json:"id"` CreatedAt time.Time `json:"createdAt"` Pid string `gorm:"index" json:"pid"` USPrice float64 `json:"usPrice"` }