diff --git a/structs/utils/profit-rate.go b/structs/utils/profit-rate.go new file mode 100644 index 0000000..e0f75a9 --- /dev/null +++ b/structs/utils/profit-rate.go @@ -0,0 +1,52 @@ +package utils + +import ( + "fmt" + "strconv" + + v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2" +) + +func ProfitRate(article *v2.Article) (after *v2.Article, changed bool) { + // 拿到最低成本价和最低售价 + var cost, sell float64 + //检查能不能购买,只要有一个供应商能买,就认为能购买 + var available bool + + for _, provider := range article.Providers { + final := provider.Cost.FinalPrice + if final > 0 && (final < cost || cost == 0) && !provider.Exclude { + if available && !provider.Available { + // 上个最低价供应商能买,这个供应商不能买,那么即使现在的供应商价格更低,也不使用 + continue + } + cost = final + } + available = available || provider.Available + } + + for _, seller := range article.Sellers { + final := seller.Sell.FinalPrice + if final > 0 && (final < sell || sell == 0) && !seller.Exclude { + sell = final + } + } + // 成本和售价没有改动,不保存,直接返回 + if cost == article.CostPrice && sell == article.SellPrice { + return article, false + } + // 到这里说明成本和售价有变动 + article.CostPrice = Decimal(cost) + article.SellPrice = Decimal(sell) + article.Available = available + if cost > 0 { + article.Rate = Decimal((article.SellPrice - article.CostPrice) * 100 / article.CostPrice) + } + article.GrossProfit = Decimal(article.SellPrice - article.CostPrice) + return article, true +} + +func Decimal(num float64) float64 { + num, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", num), 64) + return num +}