Skip to content
Snippets Groups Projects
Unverified Commit 48e37b1d authored by meskio's avatar meskio :tent:
Browse files

Calculate product price counting with existing stock and price

* Closes: #20
parent 802af4f8
No related branches found
No related tags found
No related merge requests found
...@@ -52,7 +52,11 @@ func (d *DB) AddInventary(num int, inventary *Inventary) error { ...@@ -52,7 +52,11 @@ func (d *DB) AddInventary(num int, inventary *Inventary) error {
query = query.Update("stock", gorm.Expr("stock + ?", *product.StockUpdate)) query = query.Update("stock", gorm.Expr("stock + ?", *product.StockUpdate))
} }
if product.Price != nil { 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 err := query.Error
if err != nil { if err != nil {
...@@ -64,6 +68,19 @@ func (d *DB) AddInventary(num int, inventary *Inventary) error { ...@@ -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) { func (d *DB) GetInventary(id int) (inventary Inventary, err error) {
err = d.db.Preload("Products.Product"). err = d.db.Preload("Products.Product").
Preload(clause.Associations). Preload(clause.Associations).
......
...@@ -154,7 +154,8 @@ func TestInventaryUpdateBoth(t *testing.T) { ...@@ -154,7 +154,8 @@ func TestInventaryUpdateBoth(t *testing.T) {
if product.Stock != testProduct.Stock+*inventary.Products[0].StockUpdate { if product.Stock != testProduct.Stock+*inventary.Products[0].StockUpdate {
t.Error("Wrong stock:", product.Stock) 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) t.Error("Wrong price:", product.Price)
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment