Create wallet, get transaction by id

This commit is contained in:
LittleSheep 2025-01-26 17:48:35 +08:00
parent 4cf3742a75
commit fcf1e61d4a
3 changed files with 52 additions and 0 deletions

View File

@ -9,12 +9,14 @@ func MapAPIs(app *fiber.App, baseURL string) {
{ {
wallet := api.Group("/wallet").Name("Wallet API") wallet := api.Group("/wallet").Name("Wallet API")
{ {
wallet.Post("/me", createWallet)
wallet.Get("/me", getMyWallet) wallet.Get("/me", getMyWallet)
} }
transaction := api.Group("/transaction").Name("Transaction API") transaction := api.Group("/transaction").Name("Transaction API")
{ {
transaction.Get("/me", getTransaction) transaction.Get("/me", getTransaction)
transaction.Get("/:id", getTransactionByID)
} }
} }
} }

View File

@ -39,3 +39,25 @@ func getTransaction(c *fiber.Ctx) error {
"data": transactions, "data": transactions,
}) })
} }
func getTransactionByID(c *fiber.Ctx) error {
id, _ := c.ParamsInt("id", 0)
if err := sec.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(*sec.UserInfo)
var transaction models.Transaction
if err := database.C.Where("id = ?", id).
Preload("Payer").Preload("Payee").
First(&transaction).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if transaction.Payer.AccountID != user.ID && transaction.Payee.AccountID != user.ID {
return fiber.NewError(fiber.StatusForbidden, "you are not related to this transaction")
}
return c.JSON(transaction)
}

View File

@ -1,12 +1,40 @@
package api package api
import ( import (
"errors"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec" "git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"git.solsynth.dev/hypernet/wallet/pkg/internal/database" "git.solsynth.dev/hypernet/wallet/pkg/internal/database"
"git.solsynth.dev/hypernet/wallet/pkg/internal/models" "git.solsynth.dev/hypernet/wallet/pkg/internal/models"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/shopspring/decimal"
"gorm.io/gorm"
) )
func createWallet(c *fiber.Ctx) error {
if err := sec.EnsureGrantedPerm(c, "CreateWallet", true); err != nil {
return err
}
user := c.Locals("user").(*sec.UserInfo)
var wallet models.Wallet
if err := database.C.Where("account_id = ?", user.ID).
First(&wallet).Error; err == nil || errors.Is(err, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusConflict, "wallet already exists")
}
wallet = models.Wallet{
Balance: decimal.NewFromInt(0),
AccountID: user.ID,
}
if err := database.C.Create(&wallet).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(wallet)
}
func getMyWallet(c *fiber.Ctx) error { func getMyWallet(c *fiber.Ctx) error {
if err := sec.EnsureAuthenticated(c); err != nil { if err := sec.EnsureAuthenticated(c); err != nil {
return err return err