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

Set the total of purchases negative

parent 57a5cc9c
No related branches found
No related tags found
No related merge requests found
......@@ -40,24 +40,9 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
purchase[i].Price = product.Price
}
var member Member
err = a.db.Where("num = ?", num).Find(&member).Error
if err != nil {
log.Printf("Can't find member %d: %v", num, err)
w.WriteHeader(http.StatusNotAcceptable)
return
}
if member.Balance < total {
log.Printf("Member %d don't have enough money (%d-%d)", num, member.Balance, total)
w.WriteHeader(http.StatusBadRequest)
return
}
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.StatusNotAcceptable)
httpStatus := a.substractMemberBalance(num, total)
if httpStatus != http.StatusOK {
w.WriteHeader(httpStatus)
return
}
......@@ -66,7 +51,7 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
Date: time.Now(),
Purchase: purchase,
Type: "purchase",
Total: total,
Total: -total,
}
err = a.db.Create(&transaction).Error
if err != nil {
......@@ -93,3 +78,24 @@ func (a *api) AddPurchase(num int, w http.ResponseWriter, req *http.Request) {
}
}
func (a *api) substractMemberBalance(num int, total int) int {
var member Member
err := a.db.Where("num = ?", num).Find(&member).Error
if err != nil {
log.Printf("Can't find member %d: %v", num, err)
return http.StatusNotAcceptable
}
if member.Balance < total {
log.Printf("Member %d don't have enough money (%d-%d)", num, member.Balance, total)
return http.StatusBadRequest
}
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)
return http.StatusNotAcceptable
}
return http.StatusOK
}
......@@ -30,7 +30,7 @@ func TestPurchaseAddListMine(t *testing.T) {
if len(transactions) != 1 {
t.Fatal("Wrong number of transactions", len(transactions), transactions)
}
if transactions[0].Total != testProduct.Price*products[0].Ammount {
if transactions[0].Total != -testProduct.Price*products[0].Ammount {
t.Error("Wrong total:", transactions[0].Total)
}
if len(transactions[0].Purchase) != 1 {
......
......@@ -16,7 +16,7 @@ const columns = [
};
}},
{dataField: 'date', text: 'Fecha', formatter: printDate},
{dataField: 'total', text: 'Total', formatter: cell => printMoney(cell)+""},
{dataField: 'total', text: 'Cantidad', formatter: cell => printMoney(cell)+""},
]
function TransactionList() {
......
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