From 48e37b1dbd04d73e2ddb6b1152e0b1b2c567256c Mon Sep 17 00:00:00 2001 From: meskio <meskio@sindominio.net> Date: Tue, 16 Mar 2021 13:46:50 +0100 Subject: [PATCH] Calculate product price counting with existing stock and price * Closes: #20 --- api/db/inventary.go | 19 ++++++++++++++++++- api/inventary_test.go | 3 ++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/api/db/inventary.go b/api/db/inventary.go index 34b2abd..c78c5d6 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 e34e713..b9521c2 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) } } -- GitLab