90 lines
1.9 KiB
Go
Raw Normal View History

2017-10-03 13:26:29 +00:00
package shop
import (
"net/http"
2017-10-04 11:39:59 +00:00
"sort"
2017-10-05 11:48:16 +00:00
"sync"
2017-10-03 13:26:29 +00:00
2017-10-04 06:12:12 +00:00
"github.com/animenotifier/arn"
2017-10-03 13:26:29 +00:00
"github.com/aerogo/aero"
"github.com/animenotifier/notify.moe/components"
"github.com/animenotifier/notify.moe/utils"
)
2017-10-05 11:48:16 +00:00
var itemBuyMutex sync.Mutex
2017-10-03 13:26:29 +00:00
// Get shop page.
func Get(ctx *aero.Context) string {
user := utils.GetUser(ctx)
if user == nil {
return ctx.Error(http.StatusUnauthorized, "Not logged in", nil)
}
2017-10-04 11:39:59 +00:00
items, err := arn.AllItems()
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Error fetching shop item data", err)
}
sort.Slice(items, func(i, j int) bool {
return items[i].Order < items[j].Order
})
2017-10-04 06:12:12 +00:00
return ctx.HTML(components.Shop(user, items))
2017-10-03 13:26:29 +00:00
}
2017-10-05 11:48:16 +00:00
// 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 {
return ctx.Error(http.StatusUnauthorized, "Not logged in", nil)
}
// 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)
}
item, err := arn.GetItem(itemID)
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 {
return ctx.Error(http.StatusBadRequest, "Not enough gems", nil)
}
user.Balance -= totalPrice
err = user.Save()
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Error saving user data", err)
}
// Add item to user inventory
inventory := user.Inventory()
inventory.AddItem(itemID, uint(quantity))
err = inventory.Save()
if err != nil {
return ctx.Error(http.StatusInternalServerError, "Error saving inventory", err)
}
return "ok"
}