@@ -6,6 +6,8 @@ import (
|
||||
"apskel-pos-be/internal/repository"
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
type VoucherProcessor struct {
|
||||
@@ -117,59 +119,20 @@ func (p *VoucherProcessor) GetRandomVouchersByRows(ctx context.Context, req *mod
|
||||
for i, row := range voucherRows {
|
||||
vouchers := make([]models.VoucherSpinResponse, len(row))
|
||||
|
||||
// Select a winner from this row if there are vouchers
|
||||
// Select a random winner from this row if there are vouchers
|
||||
if len(row) > 0 {
|
||||
var winnerIndex int
|
||||
|
||||
if req.WinnerNumber != nil {
|
||||
// If winner_number is specified, try to find a voucher with that winner_number
|
||||
// that is not already a winner, otherwise select any non-winner
|
||||
winnerIndex = -1
|
||||
for j, voucher := range row {
|
||||
if voucher.WinnerNumber == *req.WinnerNumber && !voucher.IsWinner {
|
||||
winnerIndex = j
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If no voucher with specified winner_number found, select any non-winner
|
||||
if winnerIndex == -1 {
|
||||
for j, voucher := range row {
|
||||
if !voucher.IsWinner {
|
||||
winnerIndex = j
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If still no non-winner found, select any voucher
|
||||
if winnerIndex == -1 {
|
||||
winnerIndex = 0
|
||||
}
|
||||
} else {
|
||||
// If no winner_number specified, select any non-winner, otherwise any voucher
|
||||
winnerIndex = -1
|
||||
for j, voucher := range row {
|
||||
if !voucher.IsWinner {
|
||||
winnerIndex = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if winnerIndex == -1 {
|
||||
winnerIndex = 0
|
||||
}
|
||||
}
|
||||
// Select random winner
|
||||
rand.Seed(time.Now().UnixNano() + int64(i)) // Add row index for different seed
|
||||
winnerIndex := rand.Intn(len(row))
|
||||
|
||||
// Mark as winner in database if not already a winner
|
||||
if !row[winnerIndex].IsWinner {
|
||||
err := p.voucherRepo.MarkAsWinner(ctx, row[winnerIndex].ID)
|
||||
if err != nil {
|
||||
// Log error but continue - don't fail the entire request
|
||||
fmt.Printf("Failed to mark voucher %d as winner: %v\n", row[winnerIndex].ID, err)
|
||||
} else {
|
||||
// Update the voucher object to reflect the change
|
||||
row[winnerIndex].IsWinner = true
|
||||
}
|
||||
// Mark as winner in database
|
||||
err := p.voucherRepo.MarkAsWinner(ctx, row[winnerIndex].ID)
|
||||
if err != nil {
|
||||
// Log error but continue - don't fail the entire request
|
||||
fmt.Printf("Failed to mark voucher %d as winner: %v\n", row[winnerIndex].ID, err)
|
||||
} else {
|
||||
// Update the voucher object to reflect the change
|
||||
row[winnerIndex].IsWinner = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user