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

Update member balance when purchase

parent 74889f9d
No related branches found
No related tags found
No related merge requests found
...@@ -56,11 +56,14 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) { ...@@ -56,11 +56,14 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
} }
total := 0 total := 0
for i, p := range products { for i, p := range products {
if p.ProductCode == 0 {
continue
}
var product Product var product Product
err := a.db.Where("code = ?", p.ProductCode).First(&product).Error err = a.db.Where("code = ?", p.ProductCode).First(&product).Error
if err != nil { if err != nil {
log.Printf("Can't get product %d: %v", p.ProductCode, err) log.Printf("Can't get product %d: %v", p.ProductCode, err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusBadRequest)
return return
} }
...@@ -68,6 +71,14 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) { ...@@ -68,6 +71,14 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
products[i].Price = product.Price products[i].Price = product.Price
} }
err = a.db.Model(&Member{}).
Where("num = ?", num).
Update("balance", gorm.Expr("balance - ?", total)).Error
if err != nil {
log.Printf("Can't update update member balance %d-%d: %v", num, total, err)
w.WriteHeader(http.StatusBadRequest)
return
}
purchase := Purchase{ purchase := Purchase{
MemberNum: num, MemberNum: num,
Date: time.Now(), Date: time.Now(),
...@@ -86,7 +97,7 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) { ...@@ -86,7 +97,7 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
Where("code = ?", p.ProductCode). Where("code = ?", p.ProductCode).
Update("stock", gorm.Expr("stock - ?", p.Ammount)).Error Update("stock", gorm.Expr("stock - ?", p.Ammount)).Error
if err != nil { if err != nil {
log.Printf("Can't update product stock %d: %v", p.ProductCode, err) log.Printf("Can't update product stock %d-%d: %v", p.ProductCode, p.Ammount, err)
} }
} }
......
...@@ -51,4 +51,13 @@ func TestPurchaseAddListMine(t *testing.T) { ...@@ -51,4 +51,13 @@ func TestPurchaseAddListMine(t *testing.T) {
if product.Stock != testProduct.Stock-products[0].Ammount { if product.Stock != testProduct.Stock-products[0].Ammount {
t.Error("Wrong product stock:", product) t.Error("Wrong product stock:", product)
} }
var member Member
resp = tapi.do("GET", "/member/10", nil, &member)
if resp.StatusCode != http.StatusOK {
t.Error("Can't find the member:", resp.Status)
}
if member.Balance != testMember.Balance-(testProduct.Price*products[0].Ammount) {
t.Error("Wrong product balance:", member.Balance)
}
} }
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