62 lines
1.3 KiB
Go
Raw Normal View History

2017-10-06 10:44:55 +00:00
package shop
import (
"net/http"
"sync"
"github.com/aerogo/aero"
"github.com/animenotifier/arn"
"github.com/animenotifier/notify.moe/utils"
)
var itemBuyMutex sync.Mutex
// BuyItem ...
func BuyItem(ctx *aero.Context) string {
// Lock via mutex to prevent race conditions
itemBuyMutex.Lock()
defer itemBuyMutex.Unlock()
// Logged in user
user := utils.GetUser(ctx)
if user == nil {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusUnauthorized, "Not logged in")
2017-10-06 10:44:55 +00:00
}
// Item ID and quantity
itemID := ctx.Get("item")
quantity, err := ctx.GetInt("quantity")
if err != nil || quantity == 0 {
return ctx.Error(http.StatusBadRequest, "Invalid item quantity", err)
}
2018-03-27 23:59:14 +00:00
item, err := arn.GetShopItem(itemID)
2017-10-06 10:44:55 +00:00
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Error fetching item data", err)
}
// Calculate total price and subtract balance
totalPrice := int(item.Price) * quantity
if user.Balance < totalPrice {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusBadRequest, "Not enough gems. You need to charge up your balance before you can buy this item.")
2017-10-06 10:44:55 +00:00
}
user.Balance -= totalPrice
2017-10-27 07:11:56 +00:00
user.Save()
2017-10-06 10:44:55 +00:00
// Add item to user inventory
inventory := user.Inventory()
inventory.AddItem(itemID, uint(quantity))
2017-10-27 07:11:56 +00:00
inventory.Save()
2017-10-06 10:44:55 +00:00
// Save purchase
2017-10-27 07:11:56 +00:00
purchase := arn.NewPurchase(user.ID, itemID, quantity, int(item.Price), "gem")
purchase.Save()
2017-10-06 10:44:55 +00:00
return "ok"
}