Merge branch 'main' into ticket-bet

This commit is contained in:
Samuel Tariku 2025-07-02 19:41:55 +03:00
commit beea3ab54e
11 changed files with 259 additions and 23 deletions

View File

@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS bets (
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_shop_bet BOOLEAN NOT NULL, is_shop_bet BOOLEAN NOT NULL,
outcomes_hash TEXT NOT NULL, outcomes_hash TEXT NOT NULL,
fast_code VARCHAR(10) NOT NULL,
UNIQUE(cashout_id), UNIQUE(cashout_id),
CHECK ( CHECK (
user_id IS NOT NULL user_id IS NOT NULL

View File

@ -10,9 +10,10 @@ INSERT INTO bets (
is_shop_bet, is_shop_bet,
cashout_id, cashout_id,
company_id, company_id,
outcomes_hash outcomes_hash,
fast_code
) )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING *; RETURNING *;
-- name: CreateBetOutcome :copyfrom -- name: CreateBetOutcome :copyfrom
INSERT INTO bet_outcomes ( INSERT INTO bet_outcomes (
@ -93,6 +94,11 @@ WHERE branch_id = $1;
SELECT * SELECT *
FROM bet_with_outcomes FROM bet_with_outcomes
WHERE user_id = $1; WHERE user_id = $1;
-- name: GetBetByFastCode :one
SELECT *
FROM bet_with_outcomes
WHERE fast_code = $1
LIMIT 1;
-- name: GetBetOutcomeByEventID :many -- name: GetBetOutcomeByEventID :many
SELECT * SELECT *
FROM bet_outcomes FROM bet_outcomes

View File

@ -23,10 +23,11 @@ INSERT INTO bets (
is_shop_bet, is_shop_bet,
cashout_id, cashout_id,
company_id, company_id,
outcomes_hash outcomes_hash,
fast_code
) )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash RETURNING id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code
` `
type CreateBetParams struct { type CreateBetParams struct {
@ -41,6 +42,7 @@ type CreateBetParams struct {
CashoutID string `json:"cashout_id"` CashoutID string `json:"cashout_id"`
CompanyID pgtype.Int8 `json:"company_id"` CompanyID pgtype.Int8 `json:"company_id"`
OutcomesHash string `json:"outcomes_hash"` OutcomesHash string `json:"outcomes_hash"`
FastCode string `json:"fast_code"`
} }
func (q *Queries) CreateBet(ctx context.Context, arg CreateBetParams) (Bet, error) { func (q *Queries) CreateBet(ctx context.Context, arg CreateBetParams) (Bet, error) {
@ -56,6 +58,7 @@ func (q *Queries) CreateBet(ctx context.Context, arg CreateBetParams) (Bet, erro
arg.CashoutID, arg.CashoutID,
arg.CompanyID, arg.CompanyID,
arg.OutcomesHash, arg.OutcomesHash,
arg.FastCode,
) )
var i Bet var i Bet
err := row.Scan( err := row.Scan(
@ -74,6 +77,7 @@ func (q *Queries) CreateBet(ctx context.Context, arg CreateBetParams) (Bet, erro
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
) )
return i, err return i, err
} }
@ -115,7 +119,7 @@ func (q *Queries) DeleteBetOutcome(ctx context.Context, betID int64) error {
} }
const GetAllBets = `-- name: GetAllBets :many const GetAllBets = `-- name: GetAllBets :many
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, outcomes SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes FROM bet_with_outcomes
wHERE ( wHERE (
branch_id = $1 branch_id = $1
@ -191,6 +195,7 @@ func (q *Queries) GetAllBets(ctx context.Context, arg GetAllBetsParams) ([]BetWi
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
&i.Outcomes, &i.Outcomes,
); err != nil { ); err != nil {
return nil, err return nil, err
@ -204,7 +209,7 @@ func (q *Queries) GetAllBets(ctx context.Context, arg GetAllBetsParams) ([]BetWi
} }
const GetBetByBranchID = `-- name: GetBetByBranchID :many const GetBetByBranchID = `-- name: GetBetByBranchID :many
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, outcomes SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes FROM bet_with_outcomes
WHERE branch_id = $1 WHERE branch_id = $1
` `
@ -234,6 +239,7 @@ func (q *Queries) GetBetByBranchID(ctx context.Context, branchID pgtype.Int8) ([
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
&i.Outcomes, &i.Outcomes,
); err != nil { ); err != nil {
return nil, err return nil, err
@ -247,7 +253,7 @@ func (q *Queries) GetBetByBranchID(ctx context.Context, branchID pgtype.Int8) ([
} }
const GetBetByCashoutID = `-- name: GetBetByCashoutID :one const GetBetByCashoutID = `-- name: GetBetByCashoutID :one
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, outcomes SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes FROM bet_with_outcomes
WHERE cashout_id = $1 WHERE cashout_id = $1
` `
@ -271,13 +277,46 @@ func (q *Queries) GetBetByCashoutID(ctx context.Context, cashoutID string) (BetW
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
&i.Outcomes,
)
return i, err
}
const GetBetByFastCode = `-- name: GetBetByFastCode :one
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes
WHERE fast_code = $1
LIMIT 1
`
func (q *Queries) GetBetByFastCode(ctx context.Context, fastCode string) (BetWithOutcome, error) {
row := q.db.QueryRow(ctx, GetBetByFastCode, fastCode)
var i BetWithOutcome
err := row.Scan(
&i.ID,
&i.Amount,
&i.TotalOdds,
&i.Status,
&i.FullName,
&i.PhoneNumber,
&i.CompanyID,
&i.BranchID,
&i.UserID,
&i.CashedOut,
&i.CashoutID,
&i.CreatedAt,
&i.UpdatedAt,
&i.IsShopBet,
&i.OutcomesHash,
&i.FastCode,
&i.Outcomes, &i.Outcomes,
) )
return i, err return i, err
} }
const GetBetByID = `-- name: GetBetByID :one const GetBetByID = `-- name: GetBetByID :one
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, outcomes SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes FROM bet_with_outcomes
WHERE id = $1 WHERE id = $1
` `
@ -301,13 +340,14 @@ func (q *Queries) GetBetByID(ctx context.Context, id int64) (BetWithOutcome, err
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
&i.Outcomes, &i.Outcomes,
) )
return i, err return i, err
} }
const GetBetByUserID = `-- name: GetBetByUserID :many const GetBetByUserID = `-- name: GetBetByUserID :many
SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, outcomes SELECT id, amount, total_odds, status, full_name, phone_number, company_id, branch_id, user_id, cashed_out, cashout_id, created_at, updated_at, is_shop_bet, outcomes_hash, fast_code, outcomes
FROM bet_with_outcomes FROM bet_with_outcomes
WHERE user_id = $1 WHERE user_id = $1
` `
@ -337,6 +377,7 @@ func (q *Queries) GetBetByUserID(ctx context.Context, userID pgtype.Int8) ([]Bet
&i.UpdatedAt, &i.UpdatedAt,
&i.IsShopBet, &i.IsShopBet,
&i.OutcomesHash, &i.OutcomesHash,
&i.FastCode,
&i.Outcomes, &i.Outcomes,
); err != nil { ); err != nil {
return nil, err return nil, err

View File

@ -89,6 +89,7 @@ type Bet struct {
UpdatedAt pgtype.Timestamp `json:"updated_at"` UpdatedAt pgtype.Timestamp `json:"updated_at"`
IsShopBet bool `json:"is_shop_bet"` IsShopBet bool `json:"is_shop_bet"`
OutcomesHash string `json:"outcomes_hash"` OutcomesHash string `json:"outcomes_hash"`
FastCode string `json:"fast_code"`
} }
type BetOutcome struct { type BetOutcome struct {
@ -125,6 +126,7 @@ type BetWithOutcome struct {
UpdatedAt pgtype.Timestamp `json:"updated_at"` UpdatedAt pgtype.Timestamp `json:"updated_at"`
IsShopBet bool `json:"is_shop_bet"` IsShopBet bool `json:"is_shop_bet"`
OutcomesHash string `json:"outcomes_hash"` OutcomesHash string `json:"outcomes_hash"`
FastCode string `json:"fast_code"`
Outcomes []BetOutcome `json:"outcomes"` Outcomes []BetOutcome `json:"outcomes"`
} }

View File

@ -53,6 +53,7 @@ type Bet struct {
IsShopBet bool IsShopBet bool
CashedOut bool CashedOut bool
CashoutID string CashoutID string
FastCode string
CreatedAt time.Time CreatedAt time.Time
} }
@ -80,6 +81,7 @@ type GetBet struct {
CashedOut bool CashedOut bool
CashoutID string CashoutID string
Outcomes []BetOutcome Outcomes []BetOutcome
FastCode string
CreatedAt time.Time CreatedAt time.Time
} }
@ -95,6 +97,7 @@ type CreateBet struct {
IsShopBet bool IsShopBet bool
CashoutID string CashoutID string
OutcomesHash string OutcomesHash string
FastCode string
} }
type CreateBetOutcomeReq struct { type CreateBetOutcomeReq struct {

View File

@ -15,3 +15,12 @@ func GenerateOTP() string {
num := 100000 + rand.UintN(899999) num := 100000 + rand.UintN(899999)
return fmt.Sprintf("%d", num) // 6 digit random number [100,000 - 999,999] return fmt.Sprintf("%d", num) // 6 digit random number [100,000 - 999,999]
} }
func GenerateFastCode() string {
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var code string
for i := 0; i < 6; i++ {
code += string(letters[rand.UintN(uint(len(letters)))])
}
return code
}

View File

@ -135,6 +135,7 @@ func convertCreateBet(bet domain.CreateBet) dbgen.CreateBetParams {
}, },
IsShopBet: bet.IsShopBet, IsShopBet: bet.IsShopBet,
CashoutID: bet.CashoutID, CashoutID: bet.CashoutID,
FastCode: bet.FastCode,
} }
} }
@ -281,6 +282,16 @@ func (s *Store) GetBetByUserID(ctx context.Context, UserID int64) ([]domain.GetB
return result, nil return result, nil
} }
func (s *Store) GetBetByFastCode(ctx context.Context, fastcode string) (domain.GetBet, error) {
bet, err := s.queries.GetBetByFastCode(ctx, fastcode)
if err != nil {
return domain.GetBet{}, err
}
return convertDBBetWithOutcomes(bet), nil
}
func (s *Store) GetBetCount(ctx context.Context, UserID int64, outcomesHash string) (int64, error) { func (s *Store) GetBetCount(ctx context.Context, UserID int64, outcomesHash string) (int64, error) {
count, err := s.queries.GetBetCount(ctx, dbgen.GetBetCountParams{ count, err := s.queries.GetBetCount(ctx, dbgen.GetBetCountParams{
UserID: pgtype.Int8{Int64: UserID}, UserID: pgtype.Int8{Int64: UserID},

View File

@ -15,6 +15,7 @@ type BetStore interface {
GetAllBets(ctx context.Context, filter domain.BetFilter) ([]domain.GetBet, error) GetAllBets(ctx context.Context, filter domain.BetFilter) ([]domain.GetBet, error)
GetBetByBranchID(ctx context.Context, BranchID int64) ([]domain.GetBet, error) GetBetByBranchID(ctx context.Context, BranchID int64) ([]domain.GetBet, error)
GetBetByUserID(ctx context.Context, UserID int64) ([]domain.GetBet, error) GetBetByUserID(ctx context.Context, UserID int64) ([]domain.GetBet, error)
GetBetByFastCode(ctx context.Context, fastcode string) (domain.GetBet, error)
GetBetOutcomeByEventID(ctx context.Context, eventID int64, is_filtered bool) ([]domain.BetOutcome, error) GetBetOutcomeByEventID(ctx context.Context, eventID int64, is_filtered bool) ([]domain.BetOutcome, error)
GetBetOutcomeByBetID(ctx context.Context, betID int64) ([]domain.BetOutcome, error) GetBetOutcomeByBetID(ctx context.Context, betID int64) ([]domain.BetOutcome, error)
GetBetCount(ctx context.Context, userID int64, outcomesHash string) (int64, error) GetBetCount(ctx context.Context, userID int64, outcomesHash string) (int64, error)

View File

@ -17,6 +17,7 @@ import (
"time" "time"
"github.com/SamuelTariku/FortuneBet-Backend/internal/domain" "github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
"github.com/SamuelTariku/FortuneBet-Backend/internal/pkgs/helpers"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/branch" "github.com/SamuelTariku/FortuneBet-Backend/internal/services/branch"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/event" "github.com/SamuelTariku/FortuneBet-Backend/internal/services/event"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/odds" "github.com/SamuelTariku/FortuneBet-Backend/internal/services/odds"
@ -207,7 +208,6 @@ func (s *Service) PlaceBet(ctx context.Context, req domain.CreateBetReq, userID
var totalOdds float32 = 1 var totalOdds float32 = 1
for _, outcomeReq := range req.Outcomes { for _, outcomeReq := range req.Outcomes {
fmt.Println("reqq: ", outcomeReq)
newOutcome, err := s.GenerateBetOutcome(ctx, outcomeReq.EventID, outcomeReq.MarketID, outcomeReq.OddID) newOutcome, err := s.GenerateBetOutcome(ctx, outcomeReq.EventID, outcomeReq.MarketID, outcomeReq.OddID)
if err != nil { if err != nil {
s.mongoLogger.Error("failed to generate outcome", s.mongoLogger.Error("failed to generate outcome",
@ -249,6 +249,8 @@ func (s *Service) PlaceBet(ctx context.Context, req domain.CreateBetReq, userID
return domain.CreateBetRes{}, err return domain.CreateBetRes{}, err
} }
fastCode := helpers.GenerateFastCode()
newBet := domain.CreateBet{ newBet := domain.CreateBet{
Amount: domain.ToCurrency(req.Amount), Amount: domain.ToCurrency(req.Amount),
TotalOdds: totalOdds, TotalOdds: totalOdds,
@ -257,6 +259,7 @@ func (s *Service) PlaceBet(ctx context.Context, req domain.CreateBetReq, userID
PhoneNumber: req.PhoneNumber, PhoneNumber: req.PhoneNumber,
CashoutID: cashoutID, CashoutID: cashoutID,
OutcomesHash: outcomesHash, OutcomesHash: outcomesHash,
FastCode: fastCode,
} }
switch role { switch role {
@ -389,7 +392,6 @@ func (s *Service) PlaceBet(ctx context.Context, req domain.CreateBetReq, userID
newBet.UserID = domain.ValidInt64{Value: userID, Valid: true} newBet.UserID = domain.ValidInt64{Value: userID, Valid: true}
newBet.IsShopBet = false newBet.IsShopBet = false
default: default:
s.mongoLogger.Error("unknown role type", s.mongoLogger.Error("unknown role type",
zap.String("role", string(role)), zap.String("role", string(role)),
@ -398,7 +400,6 @@ func (s *Service) PlaceBet(ctx context.Context, req domain.CreateBetReq, userID
return domain.CreateBetRes{}, fmt.Errorf("Unknown Role Type") return domain.CreateBetRes{}, fmt.Errorf("Unknown Role Type")
} }
fmt.Println("Bet is: ", newBet)
bet, err := s.CreateBet(ctx, newBet) bet, err := s.CreateBet(ctx, newBet)
if err != nil { if err != nil {
s.mongoLogger.Error("failed to create bet", s.mongoLogger.Error("failed to create bet",
@ -714,6 +715,14 @@ func (s *Service) GetBetByUserID(ctx context.Context, UserID int64) ([]domain.Ge
return s.betStore.GetBetByUserID(ctx, UserID) return s.betStore.GetBetByUserID(ctx, UserID)
} }
func (s *Service) GetBetOutcomeByBetID(ctx context.Context, UserID int64) ([]domain.BetOutcome, error) {
return s.betStore.GetBetOutcomeByBetID(ctx, UserID)
}
func (s *Service) GetBetByFastCode(ctx context.Context, fastcode string) (domain.GetBet, error) {
return s.betStore.GetBetByFastCode(ctx, fastcode)
}
func (s *Service) GetBetCount(ctx context.Context, UserID int64, outcomesHash string) (int64, error) { func (s *Service) GetBetCount(ctx context.Context, UserID int64, outcomesHash string) (int64, error) {
return s.betStore.GetBetCount(ctx, UserID, outcomesHash) return s.betStore.GetBetCount(ctx, UserID, outcomesHash)
} }

View File

@ -1,6 +1,7 @@
package handlers package handlers
import ( import (
"fmt"
"strconv" "strconv"
"time" "time"
@ -37,6 +38,163 @@ func (h *Handler) CreateBet(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body") return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
} }
res, err := h.CreateBetInternal(c, req, userID, role)
if err != nil {
h.mongoLoggerSvc.Error("Failed to create bet",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
}
h.mongoLoggerSvc.Info("Bet created successfully",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
return response.WriteJSON(c, fiber.StatusOK, "Bet Created", res, nil)
}
// CreateBetWithFastCode godoc
// @Summary Create a bet with fast code
// @Description Creates a bet with fast code
// @Tags bet
// @Accept json
// @Produce json
// @Param createBetWithFastCode body domain.CreateBetReq true "Creates bet"
// @Success 200 {object} domain.BetRes
// @Failure 400 {object} response.APIResponse
// @Failure 500 {object} response.APIResponse
// @Router /sport/bet/fastcode [post]
func (h *Handler) CreateBetWithFastCode(c *fiber.Ctx) error {
userID := c.Locals("user_id").(int64)
role := c.Locals("role").(domain.Role)
var req struct {
FastCode string `json:"fast_code"`
}
if err := c.BodyParser(&req); err != nil {
h.mongoLoggerSvc.Error("Failed to parse CreateBet request",
zap.Int("status_code", fiber.StatusBadRequest),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
}
bet, err := h.betSvc.GetBetByFastCode(c.Context(), req.FastCode)
if err != nil {
h.mongoLoggerSvc.Error("falied to get bet with fast code",
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "falied to get bet with fast code")
}
outcomes, err := h.betSvc.GetBetOutcomeByBetID(c.Context(), bet.ID)
if err != nil {
h.mongoLoggerSvc.Error("falied to get BetOutcomes by BetID",
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "falied to get BetOutcomes by BetID")
}
bet_outcomes := []domain.CreateBetOutcomeReq{}
for _, outcome := range outcomes {
bet_outcomes = append(bet_outcomes, domain.CreateBetOutcomeReq{
EventID: outcome.EventID,
OddID: outcome.OddID,
MarketID: outcome.MarketID,
})
}
user, err := h.userSvc.GetUserByID(c.Context(), userID)
if err != nil {
h.mongoLoggerSvc.Error("falied to get user information",
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "falied to get user information")
}
branch, err := h.branchSvc.GetBranchByID(c.Context(), user.CompanyID.Value)
if err != nil {
h.mongoLoggerSvc.Error("falied to get branch of user",
zap.Int("status_code", fiber.StatusInternalServerError),
zap.Error(err),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "falied to get branch of user")
}
newReq := domain.CreateBetReq{
Amount: float32(bet.Amount),
Status: bet.Status,
Outcomes: bet_outcomes,
BranchID: &branch.ID,
FullName: user.FirstName,
PhoneNumber: user.PhoneNumber,
}
res, err := h.CreateBetInternal(c, newReq, userID, role)
if err != nil {
h.mongoLoggerSvc.Error("Failed to create bet",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Failed to create bet")
}
wallets, err := h.walletSvc.GetWalletsByUser(c.Context(), bet.UserID.Value)
var staticWallet domain.Wallet
var staticFound bool
for _, wallet := range wallets {
if !wallet.IsWithdraw {
staticWallet = wallet
staticFound = true
break
}
}
if err != nil || staticFound == false {
fmt.Println("wallet error: ", err)
h.mongoLoggerSvc.Error("Failed to get static wallet of user",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", user.ID),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Failed to get wallets of user")
}
// amount added for fast code owner can be fetched from settings in db
amount := domain.Currency(100)
_, err = h.walletSvc.AddToWallet(c.Context(), staticWallet.ID, amount, domain.ValidInt64{}, domain.TRANSFER_DIRECT, domain.PaymentDetails{})
if err != nil {
h.mongoLoggerSvc.Error("Failed to add reward to static bet",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
return fiber.NewError(fiber.StatusBadRequest, "Failed to add reward to static bet")
}
h.mongoLoggerSvc.Info("Bet created successfully",
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
return response.WriteJSON(c, fiber.StatusOK, "Bet Created", res, nil)
}
func (h *Handler) CreateBetInternal(c *fiber.Ctx, req domain.CreateBetReq, userID int64, role domain.Role) (domain.CreateBetRes, error) {
valErrs, ok := h.validator.Validate(c, req) valErrs, ok := h.validator.Validate(c, req)
if !ok { if !ok {
h.mongoLoggerSvc.Error("CreateBet validation failed", h.mongoLoggerSvc.Error("CreateBet validation failed",
@ -44,7 +202,7 @@ func (h *Handler) CreateBet(c *fiber.Ctx) error {
zap.Any("validation_errors", valErrs), zap.Any("validation_errors", valErrs),
zap.Time("timestamp", time.Now()), zap.Time("timestamp", time.Now()),
) )
return response.WriteJSON(c, fiber.StatusBadRequest, "Invalid request", valErrs, nil) return domain.CreateBetRes{}, fmt.Errorf("%s", valErrs)
} }
res, err := h.betSvc.PlaceBet(c.Context(), req, userID, role) res, err := h.betSvc.PlaceBet(c.Context(), req, userID, role)
@ -57,19 +215,13 @@ func (h *Handler) CreateBet(c *fiber.Ctx) error {
switch err { switch err {
case bet.ErrEventHasBeenRemoved, bet.ErrEventHasNotEnded, bet.ErrRawOddInvalid, wallet.ErrBalanceInsufficient: case bet.ErrEventHasBeenRemoved, bet.ErrEventHasNotEnded, bet.ErrRawOddInvalid, wallet.ErrBalanceInsufficient:
return fiber.NewError(fiber.StatusBadRequest, err.Error()) return domain.CreateBetRes{}, fiber.NewError(fiber.StatusBadRequest, err.Error())
} }
return fiber.NewError(fiber.StatusInternalServerError, "Unable to create bet") return domain.CreateBetRes{}, fiber.NewError(fiber.StatusInternalServerError, "Unable to create bet")
} }
h.mongoLoggerSvc.Info("Bet created successfully", return res, nil
zap.Int("status_code", fiber.StatusOK),
zap.Int64("user_id", userID),
zap.Time("timestamp", time.Now()),
)
return response.WriteJSON(c, fiber.StatusOK, "Bet Created", res, nil)
} }
// RandomBet godoc // RandomBet godoc

View File

@ -196,6 +196,7 @@ func (a *App) initAppRoutes() {
// Bet Routes // Bet Routes
a.fiber.Post("/sport/bet", a.authMiddleware, h.CreateBet) a.fiber.Post("/sport/bet", a.authMiddleware, h.CreateBet)
a.fiber.Post("/sport/bet/fastcode", a.authMiddleware, h.CreateBetWithFastCode)
a.fiber.Get("/sport/bet", a.authMiddleware, h.GetAllBet) a.fiber.Get("/sport/bet", a.authMiddleware, h.GetAllBet)
a.fiber.Get("/sport/bet/:id", h.GetBetByID) a.fiber.Get("/sport/bet/:id", h.GetBetByID)
a.fiber.Get("/sport/bet/cashout/:id", a.authMiddleware, h.GetBetByCashoutID) a.fiber.Get("/sport/bet/cashout/:id", a.authMiddleware, h.GetBetByCashoutID)