diff --git a/api/db/inventary.go b/api/db/inventary.go index 34b2abd0cd3373d203ecfb3e9e2117602f1d58b1..c78c5d645f2d3b5fabb19a04859a86d3de85c2fb 100644 --- a/api/db/inventary.go +++ b/api/db/inventary.go @@ -52,7 +52,11 @@ func (d *DB) AddInventary(num int, inventary *Inventary) error { query = query.Update("stock", gorm.Expr("stock + ?", *product.StockUpdate)) } if product.Price != nil { - query = query.Update("price", *product.Price) + price, err := d.inventaryNewPrice(product) + if err != nil { + return err + } + query = query.Update("price", price) } err := query.Error if err != nil { @@ -64,6 +68,19 @@ func (d *DB) AddInventary(num int, inventary *Inventary) error { }) } +func (d *DB) inventaryNewPrice(product InventaryProduct) (int, error) { + if product.StockUpdate == nil || *product.StockUpdate == 0 { + return *product.Price, nil + } + + existingProduct, err := d.GetProduct(product.ProductCode) + if err != nil { + return 0, err + } + price := ((existingProduct.Price * existingProduct.Stock) + (*product.Price * *product.StockUpdate)) / (existingProduct.Stock + *product.StockUpdate) + return price, nil +} + func (d *DB) GetInventary(id int) (inventary Inventary, err error) { err = d.db.Preload("Products.Product"). Preload(clause.Associations). diff --git a/api/inventary_test.go b/api/inventary_test.go index e34e7136289c58ca811e35d7387f3db69e9860d3..b9521c2398d08034f8736d7b50e1644f9c5f3cb0 100644 --- a/api/inventary_test.go +++ b/api/inventary_test.go @@ -154,7 +154,8 @@ func TestInventaryUpdateBoth(t *testing.T) { if product.Stock != testProduct.Stock+*inventary.Products[0].StockUpdate { t.Error("Wrong stock:", product.Stock) } - if product.Price != *inventary.Products[0].Price { + newPrice := ((price * updateStock) + (testProduct.Price * testProduct.Stock)) / (updateStock + testProduct.Stock) + if product.Price != newPrice { t.Error("Wrong price:", product.Price) } }