68 lines
1.4 KiB
Go
Raw Normal View History

2017-10-06 10:44:55 +00:00
package shop
import (
"net/http"
"sync"
"github.com/aerogo/aero"
2019-06-03 09:32:43 +00:00
"github.com/animenotifier/notify.moe/arn"
2017-10-06 10:44:55 +00:00
"github.com/animenotifier/notify.moe/utils"
)
var itemBuyMutex sync.Mutex
// BuyItem ...
2019-06-01 04:55:49 +00:00
func BuyItem(ctx aero.Context) error {
2017-10-06 10:44:55 +00:00
// 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
}
// Add item to user inventory
inventory := user.Inventory()
2019-06-05 06:45:54 +00:00
err = inventory.AddItem(itemID, uint(quantity))
if err != nil {
return ctx.Error(http.StatusBadRequest, err)
}
2017-10-27 07:11:56 +00:00
inventory.Save()
2017-10-06 10:44:55 +00:00
2019-06-05 06:45:54 +00:00
// Deduct balance
user.Balance -= totalPrice
user.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
2019-06-01 04:55:49 +00:00
return nil
2017-10-06 10:44:55 +00:00
}