Compare commits

...
Author SHA1 Message Date
Edd e89b60c844 Admin platform, with users, transactions, games and admin creation 2026-01-02 16:17:55 +00:00
AfonsoCMSousa b9df0a4d4a Merge pull request 'fix:websocket errors & polict change' (#92) from fix/websocket-errors into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/92
Reviewed-by: Edd <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2026-01-02 14:29:39 +00:00
FernandoJVideira 3a7b1b9794 fix:websocket errors & polict change 2026-01-02 14:26:54 +00:00
AfonsoCMSousa ef277a3cfd Merge pull request 'Issues Websockets #48 #49 #51 e #54' (#91) from feature/websockets-game-continue into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/91
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2026-01-02 13:33:21 +00:00
KZix e23ca3d1ff Issues Websockets #48 #49 #51 e #54 2026-01-02 13:24:20 +00:00
FernandoJVideira bcdf542606 Merge pull request 'Created statistics personal and general' (#90) from feature/statistics into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/90
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2026-01-01 12:34:40 +00:00
Edd 16f8d3bdfc Created statistics personal and general 2025-12-31 23:57:54 +00:00
AfonsoCMSousa 45d8aa0035 Merge pull request 'Implemented coin purchase-flow' (#89) from feature/coin-purchase into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/89
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2025-12-31 22:41:09 +00:00
Edd c0af76abd3 Implemented coin purchase-flow 2025-12-31 18:28:29 +00:00
FernandoJVideira ff16a57a97 Merge pull request 'Bugfix: Added api logic with transactions when match is finished, started and joined' (#88) from bugfix/matches-transactions into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/88
Reviewed-by: Edd <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-31 15:54:20 +00:00
KZix cf238d5451 Added api logic with transactions when match is finished, started and joined 2025-12-31 15:48:24 +00:00
Edd 50ae1b7f1f Merge pull request 'Added endpoint to create tranasactions' (#87) from feature/api-coinpurchase into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/87
Reviewed-by: Edd <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-31 11:07:11 +00:00
KZix 5975208877 Added endpoint to create tranasactions 2025-12-31 01:13:27 +00:00
KZix f3e8ffc400 Merge pull request 'matches and transactions history fully operational' (#86) from na/fix-histories into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/86
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: KZix <[email protected]>
2025-12-31 00:31:59 +00:00
Edd 1b03558f93 matches and transactions history fully operational 2025-12-31 00:16:14 +00:00
AfonsoCMSousa 881a60a388 Merge pull request 'feature/api-adminstats-transactions' (#85) from feature/api-adminstats-transactions into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/85
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2025-12-30 19:24:49 +00:00
KZix cf3ca26382 removed comments on code 2025-12-30 19:17:49 +00:00
KZix 58e6615876 Merge branch 'develop' into feature/api-adminstats-transactions 2025-12-30 19:02:09 +00:00
KZix 9bfa06b1ce Added endpoint to get authenticated user's transactions 2025-12-30 19:01:02 +00:00
Edd 2a438dce26 Merge pull request 'feat: api users change password endpoint' (#84) from feature/api-update-password into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/84
Reviewed-by: KZix <[email protected]>
Reviewed-by: Edd <[email protected]>
2025-12-30 17:17:06 +00:00
KZix f38f08923f Added transaction details for the logged user 2025-12-30 16:13:46 +00:00
KZix 5f845b2ba7 Added routes, admin statistics to the controller and added models for coin transaction and coin transaction type 2025-12-30 16:08:53 +00:00
FernandoJVideira 54b4fc7cb1 feat: api users change password endpoint 2025-12-30 10:55:46 +00:00
KZix 3d23627433 Merge pull request 'register, coin balance, game history and transactions mockup' (#83) from na/history-and-register into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/83
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: KZix <[email protected]>
2025-12-30 10:24:15 +00:00
Edd 4f391e3638 histories are a little messed, will change the logic in the future (techdebt) 2025-12-30 01:49:39 +00:00
FernandoJVideira c456c9482f Merge pull request 'feature/api-stats' (#82) from feature/api-stats into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/82
Reviewed-by: Edd <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-29 19:08:47 +00:00
40 changed files with 2927 additions and 402 deletions
+9 -1
View File
@@ -58,12 +58,20 @@ class AuthController extends Controller
return response()->json(['message' => 'Nickname already registered'], 409); return response()->json(['message' => 'Nickname already registered'], 409);
} }
$avatarFilename = null;
if ($request->hasFile('photo_avatar_filename')) {
$file = $request->file('photo_avatar_filename');
$path = $file->store('photos_avatars', 'public');
$avatarFilename = basename($path);
}
$user = User::create([ $user = User::create([
'email' => $request->email, 'email' => $request->email,
'nickname' => $request->nickname, 'nickname' => $request->nickname,
'name' => $request->name, 'name' => $request->name,
'password' => bcrypt($request->password), 'password' => bcrypt($request->password),
'photo_avatar_filename' => $request->photo, 'photo_avatar_filename' => $avatarFilename,
'type' => 'P', 'type' => 'P',
'blocked' => false, 'blocked' => false,
'coins_balance' => 10, 'coins_balance' => 10,
@@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\CoinPurchase;
use App\Models\CoinTransaction;
use App\Models\CoinTransactionType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CoinPurchaseController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'euros' => 'required|numeric|min:1|max:100',
'payment_type' => 'required|in:MBWAY,MB,VISA,PAYPAL',
'payment_reference' => [
'required',
function ($attribute, $value, $fail) use ($request) {
$type = $request->payment_type;
$regex = null;
switch ($type) {
case 'MBWAY': $regex = '/^9[0-9]{8}$/'; break;
case 'MB': $regex = '/^[0-9]{5}-[0-9]{9}$/'; break;
case 'VISA': $regex = '/^4[0-9]{15}$/'; break;
case 'PAYPAL':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$fail("Invalid PayPal email.");
}
return;
}
if ($regex && !preg_match($regex, $value)) {
$fail("Invalid format for $type.");
}
},
],
]);
$user = $request->user();
$coinsAmount = $validated['euros'] * 10;
return DB::transaction(function () use ($user, $validated, $coinsAmount) {
$type = CoinTransactionType::firstOrCreate(['name' => 'Coin purchase'], ['type' => 'C']);
$transaction = CoinTransaction::create([
'user_id' => $user->id,
'coin_transaction_type_id' => $type->id,
'transaction_datetime' => now(),
'coins' => $coinsAmount,
]);
$purchase = CoinPurchase::create([
'purchase_datetime' => now(),
'user_id' => $user->id,
'coin_transaction_id' => $transaction->id,
'euros' => $validated['euros'],
'payment_type' => $validated['payment_type'],
'payment_reference' => $validated['payment_reference'],
]);
$user->increment('coins_balance', $coinsAmount);
return response()->json([
'message' => 'Purchase successful',
'balance' => $user->coins_balance,
'transaction_id' => $transaction->id,
'purchase' => $purchase,
], 201);
});
}
}
@@ -4,9 +4,7 @@ namespace App\Http\Controllers;
use App\Models\Game; use App\Models\Game;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\StoreGameRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use App\Models\MatchGame;
class GameController extends Controller class GameController extends Controller
{ {
@@ -19,15 +17,12 @@ class GameController extends Controller
$user = Auth::user(); $user = Auth::user();
$query = Game::query()->with(["winner", "player1", "player2"]); $query = Game::query()->with(["winner", "player1", "player2"]);
// Filter games based on user type
if ($user->type !== 'A') { if ($user->type !== 'A') {
// Players can only see games they participate in
$query->where(function ($q) use ($user) { $query->where(function ($q) use ($user) {
$q->where('player1_user_id', $user->id) $q->where('player1_user_id', $user->id)
->orWhere('player2_user_id', $user->id); ->orWhere('player2_user_id', $user->id);
}); });
} }
// Admins see all games (no filter needed)
if ($request->has("type") && in_array($request->type, ["3", "9"])) { if ($request->has("type") && in_array($request->type, ["3", "9"])) {
$query->where("type", $request->type); $query->where("type", $request->type);
+87 -22
View File
@@ -4,9 +4,12 @@ namespace App\Http\Controllers;
use App\Models\MatchGame; use App\Models\MatchGame;
use App\Models\Game; use App\Models\Game;
use App\Models\CoinTransaction;
use App\Models\CoinTransactionType;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\StoreMatchRequest; use App\Http\Requests\StoreMatchRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class MatchController extends Controller class MatchController extends Controller
{ {
@@ -30,42 +33,59 @@ class MatchController extends Controller
public function store(StoreMatchRequest $request) public function store(StoreMatchRequest $request)
{ {
$validated = $request->validated(); $validated = $request->validated();
$user = Auth::user(); $user = $request->user();
$stake = $validated['stake'];
if ($user->coins_balance < $stake) {
return response()->json(['message' => 'Insufficient coin balance'], 400);
}
$activeMatch = MatchGame::where(function ($q) use ($user) { $activeMatch = MatchGame::where(function ($q) use ($user) {
$q->where('player1_user_id', $user->id) $q->where('player1_user_id', $user->id)
->orWhere('player2_user_id', $user->id); ->orWhere('player2_user_id', $user->id);
})->whereIn('status', ['Pending', 'Playing'])->exists(); })->whereIn('status', ['Pending', 'Playing'])->exists();
$activeGame = Game::where(function ($q) use ($user) { if ($activeMatch) {
$q->where('player1_user_id', $user->id) return response()->json(['message' => 'You already have an active match.'], 400);
->orWhere('player2_user_id', $user->id);
})->whereIn('status', ['Pending', 'Playing'])->exists();
if ($activeMatch || $activeGame) {
return response()->json(['message' => 'You already have an active game or match.'], 400);
} }
return DB::transaction(function () use ($validated, $user, $stake) {
$GHOST_ID = 1;
$user->decrement('coins_balance', $stake);
$stakeType = CoinTransactionType::firstOrCreate(
['name' => 'Match stake'],
['type' => 'D'] // Debit
);
$match = MatchGame::create([ $match = MatchGame::create([
'type' => $validated['type'], 'type' => $validated['type'],
'status' => 'Pending', 'status' => 'Pending',
'player1_user_id' => $user->id, 'player1_user_id' => $user->id,
'player2_user_id' => $user->id, 'player2_user_id' => $GHOST_ID,
'winner_user_id' => $user->id, 'winner_user_id' => $GHOST_ID,
'loser_user_id' => $user->id, 'loser_user_id' => $GHOST_ID,
'stake' => $validated['stake'], 'stake' => $stake,
'began_at' => now(), 'began_at' => now(),
'player1_marks' => 0, 'player1_marks' => 0, 'player2_marks' => 0,
'player2_marks' => 0, 'player1_points' => 0, 'player2_points' => 0,
'player1_points' => 0, ]);
'player2_points' => 0,
'custom' => null CoinTransaction::create([
'user_id' => $user->id,
'match_id' => $match->id,
'coin_transaction_type_id' => $stakeType->id,
'transaction_datetime' => now(),
'coins' => -$stake,
]); ]);
return response()->json([ return response()->json([
'message' => 'Match created successfully', 'message' => 'Match created successfully',
'match' => $match 'match' => $match,
'balance' => $user->coins_balance
], 201); ], 201);
});
} }
public function show(MatchGame $match) public function show(MatchGame $match)
@@ -76,16 +96,19 @@ class MatchController extends Controller
public function join(MatchGame $match) public function join(MatchGame $match)
{ {
$user = Auth::user(); $user = request()->user();
if ($match->player1_user_id == $user->id) { if ($match->player1_user_id == $user->id) {
return response()->json(['message' => 'Waiting for opponent...', 'match' => $match]); return response()->json(['message' => 'You cannot join your own match'], 400);
} }
if ($match->status !== 'Pending') { if ($match->status !== 'Pending') {
return response()->json(['message' => 'Match is full or started'], 400); return response()->json(['message' => 'Match is full or started'], 400);
} }
if ($user->coins_balance < $match->stake) {
return response()->json(['message' => 'Insufficient coin balance to join this match'], 400);
}
$activeMatch = MatchGame::where(function ($q) use ($user) { $activeMatch = MatchGame::where(function ($q) use ($user) {
$q->where('player1_user_id', $user->id) $q->where('player1_user_id', $user->id)
->orWhere('player2_user_id', $user->id); ->orWhere('player2_user_id', $user->id);
@@ -95,6 +118,22 @@ class MatchController extends Controller
return response()->json(['message' => 'You are already in another active match.'], 400); return response()->json(['message' => 'You are already in another active match.'], 400);
} }
return DB::transaction(function () use ($match, $user) {
$user->decrement('coins_balance', $match->stake);
$stakeType = CoinTransactionType::firstOrCreate(
['name' => 'Match stake'],
['type' => 'D']
);
CoinTransaction::create([
'user_id' => $user->id,
'match_id' => $match->id,
'coin_transaction_type_id' => $stakeType->id,
'transaction_datetime' => now(),
'coins' => -$match->stake,
]);
$match->update([ $match->update([
'status' => 'Playing', 'status' => 'Playing',
'player2_user_id' => $user->id 'player2_user_id' => $user->id
@@ -102,8 +141,10 @@ class MatchController extends Controller
return response()->json([ return response()->json([
'message' => 'Joined match successfully!', 'message' => 'Joined match successfully!',
'match' => $match 'match' => $match,
'balance' => $user->coins_balance
]); ]);
});
} }
public function update(Request $request, MatchGame $match) public function update(Request $request, MatchGame $match)
@@ -123,12 +164,36 @@ class MatchController extends Controller
'total_time' => 'numeric' 'total_time' => 'numeric'
]); ]);
return DB::transaction(function () use ($match, $data) {
if (isset($data['status']) && $data['status'] === 'Ended') { if (isset($data['status']) && $data['status'] === 'Ended') {
$data['ended_at'] = now(); $data['ended_at'] = now();
} }
$match->update($data); $match->update($data);
if ($match->status === 'Ended' && $match->stake > 0 && $match->winner_user_id) {
$payoutType = CoinTransactionType::firstOrCreate(
['name' => 'Match payout'],
['type' => 'C'] // Credit
);
$totalPrize = $match->stake * 2;
CoinTransaction::create([
'user_id' => $match->winner_user_id,
'match_id' => $match->id,
'coin_transaction_type_id' => $payoutType->id,
'transaction_datetime' => now(),
'coins' => $totalPrize,
]);
$match->winner->increment('coins_balance', $totalPrize);
}
return response()->json($match); return response()->json($match);
});
} }
} }
@@ -7,6 +7,7 @@ use App\Models\Game;
use App\Models\User; use App\Models\User;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use App\Models\CoinTransaction;
class StatisticsController extends Controller class StatisticsController extends Controller
{ {
@@ -28,16 +29,23 @@ class StatisticsController extends Controller
{ {
$type = $request->query('type'); $type = $request->query('type');
$query = User::where('type', 'P') $leaderboard = User::where('type', 'P')
->withCount(['wonGames' => function ($query) use ($type) { ->withCount(['wonGames' => function ($query) use ($type) {
if ($type) { if ($type) {
$query->where('type', $type); $query->where('type', $type);
} }
}]) }])
->orderBy('won_games_count', 'desc') ->orderBy('won_games_count', 'desc')
->take(10); ->paginate(10);
$leaderboard = $query->get(['id', 'nickname', 'photo_avatar_filename']); $leaderboard->through(function ($user) {
return [
'id' => $user->id,
'nickname' => $user->nickname,
'photo_avatar_filename' => $user->photo_avatar_filename,
'won_games_count' => $user->won_games_count,
];
});
return response()->json($leaderboard); return response()->json($leaderboard);
} }
@@ -73,4 +81,56 @@ class StatisticsController extends Controller
'current_balance' => $user->coins_balance, // Extra info 'current_balance' => $user->coins_balance, // Extra info
]); ]);
} }
public function getAdminStats()
{
$totalPlayers = User::where('type', 'P')->count();
$totalGames = Game::count();
$totalBlockedUsers = User::where('blocked', true)->count();
$gamesByType = Game::select('type', DB::raw('count(*) as total'))
->groupBy('type')
->get();
$gamesPerMonth = Game::select(
DB::raw("strftime('%Y-%m', began_at) as month"),
DB::raw('count(*) as total')
)
->whereNotNull('began_at')
->groupBy('month')
->orderBy('month', 'desc')
->limit(12)
->get();
$totalCoinsPurchased = \App\Models\CoinTransaction::whereHas('type', function($q) {
$q->where('name', 'Coin purchase');
})
->sum('coins');
$purchasesPerMonth = \App\Models\CoinTransaction::join('coin_transaction_types', 'coin_transactions.coin_transaction_type_id', '=', 'coin_transaction_types.id')
->where('coin_transaction_types.name', 'Coin purchase')
->select(
DB::raw("strftime('%Y-%m', coin_transactions.transaction_datetime) as month"),
DB::raw('SUM(coin_transactions.coins) as total_coins')
)
->groupBy('month')
->orderBy('month', 'desc')
->limit(12)
->get();
return response()->json([
'global_counters' => [
'total_players' => $totalPlayers,
'total_games' => $totalGames,
'blocked_users' => $totalBlockedUsers,
'total_coins_purchased' => (int) $totalCoinsPurchased,
],
'charts' => [
'games_by_type' => $gamesByType,
'games_per_month' => $gamesPerMonth,
'purchases_per_month' => $purchasesPerMonth,
]
]);
}
} }
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use App\Models\CoinTransaction;
use Illuminate\Http\Request;
class TransactionController extends Controller
{
public function index(Request $request)
{
$this->authorize('viewAny', CoinTransaction::class);
$query = CoinTransaction::with('user:id,nickname,email', 'type:id,name');
if ($request->has('sort_coins')) {
$direction = $request->get('sort_coins') === 'asc' ? 'asc' : 'desc';
$query->orderBy('coins', $direction);
}
$dateDirection = $request->get('sort_datetime') === 'asc' ? 'asc' : 'desc';
$query->orderBy('transaction_datetime', $dateDirection);
$transactions = $query->paginate(15);
return response()->json($transactions);
}
}
+115 -9
View File
@@ -21,11 +21,14 @@ class UserController extends Controller
$query = User::query(); $query = User::query();
// Filtros úteis para o Backoffice
if ($request->has('type')) { if ($request->has('type')) {
$query->where('type', $request->type); $query->where('type', $request->type);
} }
if ($request->has('blocked')) {
$query->where('blocked', $request->type);
}
if ($request->has('search')) { if ($request->has('search')) {
$query->where(function ($q) use ($request) { $query->where(function ($q) use ($request) {
$q->where('name', 'like', '%'.$request->search.'%') $q->where('name', 'like', '%'.$request->search.'%')
@@ -47,7 +50,6 @@ class UserController extends Controller
$validated = $request->validate([ $validated = $request->validate([
'name' => 'required|string|max:255', 'name' => 'required|string|max:255',
'nickname' => 'required|string|max:20|unique:users,nickname',
'email' => 'required|email|unique:users,email', 'email' => 'required|email|unique:users,email',
'password' => 'required|string|min:3', 'password' => 'required|string|min:3',
'type' => 'required|in:A,U', 'type' => 'required|in:A,U',
@@ -127,6 +129,28 @@ class UserController extends Controller
return response()->json($user); return response()->json($user);
} }
public function updatePassword(Request $request, User $user)
{
$this->authorize('update', $user);
$validated = $request->validate([
'current_password' => 'required|string',
'new_password' => 'required|string|min:3|confirmed',
]);
// Verificar se a password atual está correta
if (!Hash::check($validated['current_password'], $user->password)) {
return response()->json(['message' => 'Current password is incorrect'], 403);
}
// Atualizar para a nova password
$user->password = Hash::make($validated['new_password']);
$user->save();
return response()->json(['message' => 'Password updated successfully']);
}
/** /**
* DELETE /api/users/{user} * DELETE /api/users/{user}
* Apagar conta (Soft Delete) * Apagar conta (Soft Delete)
@@ -161,15 +185,64 @@ class UserController extends Controller
{ {
$this->authorize('view', $user); $this->authorize('view', $user);
$matches = Game::query() $outcomeSql = "CASE
WHEN is_draw = 1 THEN 'DRAW'
WHEN winner_user_id = {$user->id} THEN 'WIN'
ELSE 'LOSS'
END";
$query = Game::query()
->select('*')
->selectRaw("($outcomeSql) as outcome_text")
->where(function ($q) use ($user) { ->where(function ($q) use ($user) {
$q->where('player1_user_id', $user->id)->orWhere( $q->where('player1_user_id', $user->id)
'player2_user_id', ->orWhere('player2_user_id', $user->id);
$user->id,
);
}) })
->with(['winner', 'player1', 'player2']) ->with(['winner', 'player1', 'player2']);
->orderBy('began_at', 'desc')
if ($request->has('type')) {
$query->where('type', $request->type);
}
if ($request->has('status')) {
$query->where('status', $request->status);
}
if ($request->filled('outcome')) {
switch ($request->outcome) {
case 'win':
$query->where('winner_user_id', $user->id)
->where('is_draw', 0);
break;
case 'loss':
case 'forfeit': // Forfeit treated as loss for now
$query->where('loser_user_id', $user->id)
->where('is_draw', 0);
break;
case 'draw':
$query->where('is_draw', 1);
break;
}
}
if ($request->has('date_from')) {
$query->whereDate('began_at', '>=', $request->date_from);
}
if ($request->has('date_to')) {
$query->whereDate('ended_at', '<=', $request->date_to);
}
$order = $request->get('sort_by', 'began_at');
$direction = $request->get('sort_direction', 'desc');
if ($order === 'outcome') {
$query->orderBy('outcome_text', $direction);
} else {
$query->orderBy($order, $direction);
}
$matches = $query->orderBy($order, $direction)
->paginate(10); ->paginate(10);
return response()->json($matches); return response()->json($matches);
@@ -197,4 +270,37 @@ class UserController extends Controller
return response()->json(['message' => 'User unblocked successfully']); return response()->json(['message' => 'User unblocked successfully']);
} }
public function getTransactions(Request $request, User $user)
{
if ($request->user()->id !== $user->id && $request->user()->type !== 'A') {
return response()->json(['message' => 'Forbidden'], 403);
}
$query = $user->transactions()->with('type');
if ($request->has('type')) {
$query->whereHas('type', function ($q) use ($request) {
$q->where('type', $request->type);
});
}
if ($request->has('date_from')) {
$query->whereDate('transaction_datetime', '>=', $request->date_from);
}
if ($request->has('date_to')) {
$query->whereDate('transaction_datetime', '<=', $request->date_to);
}
$transactions = $query->orderBy('transaction_datetime', 'desc')
->paginate(10);
return response()->json($transactions);
}
public function getMyTransactions(Request $request)
{
return $this->getTransactions($request, $request->user());
}
} }
+1 -1
View File
@@ -26,7 +26,7 @@ class RegisterRequest extends FormRequest
'nickname' => 'required|string|max:255', 'nickname' => 'required|string|max:255',
'name' => 'required|string|max:255', 'name' => 'required|string|max:255',
'password' => 'required|string|min:3', 'password' => 'required|string|min:3',
'photo' => 'nullable|string', 'photo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
]; ];
} }
} }
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CoinPurchase extends Model
{
use HasFactory;
protected $table = 'coin_purchases';
public $timestamps = false;
protected $fillable = [
'purchase_datetime',
'user_id',
'coin_transaction_id',
'euros',
'payment_type',
'payment_reference',
'custom'
];
protected $casts = [
'purchase_datetime' => 'datetime',
'custom' => 'array',
];
public function transaction()
{
return $this->belongsTo(CoinTransaction::class, 'coin_transaction_id');
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CoinTransaction extends Model
{
use HasFactory;
protected $table = 'coin_transactions';
public $timestamps = false;
protected $fillable = [
'transaction_datetime',
'user_id',
'match_id',
'game_id',
'coin_transaction_type_id',
'coins',
'custom'
];
protected $casts = [
'transaction_datetime' => 'datetime',
'custom' => 'array',
];
public function type()
{
return $this->belongsTo(CoinTransactionType::class, 'coin_transaction_type_id');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class CoinTransactionType extends Model
{
use HasFactory, SoftDeletes;
protected $table = 'coin_transaction_types';
protected $fillable = ['name', 'type', 'custom'];
protected $casts = [
'custom' => 'array',
];
}
-1
View File
@@ -3,7 +3,6 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\StoreGameRequest;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
+5
View File
@@ -58,4 +58,9 @@ class User extends Authenticatable
{ {
return $this->hasMany(Game::class, 'player1_user_id')->orWhere('player2_user_id', $this->id); return $this->hasMany(Game::class, 'player1_user_id')->orWhere('player2_user_id', $this->id);
} }
public function transactions()
{
return $this->hasMany(CoinTransaction::class);
}
} }
@@ -0,0 +1,18 @@
<?php
namespace App\Policies;
use App\Models\CoinTransaction;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class CoinTransactionPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->type === 'A' ? true : false;
}
}
+17 -9
View File
@@ -20,7 +20,7 @@ class GamePolicy
*/ */
public function view(User $user, Game $game): bool public function view(User $user, Game $game): bool
{ {
if ($user->type === 'A') { if ($user->type === "A") {
return true; return true;
} }
@@ -31,6 +31,10 @@ class GamePolicy
return true; return true;
} }
if ($game->status === "Pending") {
return true;
}
return false; return false;
} }
@@ -39,7 +43,7 @@ class GamePolicy
*/ */
public function create(User $user): bool public function create(User $user): bool
{ {
if ($user->type === 'A') { if ($user->type === "A") {
return false; return false;
} }
@@ -48,28 +52,32 @@ class GamePolicy
public function join(User $user, Game $game): bool public function join(User $user, Game $game): bool
{ {
if ($user->type === 'A') { if ($user->type === "A") {
return false; return false;
} }
if ( if (
$game->status !== 'waiting' || $game->status !== "Pending" ||
$game->player1_user_id === $user->id $game->player1_user_id === $user->id
) { ) {
return false; return false;
} }
if ($game->player2_user_id !== null && $game->player2_user_id !== 1) {
return false;
}
return true; return true;
} }
public function resign(User $user, Game $game): bool public function resign(User $user, Game $game): bool
{ {
if ($user->type === 'A') { if ($user->type === "A") {
return false; return false;
} }
if ( if (
$game->status !== 'ongoing' || $game->status !== "Playing" ||
($game->player1_user_id !== $user->id && ($game->player1_user_id !== $user->id &&
$game->player2_user_id !== $user->id) $game->player2_user_id !== $user->id)
) { ) {
@@ -84,12 +92,12 @@ class GamePolicy
*/ */
public function update(User $user, Game $game): bool public function update(User $user, Game $game): bool
{ {
if ($user->type === 'A') { if ($user->type === "A") {
return false; return false;
} }
if ( if (
$game->status !== 'ongoing' || $game->status !== "Playing" ||
($game->player1_user_id !== $user->id && ($game->player1_user_id !== $user->id &&
$game->player2_user_id !== $user->id) $game->player2_user_id !== $user->id)
) { ) {
@@ -105,7 +113,7 @@ class GamePolicy
public function delete(User $user, Game $game): bool public function delete(User $user, Game $game): bool
{ {
// Only admins can delete games // Only admins can delete games
return $user->type === 'A'; return $user->type === "A";
} }
/** /**
+9 -1
View File
@@ -4,8 +4,10 @@ use App\Http\Controllers\AuthController;
use App\Http\Controllers\GameController; use App\Http\Controllers\GameController;
use App\Http\Controllers\MatchController; use App\Http\Controllers\MatchController;
use App\Http\Controllers\ProfileController; use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\StatisticsController; use App\Http\Controllers\StatisticsController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\CoinPurchaseController;
use App\Http\Controllers\TransactionController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function () { Route::prefix('v1')->group(function () {
@@ -19,10 +21,12 @@ Route::prefix('v1')->group(function () {
// Authenticated Routes // Authenticated Routes
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () { Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
Route::post('/logout', [AuthController::class, 'logout']); Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/coin-purchases', [CoinPurchaseController::class, 'store']);
Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']); Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']);
Route::prefix('users/me')->group(function () { Route::prefix('users/me')->group(function () {
Route::get('/', [ProfileController::class, 'show']); Route::get('/', [ProfileController::class, 'show']);
Route::put('/', [ProfileController::class, 'update']); Route::put('/', [ProfileController::class, 'update']);
Route::patch('/password', [ProfileController::class, 'updatePassword']);
Route::delete('/', [ProfileController::class, 'destroy']); Route::delete('/', [ProfileController::class, 'destroy']);
Route::get('/coins', [ProfileController::class, 'getCoins']); Route::get('/coins', [ProfileController::class, 'getCoins']);
Route::put('/password', [ Route::put('/password', [
@@ -30,6 +34,7 @@ Route::prefix('v1')->group(function () {
'updatePassword', 'updatePassword',
]); ]);
Route::post('/avatar', [ProfileController::class, 'uploadAvatar']); Route::post('/avatar', [ProfileController::class, 'uploadAvatar']);
Route::get('/transactions', [UserController::class, 'getMyTransactions']);
}); });
// User Resources // User Resources
@@ -39,6 +44,7 @@ Route::prefix('v1')->group(function () {
UserController::class, UserController::class,
'getMatches', 'getMatches',
]); ]);
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
}); });
// Game Resources // Game Resources
@@ -65,6 +71,8 @@ Route::prefix('v1')->group(function () {
Route::middleware('user.type:A') Route::middleware('user.type:A')
->prefix('admin') ->prefix('admin')
->group(function () { ->group(function () {
Route::get('/statistics', [StatisticsController::class, 'getAdminStats']);
Route::get('/transactions', [TransactionController::class, 'index']);
Route::prefix('users')->group(function () { Route::prefix('users')->group(function () {
Route::get('/', [UserController::class, 'index']); Route::get('/', [UserController::class, 'index']);
Route::post('/', [UserController::class, 'store']); Route::post('/', [UserController::class, 'store']);
+69 -4
View File
@@ -1,19 +1,84 @@
### Get All Students (Login) ### Get All Students (Login)
# @name login # @name login
POST http://localhost:8000/api/login POST http://localhost:8000/api/v1/login
Content-Type: application/json Content-Type: application/json
Accept: application/json Accept: application/json
{ {
"email": "p[email protected]", "email": "a1@mail.pt",
"password": "123" "password": "123"
} }
### Capture the token ### Capture the token & id
@token = {{login.response.body.token}} @token = {{login.response.body.token}}
@id = {{login.response.body.user.id}}
### Get All matches ### Get All matches
GET http://localhost:8000/api/matches GET http://localhost:8000/api/v1/games
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get me user
GET http://localhost:8000/api/v1/users/me
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get me coins
GET http://localhost:8000/api/v1/users/me/coins
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get me matches
GET http://localhost:8000/api/v1/users/{{id}}/matches
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get me transactions
GET http://localhost:8000/api/v1/users/{{id}}/transactions?type=C
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### post coin-purchases
POST http://localhost:8000/api/v1/coin-purchases
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
{
"euros": 1,
"payment_type": "MBWAY",
"payment_reference": "912345678"
}
### Get leaderboard
GET http://localhost:8000/api/v1/leaderboard
Content-Type: application/json
Accept: application/json
### Get me stats
GET http://localhost:8000/api/v1/statistics/me
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get public stats
GET http://localhost:8000/api/v1/statistics/public
Content-Type: application/json
Accept: application/json
### Get admin stats
GET http://localhost:8000/api/v1/admin/statistics
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{token}}
### Get admin stats
GET http://localhost:8000/api/v1/admin/users
Content-Type: application/json Content-Type: application/json
Accept: application/json Accept: application/json
Authorization: Bearer {{token}} Authorization: Bearer {{token}}
+1 -1
View File
@@ -12,7 +12,7 @@ post {
body:json { body:json {
{ {
"email":"a1@mail.pt", "email":"p[email protected]",
"password":"123" "password":"123"
} }
} }
+23
View File
@@ -0,0 +1,23 @@
meta {
name: Patch Password
type: http
seq: 3
}
patch {
url: {{api_url}}/users/me
body: json
auth: none
}
headers {
Accept: application/json
Authorization: Bearer {{token}}
}
body:json {
{
"current_password":"123",
"new_password": "456"
}
}
+15
View File
@@ -0,0 +1,15 @@
meta {
name: Create Game
type: http
seq: 3
}
post {
url: {{api_url}}/games
body: none
auth: inherit
}
settings {
encodeUrl: true
}
+2 -4
View File
@@ -3,8 +3,7 @@
<nav class="max-w-full p-5 flex flex-row justify-between align-middle"> <nav class="max-w-full p-5 flex flex-row justify-between align-middle">
<div class="align-middle text-xl"> <div class="align-middle text-xl">
<RouterLink to="/"> {{ pageTitle }} </RouterLink> <RouterLink to="/"> {{ pageTitle }} </RouterLink>
<span class="text-xs" v-if="authStore.currentUser" <span class="text-xs" v-if="authStore.currentUser">&nbsp;&nbsp;&nbsp; ({{ authStore.currentUser?.name }})
>&nbsp;&nbsp;&nbsp; ({{ authStore.currentUser?.name }})
</span> </span>
</div> </div>
<NavBar @logout="logout" :userLoggedIn="authStore.isLoggedIn" /> <NavBar @logout="logout" :userLoggedIn="authStore.isLoggedIn" />
@@ -29,8 +28,7 @@ import { useSocketStore } from './stores/socket'
const authStore = useAuthStore() const authStore = useAuthStore()
const socketStore = useSocketStore() const socketStore = useSocketStore()
const year = new Date().getFullYear() const pageTitle = ref(`DAD 2025/26`)
const pageTitle = ref(`DAD ${year}/${String(year + 1).slice(-2)}`)
const logout = () => { const logout = () => {
toast.promise(authStore.logout(), { toast.promise(authStore.logout(), {
+28 -6
View File
@@ -22,13 +22,23 @@
</NavigationMenuLink> </NavigationMenuLink>
</NavigationMenuItem> </NavigationMenuItem>
<NavigationMenuItem v-else> <NavigationMenuItem v-else class="flex flex-row gap-4">
<NavigationMenuLink> <NavigationMenuLink v-if="userStore.coins > 0" href="/coins-purchase"
<a href="/home" @click.prevent="logoutClickHandler" class="cursor-pointer">Logout</a> class="flex flex-row items-center gap-1">
<div class="flex items-center justify-center w-5 h-5 bg-purple-400 rounded-full shadow-sm">
<span class="text-[10px] font-bold text-purple-900">$</span>
</div>
<span class="text-sm font-medium tabular-nums">
{{ userStore.coins }} <span class="text-muted-foreground text-xs">Coins</span>
</span>
</NavigationMenuLink> </NavigationMenuLink>
<NavigationMenuLink> <NavigationMenuLink>
<RouterLink to="/user">Profile</RouterLink> <RouterLink to="/user">Profile</RouterLink>
</NavigationMenuLink> </NavigationMenuLink>
<NavigationMenuLink>
<a href="/home" @click.prevent="logoutClickHandler" class="cursor-pointer">Logout</a>
</NavigationMenuLink>
</NavigationMenuItem> </NavigationMenuItem>
</NavigationMenuList> </NavigationMenuList>
</NavigationMenu> </NavigationMenu>
@@ -46,6 +56,9 @@ import {
NavigationMenuTrigger, NavigationMenuTrigger,
} from '@/components/ui/navigation-menu' } from '@/components/ui/navigation-menu'
import router from '@/router'; import router from '@/router';
import { watch } from 'vue';
import { useUserStore } from '@/stores/user';
const emits = defineEmits(['logout']) const emits = defineEmits(['logout'])
const { userLoggedIn } = defineProps(['userLoggedIn']) const { userLoggedIn } = defineProps(['userLoggedIn'])
@@ -55,7 +68,7 @@ const biscaStore = useBiscaStore()
const logoutClickHandler = () => { const logoutClickHandler = () => {
if (biscaStore.isGameRunning) { if (biscaStore.isGameRunning) {
const confirmLogout = window.confirm( const confirmLogout = window.confirm(
'⚠️ Jogo em Progresso!\n\nSe fizeres Logout agora, perderás o jogo atual e serás considerado PERDEDOR.\n\nQueres mesmo sair?' 'If you leave now this game will count as "FORFEIT". Are you sure you want to logout?'
) )
if (!confirmLogout) return if (!confirmLogout) return
@@ -67,7 +80,16 @@ const logoutClickHandler = () => {
} }
emits('logout') emits('logout')
router.push('/login')
router.push({ name: 'home' })
} }
const userStore = useUserStore()
watch(() => userLoggedIn, async (isLoggedIn) => {
if (isLoggedIn) {
await userStore.fetchCoins()
} else {
userStore.coins = 0
}
}, { immediate: true })
</script> </script>
+752
View File
@@ -0,0 +1,752 @@
<template>
<div class="min-h-screen p-4 md:p-8 flex flex-col items-center font-sans text-black">
<div class="max-w-7xl w-full mb-8">
<div class="flex flex-col md:flex-row md:justify-between md:items-end gap-6 mb-8">
<div>
<h1 class="text-4xl font-black uppercase tracking-tighter">Admin Panel</h1>
<p class="text-gray-500 text-xs mt-1 uppercase tracking-[0.2em] font-bold">Platform Oversight</p>
</div>
<button @click="showCreateModal = true"
class="px-6 py-3 bg-black text-white text-xs font-bold uppercase tracking-widest hover:bg-gray-800 transition-all active:scale-95 border border-black">
+ Create Admin
</button>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div class="bg-white border border-gray-300 p-6 shadow-sm">
<span class="text-[10px] font-bold uppercase tracking-widest text-gray-400 block mb-1">Total
Players</span>
<span class="text-3xl font-black">{{ stats.global_counters?.total_players ?? 'Loading' }}</span>
</div>
<div class="bg-white border border-gray-300 p-6 shadow-sm">
<span class="text-[10px] font-bold uppercase tracking-widest text-gray-400 block mb-1">Active
Games</span>
<span class="text-3xl font-black">{{ stats.global_counters?.active_games ?? 'Loading' }}</span>
</div>
<div @click="openChart('games')"
class="bg-white border border-gray-300 p-6 shadow-sm cursor-pointer hover:border-black transition-colors group">
<div class="flex justify-between items-start">
<span class="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1">Total
Games</span>
<svg class="w-4 h-4 text-gray-300 group-hover:text-black" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path d="M7 12l5 5L22 7"></path>
</svg>
</div>
<span class="text-3xl font-black">{{ stats.global_counters?.total_games ?? 'Loading' }}</span>
<span
class="block text-[10px] mt-2 underline opacity-0 group-hover:opacity-100 transition-opacity">View
Volume Chart</span>
</div>
<div @click="openChart('revenue')"
class="bg-black text-white p-6 shadow-lg cursor-pointer hover:bg-gray-900 transition-colors group">
<div class="flex justify-between items-start">
<span class="text-[10px] font-bold uppercase tracking-widest opacity-60 mb-1">Estimated
Revenue</span>
<svg class="w-4 h-4 opacity-40 group-hover:opacity-100" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z">
</path>
</svg>
</div>
<span class="text-3xl font-black"> {{ (stats.global_counters?.total_coins_purchased /
10).toLocaleString() ?? 'Loading' }}</span>
<span
class="block text-[10px] mt-2 underline opacity-60 group-hover:opacity-100 transition-opacity">View
Purchase History</span>
</div>
</div>
</div>
<div v-if="activeChart"
class="fixed inset-0 bg-black/80 backdrop-blur-md z-[60] flex items-center justify-center p-4"
@click.self="activeChart = null">
<div class="bg-white border border-gray-300 w-full max-w-5xl overflow-hidden shadow-2xl">
<div class="p-6 border-b border-gray-300 flex justify-between items-center bg-white">
<div>
<h3 class="text-2xl font-black uppercase tracking-tighter">
{{ activeChart === 'games' ? 'Games Volume' : 'Purchases History' }}
</h3>
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-[0.2em]">Last 12 Months
Activity</p>
</div>
<button @click="activeChart = null"
class="w-12 h-12 flex items-center justify-center border border-black hover:bg-black hover:text-white transition-all group">
<span class="text-xl group-hover:rotate-90 transition-transform"></span>
</button>
</div>
<div class="p-12 min-h-[400px] flex flex-col justify-end">
<div v-if="chartData.length > 0" class="flex items-end gap-3 h-64 w-full">
<div v-for="(data, index) in chartData" :key="data.month"
class="flex-1 flex flex-col items-center group relative h-full justify-end">
<div
class="absolute -top-12 bg-black text-white text-[10px] py-2 px-3 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 font-bold">
{{ data.total || data.total_coins }}
<div class="absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-black rotate-45">
</div>
</div>
<div class="w-full bg-black hover:bg-gray-700 transition-all ease-out" :style="{
height: showBars ? `${calculateHeight(data.total || data.total_coins)}%` : '0%',
transitionDelay: `${index * 50}ms`,
transitionDuration: '800ms'
}"></div>
<div class="h-8 flex items-center">
<span class="text-[9px] font-black uppercase text-gray-400">
{{ formatMonth(data.month) }}
</span>
</div>
</div>
</div>
<div v-else
class="h-64 flex flex-col items-center justify-center text-gray-400 border-2 border-dashed border-gray-100">
<p class="text-xs font-bold uppercase tracking-widest">No data available for this period</p>
</div>
</div>
<div class="bg-gray-50 p-8 border-t border-gray-300 flex justify-between items-center">
<div class="flex gap-12">
<div v-if="activeChart === 'games'" v-for="gt in stats.charts.games_by_type" :key="gt.type">
<span class="text-[10px] font-bold uppercase text-gray-400 block tracking-widest">Bisca {{
gt.type }}</span>
<span class="text-2xl font-black">{{ gt.total.toLocaleString() }}</span>
</div>
<div v-if="activeChart === 'revenue'">
<span class="text-[10px] font-bold uppercase text-gray-400 block tracking-widest">Total
Period Volume</span>
<span class="text-2xl font-black">{{
stats.global_counters.total_coins_purchased.toLocaleString() }} Coins</span>
</div>
</div>
<div class="text-[10px] font-bold text-gray-400 uppercase italic">
* Admin Full-Access View
</div>
</div>
</div>
</div>
<div class="bg-white border border-gray-300 shadow-2xl max-w-7xl w-full overflow-hidden">
<div class="flex border-b border-gray-300 bg-gray-50 overflow-x-auto scrollbar-hide">
<button v-for="tab in tabs" :key="tab.id" @click="activeTab = tab.id" :class="[
'flex-1 min-w-[150px] p-5 text-xs font-bold uppercase tracking-widest transition-all outline-none',
activeTab === tab.id
? 'bg-white border-b-2 border-black text-black'
: 'text-gray-400 hover:text-black hover:bg-gray-100 border-b-2 border-transparent'
]">
{{ tab.name }}
</button>
</div>
<div class="min-h-[400px]">
<div v-if="activeTab === 'users'" class="animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="overflow-x-auto">
<div id="table-scroll-container"
class="overflow-y-auto h-[500px] scrollbar-thin scrollbar-thumb-black">
<table class="w-full text-left border-collapse sticky-header">
<thead class="bg-gray-50 border-b border-gray-300">
<tr>
<th
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Name</th>
<th
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Coins</th>
<th @click="handleSort('type')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Role
<span class="ml-1">
<template v-if="filters.type === 'A'"> (Admins)</template>
<template v-else-if="filters.type === 'P'"> (Players)</template>
<template v-else> </template>
</span>
</th>
<th @click="handleSort('blocked')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Status
<span class="ml-1">
<template v-if="filters.blocked === true"> (Blocked)</template>
<template v-else-if="filters.blocked === false"> (Active)</template>
<template v-else> </template>
</span>
</th>
<th></th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<template v-if="filteredUsers.length > 0">
<tr v-for="user in filteredUsers" :key="user.id"
class="hover:bg-gray-50/80 transition-colors">
<td class="p-4">
<div class="flex items-center gap-3">
<div
class="w-10 h-10 bg-black text-white flex items-center justify-center font-bold text-sm border-2 border-black">
{{ user.name.charAt(0) }}
</div>
<div>
<div class="text-sm font-bold">{{ user.name }}</div>
<div v-if="user.nickname"
class="text-xs text-gray-500 font-mono">@{{ user.nickname
}}</div>
<div class="text-xs text-gray-500 font-mono">{{ user.email }}
</div>
</div>
</div>
</td>
<td class="p-4">
<div v-if="user.coins_balance" class="flex items-center gap-2">
<div
class="flex items-center justify-center w-5 h-5 bg-purple-400 rounded-full shadow-sm">
<span class="text-[10px] font-bold text-purple-900">$</span>
</div>
<span class="text-[10px] uppercase font-bold tracking-tight">{{
user.coins_balance }}</span>
</div>
</td>
<td class="p-4">
<span :class="[
'px-2 py-1 text-[10px] font-bold border',
user.type === 'A' ? 'bg-black text-white border-black' : 'bg-white text-gray-600 border-gray-300'
]">
{{ user.type === 'A' ? 'ADMIN' : 'PLAYER' }}
</span>
</td>
<td class="p-4">
<div class="flex items-center gap-2">
<div
:class="['w-2 h-2 rounded-full', user.blocked ? 'bg-red-600' : 'bg-green-500']">
</div>
<span class="text-[10px] uppercase font-bold tracking-tight">{{
user.blocked
? 'Blocked' : 'Active' }}</span>
</div>
</td>
<td class="p-4 text-right">
<div v-if="user.type != 'A'" class="space-x-2 flex justify-end">
<button @click="toggleBlock(user)"
class="text-[10px] font-bold uppercase tracking-tighter border-2 border-black px-3 py-1 hover:bg-black hover:text-white transition-all">{{
user.blocked ? 'Unblock' : 'Block' }}</button>
<button @click=" confirmDelete(user)"
class="text-[10px] font-bold uppercase tracking-tighter bg-red-600 text-white border-2 border-red-600 px-3 py-1 hover:bg-red-700 transition-all">Remove</button>
</div>
</td>
</tr>
</template>
<tr v-else-if="!isLoading">
<td colspan="3"
class="p-12 text-center text-gray-400 uppercase text-xs font-bold tracking-widest">
No users found
</td>
</tr>
<tr ref="loadMoreTrigger">
<td colspan="4" class="p-4 text-center">
<span v-if="isLoading"
class="text-[10px] font-bold uppercase animate-pulse">Loading
more...</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else-if="activeTab === 'transactions'"
class="animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="overflow-x-auto">
<div id="table-scroll-container"
class="overflow-y-auto h-[500px] scrollbar-thin scrollbar-thumb-black">
<table class="w-full text-left border-collapse sticky-header">
<thead class="bg-gray-50 border-b border-gray-300">
<tr>
<th @click="handleSort('datetime')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Date Time
<span>{{ filters.sort_datetime === 'desc' ? ' ↓' : ' ↑' }}</span>
</th>
<th class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500">
User
</th>
<th class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500">
Transaction type
</th>
<th @click="handleSort('coins')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Coins
<span v-if="filters.sort_coins">
{{ filters.sort_coins === 'desc' ? ' ' : '' }}</span>
<span v-else> </span>
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<template v-if="transactions.length > 0">
<tr v-for="tx in transactions" :key="tx.id"
class="hover:bg-gray-50/80 transition-colors">
<td class="p-4 text-xs font-mono text-gray-600">
{{ new Date(tx.transaction_datetime).toLocaleDateString() }}
{{ new Date(tx.transaction_datetime).toLocaleTimeString([], {
hour:
'2-digit', minute: '2-digit'
}) }}
</td>
<td class="p-4">
<div class="text-sm font-bold">{{ tx.user?.nickname || 'Guest' }}</div>
<div class="text-[10px] text-gray-500 font-mono">{{ tx.user?.email }}
</div>
</td>
<td class="p-4">
<div class="flex items-center gap-4">
<div
class="px-2 py-1 bg-gray-100 border border-gray-300 text-[9px] font-black uppercase tracking-tighter text-gray-500 min-w-[80px] text-center">
{{ tx.type?.name || 'Manual' }}
</div>
</div>
</td>
<td class="p-4">
<div class="inline-flex items-center gap-2">
<span :class="[
'text-sm font-black tracking-tighter',
tx.coins >= 0 ? 'text-green-400' : 'text-red-400'
]">
{{ tx.coins > 0 ? '+' : '' }}{{ tx.coins.toLocaleString() }}
</span>
<span
class="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Coins</span>
</div>
</td>
</tr>
</template>
<tr v-else-if="!isLoading">
<td colspan="3"
class="w-1 p-12 text-center text-gray-400 uppercase text-xs font-bold tracking-widest">
No transactions found
</td>
</tr>
<tr ref="loadMoreTrigger">
<td colspan="4" class="p-4 text-center">
<span v-if="isLoading"
class="text-[10px] font-bold uppercase animate-pulse">Loading
more...</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else-if="activeTab === 'games'" class="animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="overflow-x-auto">
<div id="table-scroll-container"
class="overflow-y-auto h-[500px] scrollbar-thin scrollbar-thumb-black">
<table class="w-full text-left border-collapse sticky-header">
<thead class="bg-gray-50 border-b border-gray-300">
<tr>
<th @click="handleSort('date')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Timeline
<span>{{ filters.game_sort_date === 'desc' ? ' ↓' : ' ↑' }}</span>
</th>
<th class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500">
Player 1</th>
<th class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500">
Player 2</th>
<th class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500">
Result</th>
<th @click="handleSort('type')"
class="p-4 text-[10px] font-bold uppercase tracking-widest text-gray-500 cursor-pointer hover:text-black transition-colors">
Variant
<span v-if="filters.game_filter_type"> (Bisca {{ filters.game_filter_type
}})</span>
<span v-else> </span>
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<template v-if="games.length > 0">
<tr v-for="game in games" :key="game.id"
class="hover:bg-gray-50/80 transition-colors">
<td class="p-4">
<div class="text-[10px] font-mono text-black font-bold">
{{ new Date(game.began_at).toLocaleDateString() }}</div>
<div class="text-[10px] font-mono text-gray-400 italic">
{{ new Date(game.began_at).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}) }}
{{ new Date(game.ended_at).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}) }}
</div>
</td>
<td class="p-4">
<div class="text-sm font-bold text-black">{{ game.player1?.nickname }}
</div>
<div
class="text-[10px] font-black text-gray-400 uppercase tracking-tighter">
{{ game.player1_points }} Points
</div>
</td>
<td class="p-4">
<div class="text-sm font-bold text-black">{{ game.player2?.nickname }}
</div>
<div
class="text-[10px] font-black text-gray-400 uppercase tracking-tighter">
{{ game.player2_points }} Points
</div>
</td>
<td class="p-4">
<div v-if="game.is_draw" class="text-xs font-bold text-gray-400"> Draw
</div>
<div v-else class="flex flex-col">
<span
class="text-[9px] font-bold uppercase text-gray-400 tracking-widest mb-0.5">Winner</span>
<span
class="text-xs font-black bg-black text-white px-2 py-0.5 w-fit uppercase tracking-tighter">
{{ game.winner_user_id === game.player1_user_id ?
game.player1?.nickname : game.player2?.nickname }}
</span>
</div>
</td>
<td class="p-4">
<div
class="px-2 py-1 bg-gray-100 border border-gray-300 text-[10px] font-black text-center w-20">
BISCA {{ game.type }}
</div>
</td>
</tr>
<tr ref="loadMoreTrigger">
<td colspan="5" class="p-8 text-center border-none">
<div v-if="isLoading" class="flex flex-col items-center gap-2">
<div
class="w-5 h-5 border-2 border-black border-t-transparent rounded-full animate-spin">
</div>
<span
class="text-[10px] font-black uppercase tracking-[0.2em]">Retrieving
match data...</span>
</div>
</td>
</tr>
</template>
<tr v-else-if="!isLoading">
<td colspan="5"
class="p-12 text-center text-gray-400 uppercase text-xs font-bold tracking-widest border-none">
No match history found
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else class="p-12 text-center animate-in fade-in duration-500">
<svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1"
d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<h2 class="text-sm font-bold uppercase tracking-widest text-gray-400">Detailed logs for {{ activeTab
}} pending API</h2>
</div>
</div>
</div>
<div v-if="showCreateModal"
class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
<div class="bg-white border border-gray-300 w-full max-w-md shadow-2xl animate-in zoom-in-95 duration-200">
<div class="p-6 border-b border-gray-300 bg-black text-white">
<h3 class="text-xl font-black uppercase tracking-tighter">New Admin</h3>
</div>
<form @submit.prevent="handleSubmitAdmin" class="p-6 space-y-4">
<div>
<label class="block text-[10px] font-bold uppercase text-gray-500 mb-1">Full Name</label>
<input v-model="adminForm.name" type="text" required
class="w-full border border-gray-300 p-3 text-sm focus:border-black outline-none transition-colors" />
</div>
<div>
<label class="block text-[10px] font-bold uppercase text-gray-500 mb-1">Email Address</label>
<input v-model="adminForm.email" type="email" required
class="w-full border border-gray-300 p-3 text-sm focus:border-black outline-none transition-colors" />
</div>
<div class="flex gap-3 pt-4">
<button type="button" @click="showCreateModal = false"
class="flex-1 px-4 py-3 border border-gray-300 font-bold uppercase text-xs hover:bg-gray-50 transition-all">Cancel</button>
<button type="submit"
class="flex-1 px-4 py-3 bg-black text-white font-bold uppercase text-xs hover:bg-gray-800 transition-all">Create
Account</button>
</div>
</form>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { useAPIStore } from '@/stores/api'
import { useAuthStore } from '@/stores/auth'
import { toast } from 'vue-sonner'
const activeTab = ref('users')
const showCreateModal = ref(false)
const activeChart = ref(null)
const showBars = ref(false)
const stats = ref({})
const users = ref([])
const transactions = ref([])
const games = ref([])
const isLoading = ref(false)
const loadMoreTrigger = ref(null)
const apiStore = useAPIStore()
const pagination = reactive({
users: { page: 1, lastPage: 1 },
transactions: { page: 1, lastPage: 1 },
games: { page: 1, lastPage: 1 }
})
const filters = reactive({
type: null,
blocked: null,
sort_datetime: 'desc',
sort_coins: null,
game_sort_direction: 'desc',
game_type: null
})
watch(activeTab, async () => {
resetPagination();
await fetchData();
await nextTick();
setupObserver();
});
const tabs = [
{ id: 'users', name: 'User Management' },
{ id: 'transactions', name: 'Transactions' },
{ id: 'games', name: 'Games History' }
]
const chartData = computed(() => {
if (!stats.value) return []
if (activeChart.value === 'games') return [...stats.value.charts.games_per_month].reverse()
if (activeChart.value === 'revenue') return [...stats.value.charts.purchases_per_month].reverse()
return []
})
const openChart = (type) => {
activeChart.value = type
showBars.value = false
setTimeout(() => {
showBars.value = true
}, 50);
}
const calculateHeight = (value) => {
const max = Math.max(...chartData.value.map(d => d.total || d.total_coins))
return (value / max) * 100
}
const formatMonth = (monthStr) => {
const [_, month] = monthStr.split('-')
const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
return months[parseInt(month) - 1]
}
const adminForm = reactive({ name: '', nickname: '', email: '' })
const toggleBlock = (user) => {
user.blocked == false ? apiStore.blockUser(user) : apiStore.unblockUser(user)
user.blocked = !user.blocked
}
const confirmDelete = (user) => {
if (confirm(`Remove ${user.name}? This action follows platform rules for ${user.type === 'P' ? 'soft-deletion' : 'permanent removal'}.`)) {
apiStore.deleteUser(user)
users.value = users.value.filter(u => u.id !== user.id)
}
}
const handleSubmitAdmin = () => {
adminForm.type = 'A'
adminForm.password = '123'
adminForm.blocked = false
const promise = apiStore.postAdmin(adminForm)
toast.promise(promise, {
loading: 'Calling API',
success: () => {
return `Admin created with success`
},
error: (error) =>
error.response?.data?.message
})
showCreateModal.value = false
adminForm.name = ''; adminForm.email = '';
}
const resetPagination = () => {
pagination[activeTab.value].page = 1
if (activeTab.value === 'users') users.value = []
if (activeTab.value === 'transactions') transactions.value = []
if (activeTab.value === 'games') games.value = []
}
const filteredUsers = computed(() => {
return users.value.filter(user => user.id !== useAuthStore().currentUserID);
});
const fetchData = async () => {
if (isLoading.value) return
const currentTab = activeTab.value
if (pagination[currentTab].page > pagination[currentTab].lastPage && pagination[currentTab].page !== 1) return
isLoading.value = true
try {
let response
if (currentTab === 'users') {
const params = { page: pagination[currentTab].page, type: filters.type, blocked: filters.blocked };
response = await apiStore.getAdminUsers(params);
users.value.push(...response.data.data);
}
else if (currentTab === 'transactions') {
const params = {
page: pagination[currentTab].page,
sort_datetime: filters.sort_datetime,
sort_coins: filters.sort_coins
};
response = await apiStore.getAdminTransactions(params);
transactions.value.push(...response.data.data);
}
else if (currentTab === 'games') {
const params = {
page: pagination[currentTab].page,
sort_direction: filters.game_sort_direction,
type: filters.game_type
};
response = await apiStore.getAdminGames(params);
games.value.push(...response.data.data);
}
pagination[currentTab].lastPage = response.data.last_page
pagination[currentTab].page++
} catch (error) {
console.error("Fetch failed", error)
} finally {
isLoading.value = false
}
}
const handleSort = async (column) => {
if (activeTab.value === 'users') {
if (column === 'type') {
filters.type = filters.type === null ? 'A' : (filters.type === 'A' ? 'P' : null);
} else if (column === 'blocked') {
filters.blocked = filters.blocked === null ? true : (filters.blocked === true ? false : null);
}
}
else if (activeTab.value === 'transactions') {
if (column === 'datetime') {
filters.sort_datetime = filters.sort_datetime === 'desc' ? 'asc' : 'desc';
} else if (column === 'coins') {
if (filters.sort_coins === null) filters.sort_coins = 'desc';
else if (filters.sort_coins === 'desc') filters.sort_coins = 'asc';
else filters.sort_coins = null;
}
}
else if (activeTab.value === 'games') {
if (column === 'date') {
filters.game_sort_direction = filters.game_sort_direction === 'desc' ? 'asc' : 'desc';
} else if (column === 'type') {
if (filters.game_type === null) filters.game_type = '9';
else if (filters.game_type === '9') filters.game_type = '3';
else filters.game_type = null;
}
}
resetPagination();
await fetchData();
await nextTick();
setupObserver();
};
const setupObserver = () => {
if (window.adminTableObserver) window.adminTableObserver.disconnect();
const container = document.querySelector('#table-scroll-container');
const observer = new IntersectionObserver((entries) => {
const currentTab = activeTab.value;
const hasMore = pagination[currentTab].page <= pagination[currentTab].lastPage;
if (entries[0].isIntersecting && !isLoading.value && hasMore) {
fetchData();
}
}, {
root: container,
threshold: 0.1,
rootMargin: '100px'
});
if (loadMoreTrigger.value) {
observer.observe(loadMoreTrigger.value);
window.adminTableObserver = observer;
}
};
onMounted(async () => {
const statsResponse = await apiStore.getAdminStats()
const globalResponse = await apiStore.getPublicStats()
stats.value = statsResponse.data
stats.value.global_counters.active_games = globalResponse.data.active_games
await fetchData()
await nextTick()
setupObserver()
})
</script>
<style scoped>
.sticky-header thead th {
position: sticky;
top: 0;
background-color: #f9fafb;
box-shadow: inset 0 -1px 0 #d1d5db;
}
#table-scroll-container::-webkit-scrollbar {
width: 6px;
}
#table-scroll-container::-webkit-scrollbar-thumb {
background-color: black;
}
#table-scroll-container::-webkit-scrollbar-track {
background-color: #f3f4f6;
}
</style>
+236 -21
View File
@@ -1,5 +1,6 @@
<script setup> <script setup>
import { ref, onMounted, nextTick } from 'vue' import { User, Trophy } from 'lucide-vue-next'
import { ref, onMounted, nextTick, inject } from 'vue'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { import {
Card, Card,
@@ -10,40 +11,52 @@ import {
} from '@/components/ui/card' } from '@/components/ui/card'
import { useAPIStore } from '@/stores/api' import { useAPIStore } from '@/stores/api'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const API_BASE_URL = inject('apiBaseURL')
const apiStore = useAPIStore() const apiStore = useAPIStore()
const router = useRouter() const router = useRouter()
const openGames = ref([]) const openGames = ref([])
const selectedMode = ref('9') const selectedMode = ref('9')
const observerTarget = ref(null); const gObserverTarget = ref(null);
const observer = ref(null); const gObserver = ref(null);
const isLoading = ref(false); const gLoading = ref(false);
const pageCounter = ref(1); const gPage = ref(1);
const showHostModal = ref(false) const showHostModal = ref(false)
const showJoinModal = ref(false) const showJoinModal = ref(false)
const selectedGame = ref(null) const selectedGame = ref(null)
const isReady = ref(false) const isReady = ref(false)
const showLeaderboardModal = ref(false)
const showStatsModal = ref(false)
const userStats = ref(null)
const statsLoading = ref(false)
const leaderboardEntries = ref([])
const lbLoading = ref(false)
const lbPage = ref(1)
const lbObserverTarget = ref(null)
const lbObserver = ref(null)
const lbMorePages = ref(true)
const publicStats = ref(null)
const setupObserver = () => { const setupGamesObserver = () => {
if (observer.value) observer.value.disconnect(); if (gObserver.value) gObserver.value.disconnect();
observer.value = new IntersectionObserver((entries) => { gObserver.value = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !isLoading.value && openGames.value.length > 0) { if (entries[0].isIntersecting && !gLoading.value && openGames.value.length > 0) {
getPendingGames(); getPendingGames();
} }
}, { threshold: 0.1 }); }, { threshold: 0.1 });
if (observerTarget.value) { if (gObserverTarget.value) {
observer.value.observe(observerTarget.value); gObserver.value.observe(gObserverTarget.value);
} }
} }
const getPendingGames = async (mode = selectedMode.value) => { const getPendingGames = async (mode = selectedMode.value) => {
if (isLoading.value) return; if (gLoading.value) return;
isLoading.value = true; gLoading.value = true;
apiStore.gameQueryParameters.page = gPage.value++;
apiStore.gameQueryParameters.page = pageCounter.value++;
apiStore.gameQueryParameters.filters.sort_direction = "asc" apiStore.gameQueryParameters.filters.sort_direction = "asc"
apiStore.gameQueryParameters.filters.type = mode apiStore.gameQueryParameters.filters.type = mode
apiStore.gameQueryParameters.filters.status = 'Pending' apiStore.gameQueryParameters.filters.status = 'Pending'
@@ -52,7 +65,75 @@ const getPendingGames = async (mode = selectedMode.value) => {
const newGames = response.data.data; const newGames = response.data.data;
openGames.value = [...openGames.value, ...newGames]; openGames.value = [...openGames.value, ...newGames];
} finally { } finally {
isLoading.value = false; gLoading.value = false;
}
}
const fetchPublicStats = async () => {
try {
const response = await apiStore.getPublicStats()
publicStats.value = response.data
} catch (error) {
console.error("Failed to fetch public stats", error)
}
}
const openStats = async () => {
showStatsModal.value = true
statsLoading.value = true
try {
const response = await apiStore.getCurrentUserStats()
userStats.value = response.data
} catch (error) {
console.error("Failed to fetch stats", error)
} finally {
statsLoading.value = false
}
}
const getAvatarUrl = (filename) => {
return filename
? `${API_BASE_URL.replace('/api/v1', '').replace('v1/')}/storage/photos_avatars/${filename}`
: `${API_BASE_URL.replace('/api/v1', '').replace('v1/')}/storage/photos_avatars/anonymous.png`;
}
const fetchLeaderboard = async () => {
if (lbLoading.value || !lbMorePages.value) return;
lbLoading.value = true;
try {
const response = await apiStore.getLeaderboard({ page: lbPage.value });
const newEntries = response.data.data;
if (newEntries.length < 10) {
lbMorePages.value = false;
}
leaderboardEntries.value = [...leaderboardEntries.value, ...newEntries];
lbPage.value++;
} finally {
lbLoading.value = false;
}
}
const openLeaderboard = async () => {
leaderboardEntries.value = [];
lbPage.value = 1;
showLeaderboardModal.value = true;
await nextTick();
setupLeaderboardObserver();
await fetchLeaderboard();
}
const setupLeaderboardObserver = () => {
if (lbObserver.value) lbObserver.value.disconnect();
lbObserver.value = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !lbLoading.value && leaderboardEntries.value.length > 0) {
fetchLeaderboard();
}
}, { threshold: 0.1 });
if (lbObserverTarget.value) {
lbObserver.value.observe(lbObserverTarget.value);
} }
} }
@@ -60,9 +141,9 @@ const clickMode = async (mode) => {
if (selectedMode.value === mode) return; if (selectedMode.value === mode) return;
openGames.value = []; openGames.value = [];
selectedMode.value = mode; selectedMode.value = mode;
pageCounter.value = 1; gPage.value = 1;
await getPendingGames(); await getPendingGames();
setupObserver(); setupGamesObserver();
} }
const startSingle = () => { const startSingle = () => {
@@ -84,9 +165,10 @@ const toggleReady = () => {
} }
onMounted(async () => { onMounted(async () => {
await fetchPublicStats();
await getPendingGames(); await getPendingGames();
await nextTick(); await nextTick();
setupObserver(); setupGamesObserver();
}) })
</script> </script>
@@ -95,6 +177,27 @@ onMounted(async () => {
<div class="flex flex-col justify-center items-center gap-5 pt-10 px-4"> <div class="flex flex-col justify-center items-center gap-5 pt-10 px-4">
<Card v-if="publicStats" class="w-full max-w-2xl border-[#a855f7] bg-[#f8f0ff] shadow-sm">
<CardContent class="p-4">
<div class="flex justify-around items-center">
<div class="text-center">
<p class="text-xs uppercase font-bold opacity-70">Players</p>
<p class="text-xl font-black">{{ publicStats.total_players }}</p>
</div>
<div class="h-8 w-[1px] bg-[#a855f7]/20"></div>
<div class="text-center">
<p class="text-xs uppercase font-bold opacity-70">Total Games</p>
<p class="text-xl font-black">{{ publicStats.total_games }}</p>
</div>
<div class="h-8 w-[1px] bg-[#a855f7]/20"></div>
<div class="text-center">
<p class="text-xs uppercase font-bold opacity-70">Active</p>
<p class="text-xl font-black">{{ publicStats.active_games }}</p>
</div>
</div>
</CardContent>
</Card>
<div class="relative w-full max-w-md bg-card rounded-lg border shadow-sm overflow-hidden"> <div class="relative w-full max-w-md bg-card rounded-lg border shadow-sm overflow-hidden">
<div class="relative h-14 flex items-center"> <div class="relative h-14 flex items-center">
@@ -171,8 +274,8 @@ onMounted(async () => {
</div> </div>
</div> </div>
<div ref="observerTarget" class="h-10 flex items-center justify-center"> <div ref="gObserverTarget" class="h-10 flex items-center justify-center">
<span v-if="isLoading" class="text-xs text-purple-500 animate-pulse">Loading <span v-if="gLoading" class="text-xs text-purple-500 animate-pulse">Loading
more...</span> more...</span>
</div> </div>
</div> </div>
@@ -238,5 +341,117 @@ onMounted(async () => {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
<div v-if="showStatsModal"
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
<Card class="w-full max-w-sm max-h-2/3 border-purple-500 shadow-2xl">
<CardHeader class="border-b bg-muted/20">
<div class="flex justify-between items-center">
<CardTitle class="flex items-center gap-2">
<User class="text-yellow-500" /> My Statistics
</CardTitle>
<Button variant="ghost" size="sm" @click="showStatsModal = false">X</Button>
</div>
</CardHeader>
<CardContent class="py-6">
<div v-if="statsLoading" class="flex flex-col items-center py-10 gap-4">
<div class="h-8 w-8 animate-spin rounded-full border-4 border-purple-500 border-t-transparent">
</div>
<p class="text-sm text-muted-foreground">Calculating your glory...</p>
</div>
<div v-else-if="userStats" class="space-y-6">
<div class="text-center">
<h3 class="text-2xl font-bold text-purple-600">{{ userStats.nickname }}</h3>
<p class="text-sm text-muted-foreground">Performance Overview</p>
</div>
<div class="grid grid-cols-2 gap-4">
<div
class="rounded-lg bg-muted/50 p-4 text-center border border-transparent hover:border-purple-500/30 transition-all">
<p class="text-xs uppercase text-muted-foreground font-semibold">Total Games</p>
<p class="text-2xl font-bold">{{ userStats.total_games }}</p>
</div>
<div class="rounded-lg bg-purple-500/10 p-4 text-center border border-purple-500/20">
<p class="text-xs uppercase text-purple-600 font-semibold">Win Rate</p>
<p class="text-2xl font-bold text-purple-600">{{ userStats.win_rate }}</p>
</div>
<div class="rounded-lg bg-green-500/10 p-4 text-center border border-green-500/20">
<p class="text-xs uppercase text-green-600 font-semibold">Wins</p>
<p class="text-2xl font-bold text-green-600">{{ userStats.total_wins }}</p>
</div>
<div class="rounded-lg bg-red-500/10 p-4 text-center border border-red-500/20">
<p class="text-xs uppercase text-red-600 font-semibold">Losses</p>
<p class="text-2xl font-bold text-red-600">{{ userStats.total_losses }}</p>
</div>
</div>
<div class="space-y-2">
<div class="flex justify-between text-xs font-medium">
<span>Win/Loss Ratio</span>
<span>{{ userStats.total_wins }}W - {{ userStats.total_losses }}L</span>
</div>
<div class="h-2 w-full bg-red-500/20 rounded-full overflow-hidden flex">
<div class="bg-green-500 h-full" :style="{ width: userStats.win_rate }"></div>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
<div v-if="showLeaderboardModal"
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
<Card class="w-full max-w-lg max-h-1/2 h-[80vh] flex flex-col border-purple-500 shadow-2xl">
<CardHeader class="border-b">
<div class="flex justify-between items-center">
<CardTitle class="flex items-center gap-2">
<Trophy class="text-purple-500" /> Leaderboard
</CardTitle>
<Button variant="ghost" size="sm" @click="showLeaderboardModal = false">X</Button>
</div>
</CardHeader>
<CardContent class="flex-1 overflow-y-auto custom-scrollbar p-0">
<div v-for="(user, index) in leaderboardEntries" :key="user.id"
class="flex items-center justify-between p-4 border-b last:border-0 hover:bg-muted/30 transition-colors">
<div class="flex items-center gap-4">
<span class="font-bold text-muted-foreground w-6 text-center"
:class="{ 'text-yellow-500': index === 0, 'text-slate-400': index === 1, 'text-orange-400': index === 2 }">
#{{ index + 1 }}
</span>
<img :src="getAvatarUrl(user.photo_avatar_filename)"
class="h-10 w-10 rounded-full border border-purple-200 object-cover" alt="Avatar" />
<div>
<p class="font-semibold text-sm">{{ user.nickname }}</p>
<p class="text-[10px] text-muted-foreground uppercase tracking-wider">Player</p>
</div>
</div>
<div class="text-right">
<p class="text-lg font-bold text-purple-600">{{ user.won_games_count }}</p>
<p class="text-[10px] text-muted-foreground uppercase">Wins</p>
</div>
</div>
<div ref="lbObserverTarget" class="h-20 flex items-center justify-center">
<span v-if="lbLoading" class="text-purple-500 animate-bounce">Loading rankings...</span>
</div>
</CardContent>
</Card>
</div>
</div>
<div class="fixed right-4 top-1/2 -translate-y-1/2 flex flex-col gap-4 z-40">
<Button @click="openLeaderboard" variant="outline" size="icon"
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
<Trophy class="h-6 w-6" />
</Button>
<Button v-if="useAuthStore().isLoggedIn" @click="openStats" variant="outline" size="icon"
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
<User class="h-6 w-6" />
</Button>
</div> </div>
</template> </template>
+1 -1
View File
@@ -44,7 +44,7 @@
<div class="text-center text-sm"> <div class="text-center text-sm">
<span class="text-gray-600">Don't have an account? </span> <span class="text-gray-600">Don't have an account? </span>
<a href="#" class="font-medium text-blue-600 hover:text-blue-500"> <a href="/register" class="font-medium text-blue-600 hover:text-blue-500">
Sign up Sign up
</a> </a>
</div> </div>
@@ -0,0 +1,139 @@
<template>
<div class="flex min-h-screen items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
<div class="w-full max-w-md space-y-8">
<div>
<h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">Buy Coins</h2>
<p class="mt-2 text-center text-sm text-gray-600">1.00 = 10 Coins</p>
</div>
<form class="mt-8 space-y-4" @submit.prevent="handleSubmit">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Amount (Euros)</label>
<Input v-model.number="formData.euros" type="number" min="1" max="100" placeholder="Ex: 10"
required />
<p class="mt-1 text-xs text-blue-600 font-medium">
You will receive: {{ formData.euros * 10 }} coins
</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
<select v-model="formData.payment_type"
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
<option value="MBWAY">MB WAY</option>
<option value="MB">Multibanco (MB)</option>
<option value="VISA">VISA</option>
<option value="PAYPAL">PayPal</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
{{ referenceLabel }}
</label>
<Input v-model="formData.payment_reference" type="text" :placeholder="referencePlaceholder"
required />
<p v-if="errors.payment_reference" class="mt-1 text-xs text-red-500">
{{ errors.payment_reference }}
</p>
</div>
<div class="pt-4">
<Button type="submit" class="w-full">
Confirm Purchase ({{ formData.euros }})
</Button>
</div>
</form>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { usePurchaseStore } from '@/stores/purchase'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
import { useUserStore } from '@/stores/user'
const purchaseStore = usePurchaseStore()
const router = useRouter()
const formData = ref({
euros: 1,
payment_type: 'MBWAY',
payment_reference: ''
})
const errors = ref({})
const referenceLabel = computed(() => {
const labels = {
MBWAY: 'Phone Number',
MB: 'Entity-Reference',
VISA: 'Card Number',
PAYPAL: 'PayPal Email'
}
return labels[formData.value.payment_type]
})
const referencePlaceholder = computed(() => {
const placeholders = {
MBWAY: '912345678',
MB: '12345-123456789',
VISA: '1234 5678 9012 3456',
PAYPAL: '[email protected]'
}
return placeholders[formData.value.payment_type]
})
const validateForm = () => {
errors.value = {}
const type = formData.value.payment_type
const refValue = formData.value.payment_reference
const patterns = {
MBWAY: /^9[0-9]{8}$/,
MB: /^[0-9]{5}-[0-9]{9}$/,
VISA: /^4[0-9]{15}$/,
PAYPAL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
}
if (!patterns[type].test(refValue)) {
errors.value.payment_reference = `Invalid format for ${type}`
return false
}
if (formData.value.euros < 1 || formData.value.euros > 100) {
toast.error("Amount must be between 1 and 100")
return false
}
return true
}
const userStore = useUserStore()
const handleSubmit = async () => {
if (!validateForm()) return
const promise = purchaseStore.purchase(formData.value)
toast.promise(promise, {
loading: 'Processing transaction...',
success: (res) => {
userStore.fetchCoins()
router.push('/')
return `Purchase successful! New balance: ${res.data.balance} coins`
},
error: (error) => {
if (error.response?.status === 422) {
errors.value = error.response.data.errors
return "Please check the highlighted fields"
}
return error.response?.data?.message || "Transaction failed"
}
})
}
</script>
@@ -0,0 +1,151 @@
<template>
<div class="flex min-h-screen items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
<div class="w-full max-w-md space-y-8">
<div>
<h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">Sign up</h2>
<p class="mt-2 text-center text-sm text-gray-600">Enter your data to create your account</p>
</div>
<form class="mt-8 space-y-4" @submit.prevent="handleSubmit">
<div class="flex flex-col items-center justify-center space-y-2">
<label for="avatar-upload"
class="group relative flex h-24 w-24 cursor-pointer items-center justify-center overflow-hidden rounded-full border-2 border-dashed border-gray-300 bg-gray-50 transition hover:border-blue-400 hover:bg-gray-100">
<img v-if="imagePreview" :src="imagePreview" class="h-full w-full object-cover" />
<div v-else class="flex flex-col items-center text-gray-400">
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 4v16m8-8H4" />
</svg>
<span class="text-[10px] font-medium">UPLOAD</span>
</div>
<div
class="absolute inset-0 flex items-center justify-center bg-black/20 opacity-0 transition group-hover:opacity-100">
<span class="text-xs font-semibold text-white">Change</span>
</div>
</label>
<input id="avatar-upload" type="file" class="hidden" accept="image/*" @change="handleFileChange" />
<p class="text-xs text-gray-500">Optional</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
<Input v-model="formData.name" type="text" placeholder="John Doe" required />
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Nickname</label>
<Input v-model="formData.nickname" type="text" placeholder="johny123" required />
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Email address</label>
<Input v-model="formData.email" type="email" placeholder="[email protected]" />
<p v-if="errors.email" class="mt-1 text-xs text-red-500">{{ errors.email }}</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
<Input v-model="formData.password" type="password" placeholder="••••••••" />
<p v-if="errors.password" class="mt-1 text-xs text-red-500">{{ errors.password }}</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Confirm Password</label>
<Input v-model="formData.confirmPassword" type="password" placeholder="••••••••" />
<p v-if="errors.confirmPassword" class="mt-1 text-xs text-red-500">{{ errors.confirmPassword }}</p>
</div>
<div class="pt-4">
<Button type="submit" class="w-full">Create Account</Button>
</div>
</form>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useRegisterStore } from '@/stores/register'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
const registerStore = useRegisterStore()
const router = useRouter()
const formData = ref({
email: '',
nickname: '',
name: '',
password: '',
confirmPassword: '',
photo: ''
})
const imagePreview = ref(null)
const errors = ref({})
const handleFileChange = (event) => {
const file = event.target.files[0]
if (file) {
formData.value.photo = file
imagePreview.value = URL.createObjectURL(file)
}
console.log(formData, file)
}
const validateForm = () => {
errors.value = {} // Reset errors
let isValid = true
if (!formData.value.email.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
errors.value.email = "Please enter a valid email"
isValid = false
}
if (!formData.value.password || formData.value.password.length < 3) {
errors.value.password = "Password must be at least 3 characters"
isValid = false
}
if (formData.value.password !== formData.value.confirmPassword) {
errors.value.confirmPassword = "Passwords do not match"
isValid = false
}
return isValid
}
const handleSubmit = async () => {
if (!validateForm()) {
toast.error("Please fix the errors in the form")
return
}
const data = new FormData()
data.append('email', formData.value.email)
data.append('nickname', formData.value.nickname)
data.append('name', formData.value.name)
data.append('password', formData.value.password)
if (formData.value.photo) {
data.append('photo_avatar_filename', formData.value.photo)
}
const promise = registerStore.register(data)
toast.promise(promise, {
loading: 'Creating your account...',
success: (res) => {
router.push('/login')
return `Registration Successful - ${res.data.user.name}`
},
error: (error) => error.response?.data?.message || "Registration failed"
})
}
</script>
+514 -152
View File
@@ -9,57 +9,55 @@
</div> </div>
<!-- Error State --> <!-- Error State -->
<div v-else-if="error" class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full text-gray-800"> <div v-else-if="error"
class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full text-gray-800">
<svg class="w-12 h-12 mx-auto mb-4 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg class="w-12 h-12 mx-auto mb-4 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="2"/> <circle cx="12" cy="12" r="10" stroke-width="2" />
<line x1="12" y1="8" x2="12" y2="12" stroke-width="2"/> <line x1="12" y1="8" x2="12" y2="12" stroke-width="2" />
<line x1="12" y1="16" x2="12.01" y2="16" stroke-width="2"/> <line x1="12" y1="16" x2="12.01" y2="16" stroke-width="2" />
</svg> </svg>
<h3 class="text-2xl mb-2 text-black">Oops! Something went wrong</h3> <h3 class="text-2xl mb-2 text-black">Oops! Something went wrong</h3>
<p class="text-gray-600 mb-6">{{ error }}</p> <p class="text-gray-600 mb-6">{{ error }}</p>
<button @click="retry" class="flex items-center gap-2 px-6 py-3 bg-black text-white cursor-pointer text-base font-medium transition-colors hover:bg-gray-800 mx-auto"> <button @click="retry"
class="flex items-center gap-2 px-6 py-3 bg-black text-white cursor-pointer text-base font-medium transition-colors hover:bg-gray-800 mx-auto">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M1 4v6h6M23 20v-6h-6" stroke-width="2"/> <path d="M1 4v6h6M23 20v-6h-6" stroke-width="2" />
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke-width="2"/> <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke-width="2" />
</svg> </svg>
Try Again Try Again
</button> </button>
</div> </div>
<!-- User Profile --> <!-- User Profile -->
<div v-else-if="authStore.currentUser" class="bg-white border border-gray-300 shadow-lg max-w-4xl w-full overflow-hidden"> <div v-else-if="authStore.currentUser"
class="bg-white border border-gray-300 shadow-lg max-w-4xl w-full overflow-hidden">
<div class="bg-black p-12 text-center relative text-white border-b border-gray-300"> <div class="bg-black p-12 text-center relative text-white border-b border-gray-300">
<div class="mb-6 relative inline-block"> <div class="mb-6 relative inline-block">
<img <img v-if="authStore.currentUser.photo_avatar_filename"
v-if="authStore.currentUser.photo_avatar_filename" :src="`${API_BASE_URL.replace('/api/v1', '').replace('v1/')}/storage/photos_avatars/${authStore.currentUser.photo_avatar_filename}`"
:src="`${API_BASE_URL.replace('/api', '')}/storage/photos_avatars/${authStore.currentUser.photo_avatar_filename}`" :alt="authStore.currentUser.name" class="w-24 h-24 border-[3px] border-white object-cover" />
:alt="authStore.currentUser.name" <div v-else
class="w-24 h-24 border-[3px] border-white object-cover" class="w-24 h-24 border-[3px] border-white bg-white text-black flex items-center justify-center text-4xl font-semibold">
/>
<div v-else class="w-24 h-24 border-[3px] border-white bg-white text-black flex items-center justify-center text-4xl font-semibold">
{{ authStore.currentUser.name.charAt(0).toUpperCase() }} {{ authStore.currentUser.name.charAt(0).toUpperCase() }}
</div> </div>
<button @click="triggerFileInput" class="absolute bottom-0 right-0 w-9 h-9 bg-white border-2 border-black cursor-pointer flex items-center justify-center transition-colors hover:bg-gray-100"> <button @click="triggerFileInput"
class="absolute bottom-0 right-0 w-9 h-9 bg-white border-2 border-black cursor-pointer flex items-center justify-center transition-colors hover:bg-gray-100">
<svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" stroke-width="1.5"/> <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"
<circle cx="12" cy="13" r="4" stroke-width="1.5"/> stroke-width="1.5" />
<circle cx="12" cy="13" r="4" stroke-width="1.5" />
</svg> </svg>
</button> </button>
<input <input ref="fileInput" type="file" accept="image/*" @change="handleAvatarUpload" class="hidden" />
ref="fileInput"
type="file"
accept="image/*"
@change="handleAvatarUpload"
class="hidden"
/>
</div> </div>
<div> <div>
<h1 class="text-3xl font-semibold mb-2">{{ authStore.currentUser.name }}</h1> <h1 class="text-3xl font-semibold mb-2">{{ authStore.currentUser.name }}</h1>
<p class="text-base opacity-80">@{{ authStore.currentUser.nickname }}</p> <p class="text-base opacity-80">@{{ authStore.currentUser.nickname }}</p>
</div> </div>
<div class="inline-flex items-center gap-2 bg-white text-black px-4 py-2 mt-6 font-medium text-base border border-gray-300"> <div
class="inline-flex items-center gap-2 bg-white text-black px-4 py-2 mt-6 font-medium text-base border border-gray-300">
<svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="1.5"/> <circle cx="12" cy="12" r="10" stroke-width="1.5" />
<text x="12" y="16" text-anchor="middle" fill="currentColor" font-size="12" font-weight="bold">$</text> <text x="12" y="16" text-anchor="middle" fill="currentColor" font-size="12" font-weight="bold">$</text>
</svg> </svg>
<span>{{ authStore.currentUser.coins_balance }} coins</span> <span>{{ authStore.currentUser.coins_balance }} coins</span>
@@ -71,26 +69,32 @@
<div class="flex border-b border-gray-300 bg-gray-50"> <div class="flex border-b border-gray-300 bg-gray-50">
<button <button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'info' }]" :class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'info' }]"
@click="activeTab = 'info'" @click="activeTab = 'info'">
>
Profile Information Profile Information
</button> </button>
<button <button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'edit' }]" :class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'edit' }]"
@click="activeTab = 'edit'" @click="activeTab = 'edit'">
>
Edit Profile Edit Profile
</button> </button>
<button v-if="!authStore.isAdmin"
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'transaction-history' }]"
@click="activeTab = 'transaction-history'">
Transaction History
</button>
<button v-if="!authStore.isAdmin"
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'game-history' }]"
@click="activeTab = 'game-history'">
Game History
</button>
<button <button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'password' }]" :class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'password' }]"
@click="activeTab = 'password'" @click="activeTab = 'password'">
>
Change Password Change Password
</button> </button>
<button <button v-if="!authStore.isAdmin"
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'delete' }]" :class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'delete' }]"
@click="activeTab = 'delete'" @click="activeTab = 'delete'">
>
Delete Account Delete Account
</button> </button>
</div> </div>
@@ -101,8 +105,8 @@
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/> <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
<polyline points="22,6 12,13 2,6"/> <polyline points="22,6 12,13 2,6" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
@@ -114,12 +118,13 @@
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/> <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4"/> <circle cx="12" cy="7" r="4" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Account Type</label> <label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Account
Type</label>
<p class="text-sm text-black">{{ authStore.currentUser.type === 'P' ? 'Player' : 'Other' }}</p> <p class="text-sm text-black">{{ authStore.currentUser.type === 'P' ? 'Player' : 'Other' }}</p>
</div> </div>
</div> </div>
@@ -127,14 +132,15 @@
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/> <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
<line x1="16" y1="2" x2="16" y2="6"/> <line x1="16" y1="2" x2="16" y2="6" />
<line x1="8" y1="2" x2="8" y2="6"/> <line x1="8" y1="2" x2="8" y2="6" />
<line x1="3" y1="10" x2="21" y2="10"/> <line x1="3" y1="10" x2="21" y2="10" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Member Since</label> <label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Member
Since</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.created_at) }}</p> <p class="text-sm text-black">{{ formatDate(authStore.currentUser.created_at) }}</p>
</div> </div>
</div> </div>
@@ -142,29 +148,32 @@
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<circle cx="12" cy="12" r="10"/> <circle cx="12" cy="12" r="10" />
<path d="M9 12l2 2 4-4"/> <path d="M9 12l2 2 4-4" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Status</label> <label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Status</label>
<p> <p>
<span :class="['inline-block px-3 py-1 text-sm font-medium border', authStore.currentUser.blocked ? 'bg-black text-white border-black' : 'bg-white text-black border-black']"> <span
:class="['inline-block px-3 py-1 text-sm font-medium border', authStore.currentUser.blocked ? 'bg-black text-white border-black' : 'bg-white text-black border-black']">
{{ authStore.currentUser.blocked ? 'Blocked' : 'Active' }} {{ authStore.currentUser.blocked ? 'Blocked' : 'Active' }}
</span> </span>
</p> </p>
</div> </div>
</div> </div>
<div v-if="authStore.currentUser.email_verified_at" class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div v-if="authStore.currentUser.email_verified_at"
class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/> <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
<polyline points="22 4 12 14.01 9 11.01"/> <polyline points="22 4 12 14.01 9 11.01" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Email Verified</label> <label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Email
Verified</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.email_verified_at) }}</p> <p class="text-sm text-black">{{ formatDate(authStore.currentUser.email_verified_at) }}</p>
</div> </div>
</div> </div>
@@ -172,12 +181,13 @@
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md"> <div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600"> <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"> <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<polyline points="23 4 23 10 17 10"/> <polyline points="23 4 23 10 17 10" />
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/> <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
</svg> </svg>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Last Updated</label> <label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Last
Updated</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.updated_at) }}</p> <p class="text-sm text-black">{{ formatDate(authStore.currentUser.updated_at) }}</p>
</div> </div>
</div> </div>
@@ -189,108 +199,272 @@
<form @submit.prevent="updateProfile" class="max-w-lg"> <form @submit.prevent="updateProfile" class="max-w-lg">
<div class="mb-6"> <div class="mb-6">
<label for="name" class="block text-sm font-semibold text-gray-800 mb-2">Name</label> <label for="name" class="block text-sm font-semibold text-gray-800 mb-2">Name</label>
<input <input id="name" v-model="profileForm.name" type="text" required :disabled="updatingProfile"
id="name" class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" />
v-model="profileForm.name"
type="text"
required
:disabled="updatingProfile"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div> </div>
<div class="mb-6"> <div class="mb-6">
<label for="nickname" class="block text-sm font-semibold text-gray-800 mb-2">Nickname</label> <label for="nickname" class="block text-sm font-semibold text-gray-800 mb-2">Nickname</label>
<input <input id="nickname" v-model="profileForm.nickname" type="text" required :disabled="updatingProfile"
id="nickname" class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" />
v-model="profileForm.nickname"
type="text"
required
:disabled="updatingProfile"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div> </div>
<div class="flex gap-4 mt-8"> <div class="flex gap-4 mt-8">
<button type="button" @click="resetProfileForm" :disabled="updatingProfile" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"> <button type="button" @click="resetProfileForm" :disabled="updatingProfile"
class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed">
Cancel Cancel
</button> </button>
<button type="submit" :disabled="updatingProfile" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"> <button type="submit" :disabled="updatingProfile"
class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed">
{{ updatingProfile ? 'Saving...' : 'Save Changes' }} {{ updatingProfile ? 'Saving...' : 'Save Changes' }}
</button> </button>
</div> </div>
<div v-if="profileMessage" :class="['mt-4 px-3 py-3 border text-sm', profileMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']"> <div v-if="profileMessage"
:class="['mt-4 px-3 py-3 border text-sm', profileMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']">
{{ profileMessage }} {{ profileMessage }}
</div> </div>
</form> </form>
</div> </div>
<!-- Transaction History Tab -->
<div v-if="activeTab === 'transaction-history' && !authStore.isAdmin" class="p-8">
<div class="flex flex-wrap gap-4 mb-6 items-end">
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">Type</label>
<select v-model="filters.type" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none">
<option value="all">All Types</option>
<option value="credit">Credit (+)</option>
<option value="debit">Debit (-)</option>
</select>
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">From</label>
<input type="date" v-model="filters.startDate" :max="filters.endDate" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none" />
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">To</label>
<input type="date" v-model="filters.endDate" :min="filters.startDate" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none" />
</div>
<button @click="clearFilters" class="text-xs text-purple-500 hover:underline pb-2">
Clear Filters
</button>
</div>
<div class="rounded-lg border bg-card text-card-foreground shadow-sm">
<div v-if="transactions.length === 0" class="p-6 text-center text-sm text-muted-foreground">
No transactions yet.
</div>
<div v-else class="max-h-[450px] overflow-y-auto custom-scrollbar p-1">
<div v-for="(transaction) in transactions" :key="transaction.id"
class="flex items-center justify-between p-4 mb-3 border rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500"
:class="[transaction.type === 'credit' ? 'border-green-500/30' : 'border-red-500/30']">
<div class="flex items-center gap-4">
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold"
:class="transaction.type === 'credit' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'">
<span v-if="transaction.type === 'credit'">+</span>
<span v-else>-</span>
</div>
<div class="flex flex-col">
<div class="font-semibold text-sm">
{{ transaction.category }} </div>
<div class="text-xs text-muted-foreground">
{{ new Date(transaction.began_at).toLocaleDateString() }}
{{ new Date(transaction.began_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }}
</div>
</div>
</div>
<div class="text-right">
<div class="font-bold text-sm"
:class="transaction.type === 'credit' ? 'text-green-600' : 'text-red-600'">
{{ transaction.type === 'credit' ? '+' : '-' }}{{ transaction.amount }} coins
</div>
<div class="text-[10px] text-muted-foreground uppercase tracking-wider">
{{ transaction.reference }} </div>
</div>
</div>
<div ref="observerTarget" class="h-10 flex items-center justify-center">
<span v-if="isLoading" class="text-xs text-purple-500 animate-pulse">Loading
more...</span>
</div>
</div>
</div>
</div>
<!-- Game History Tab -->
<div v-if="activeTab === 'game-history' && !authStore.isAdmin" class="p-8">
<div class="flex flex-wrap gap-4 mb-6 items-end">
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">Variant</label>
<select v-model="filters.variant" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm outline-none">
<option value="all">All Variants</option>
<option value="3">Bisca 3</option>
<option value="9">Bisca 9</option>
</select>
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">Outcome</label>
<select v-model="filters.outcome" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm outline-none">
<option value="all">All Results</option>
<option value="win">Win</option>
<option value="loss">Loss</option>
<option value="draw">Draw</option>
<option value="forfeit">Forfeit</option>
</select>
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">From</label>
<input type="date" v-model="filters.startDate" :max="filters.endDate" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none" />
</div>
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">To</label>
<input type="date" v-model="filters.endDate" :min="filters.startDate" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none" />
</div>
<button @click="clearFilters" class="text-xs text-purple-500 hover:underline pb-2">
Clear Filters
</button>
<div class="flex flex-row gap-4 ml-auto">
<div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">Sort By</label>
<div class="flex gap-2">
<select v-model="filters.sort.column" @change="resetAndFetch"
class="bg-background border rounded-md px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-purple-500">
<option value="began_at">Date</option>
<option value="outcome">Outcome</option>
<option value="total_time">Duration</option>
</select>
<button @click="handleSortChange(filters.sort.column)"
class="bg-background border rounded-md px-4 py-2 text-sm outline-none transition-all hover:ring-2 hover:ring-purple-500 flex items-center justify-center min-w-[42px]"
title="Toggle Order">
<span v-if="filters.sort.order === 'desc'" class="leading-none"></span>
<span v-else class="leading-none"></span>
</button>
</div>
</div>
</div>
</div>
<div class="rounded-lg border bg-card text-card-foreground shadow-sm">
<div v-if="games.length === 0" class="p-6 text-center text-sm text-muted-foreground">
No games played yet.
</div>
<div v-else class="max-h-[450px] overflow-y-auto custom-scrollbar p-1">
<div v-for="game in games" :key="game.id"
class="p-4 mb-3 border rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500">
<div class="flex items-center justify-between">
<div class="flex items-center gap-4">
<div :class="game.outcome === 'win' ? 'text-green-500' : 'text-red-500'"
class="font-bold uppercase text-xs">
{{ game.outcome }}
</div>
<div>
<div class="font-semibold text-sm">vs {{ game.opponent }}</div>
<div class="text-xs text-muted-foreground">
{{ game.variant }} {{ game.duration }}
</div>
</div>
</div>
<div class="text-right">
<div class="font-bold text-sm">{{ game.amount }} pts</div>
<div class="text-[10px] text-muted-foreground">
{{ new Date(game.began_at).toLocaleDateString() }} {{ new
Date(game.began_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }}
</div>
</div>
</div>
<div class="mt-3 pt-3 border-t flex gap-4 text-[10px] uppercase font-medium text-muted-foreground">
<span>Capotes: {{ game.details.capotes }}</span>
<span>Bandeiras: {{ game.details.bandeiras }}</span>
</div>
</div>
<div ref="observerTarget" class="h-10 flex items-center justify-center">
<span v-if="isLoading" class="text-xs text-purple-500 animate-pulse">Loading
more...</span>
</div>
</div>
</div>
</div>
<!-- Change Password Tab --> <!-- Change Password Tab -->
<div v-if="activeTab === 'password'" class="p-8"> <div v-if="activeTab === 'password'" class="p-8">
<form @submit.prevent="changePassword" class="max-w-lg"> <form @submit.prevent="changePassword" class="max-w-lg">
<div class="mb-6"> <div class="mb-6">
<label for="current_password" class="block text-sm font-semibold text-gray-800 mb-2">Current Password</label> <label for="current_password" class="block text-sm font-semibold text-gray-800 mb-2">Current
<input Password</label>
id="current_password" <input id="current_password" v-model="passwordForm.current_password" type="password" required
v-model="passwordForm.current_password"
type="password"
required
:disabled="updatingPassword" :disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" />
/>
</div> </div>
<div class="mb-6"> <div class="mb-6">
<label for="new_password" class="block text-sm font-semibold text-gray-800 mb-2">New Password</label> <label for="new_password" class="block text-sm font-semibold text-gray-800 mb-2">New Password</label>
<input <input id="new_password" v-model="passwordForm.new_password" type="password" required minlength="8"
id="new_password"
v-model="passwordForm.new_password"
type="password"
required
minlength="8"
:disabled="updatingPassword" :disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" />
/>
<small class="block mt-1 text-xs text-gray-600">Password must be at least 8 characters long</small> <small class="block mt-1 text-xs text-gray-600">Password must be at least 8 characters long</small>
</div> </div>
<div class="mb-6"> <div class="mb-6">
<label for="confirm_password" class="block text-sm font-semibold text-gray-800 mb-2">Confirm New Password</label> <label for="confirm_password" class="block text-sm font-semibold text-gray-800 mb-2">Confirm New
<input Password</label>
id="confirm_password" <input id="confirm_password" v-model="passwordForm.confirm_password" type="password" required
v-model="passwordForm.confirm_password"
type="password"
required
:disabled="updatingPassword" :disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed" />
/>
</div> </div>
<div class="flex gap-4 mt-8"> <div class="flex gap-4 mt-8">
<button type="button" @click="resetPasswordForm" :disabled="updatingPassword" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"> <button type="button" @click="resetPasswordForm" :disabled="updatingPassword"
class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed">
Cancel Cancel
</button> </button>
<button type="submit" :disabled="updatingPassword" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"> <button type="submit" :disabled="updatingPassword"
class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed">
{{ updatingPassword ? 'Updating...' : 'Change Password' }} {{ updatingPassword ? 'Updating...' : 'Change Password' }}
</button> </button>
</div> </div>
<div v-if="passwordMessage" :class="['mt-4 px-3 py-3 border text-sm', passwordMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']"> <div v-if="passwordMessage"
:class="['mt-4 px-3 py-3 border text-sm', passwordMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']">
{{ passwordMessage }} {{ passwordMessage }}
</div> </div>
</form> </form>
</div> </div>
<!-- Delete Account Tab --> <!-- Delete Account Tab -->
<div v-if="activeTab === 'delete'" class="p-8 flex flex-col items-center"> <div v-if="activeTab === 'delete' && !authStore.isAdmin" class="p-8 flex flex-col items-center">
<div class="max-w-lg"> <div class="max-w-lg">
<div class="border border-red-600 bg-red-50 p-6 mb-6"> <div class="border border-red-600 bg-red-50 p-6 mb-6">
<div class="flex items-start gap-3"> <div class="flex items-start gap-3">
<svg class="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg class="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" viewBox="0 0 24 24" fill="none"
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/> stroke="currentColor" stroke-width="2">
<line x1="12" y1="9" x2="12" y2="13"/> <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<line x1="12" y1="17" x2="12.01" y2="17"/> <line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg> </svg>
<div> <div>
<h3 class="text-lg font-semibold text-red-900 mb-2">Danger Zone</h3> <h3 class="text-lg font-semibold text-red-900 mb-2">Danger Zone</h3>
@@ -299,7 +473,8 @@
</p> </p>
<ul class="text-sm text-red-800 list-disc list-inside space-y-1"> <ul class="text-sm text-red-800 list-disc list-inside space-y-1">
<li>Permanently delete all your account data</li> <li>Permanently delete all your account data</li>
<li>Forfeit your current coin balance of <strong>{{ authStore.currentUser.coins_balance }} coins</strong></li> <li>Forfeit your current coin balance of <strong>{{ authStore.currentUser.coins_balance }}
coins</strong></li>
<li>Remove your access to all games and matches</li> <li>Remove your access to all games and matches</li>
<li>Delete your profile and all associated information</li> <li>Delete your profile and all associated information</li>
</ul> </ul>
@@ -312,29 +487,21 @@
Are you absolutely sure? Are you absolutely sure?
</h4> </h4>
<p class="text-sm text-gray-600 mb-4"> <p class="text-sm text-gray-600 mb-4">
To confirm deletion, please type your email address: <strong class="text-black">{{ authStore.currentUser.email }}</strong> To confirm deletion, please type your email address: <strong class="text-black">{{
authStore.currentUser.email }}</strong>
</p> </p>
<input <input v-model="deleteConfirmEmail" type="text" placeholder="Enter your email to confirm"
v-model="deleteConfirmEmail" class="w-full px-3 py-3 border border-gray-300 text-base mb-4 focus:outline-none focus:border-red-600" />
type="text"
placeholder="Enter your email to confirm"
class="w-full px-3 py-3 border border-gray-300 text-base mb-4 focus:outline-none focus:border-red-600"
/>
<div class="flex gap-4"> <div class="flex gap-4">
<button <button type="button" @click="activeTab = 'info'"
type="button" class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50">
@click="activeTab = 'info'"
class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50"
>
Cancel Cancel
</button> </button>
<button <button @click="showDeleteConfirmation = true"
@click="showDeleteConfirmation = true"
:disabled="deleteConfirmEmail !== authStore.currentUser.email" :disabled="deleteConfirmEmail !== authStore.currentUser.email"
class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-red-600" class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-red-600">
>
Delete My Account Delete My Account
</button> </button>
</div> </div>
@@ -345,11 +512,9 @@
</div> </div>
<!-- Delete Confirmation Modal --> <!-- Delete Confirmation Modal -->
<div <div v-if="showDeleteConfirmation"
v-if="showDeleteConfirmation"
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
@click.self="showDeleteConfirmation = false" @click.self="showDeleteConfirmation = false">
>
<div class="bg-white border border-gray-300 max-w-md w-full shadow-xl"> <div class="bg-white border border-gray-300 max-w-md w-full shadow-xl">
<div class="p-6 border-b border-gray-300"> <div class="p-6 border-b border-gray-300">
<h3 class="text-xl font-semibold text-gray-900">Final Confirmation</h3> <h3 class="text-xl font-semibold text-gray-900">Final Confirmation</h3>
@@ -357,17 +522,19 @@
<div class="p-6"> <div class="p-6">
<div class="flex items-start gap-3 mb-4"> <div class="flex items-start gap-3 mb-4">
<svg class="w-12 h-12 text-red-600 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg class="w-12 h-12 text-red-600 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor"
<circle cx="12" cy="12" r="10"/> stroke-width="2">
<line x1="15" y1="9" x2="9" y2="15"/> <circle cx="12" cy="12" r="10" />
<line x1="9" y1="9" x2="15" y2="15"/> <line x1="15" y1="9" x2="9" y2="15" />
<line x1="9" y1="9" x2="15" y2="15" />
</svg> </svg>
<div> <div>
<p class="text-base text-gray-900 font-semibold mb-2"> <p class="text-base text-gray-900 font-semibold mb-2">
This is your last chance to cancel. This is your last chance to cancel.
</p> </p>
<p class="text-sm text-gray-600"> <p class="text-sm text-gray-600">
Once you click "Yes, Delete My Account", your account and all associated data will be permanently deleted. You will lose your <strong>{{ authStore.currentUser.coins_balance }} coins</strong> forever. Once you click "Yes, Delete My Account", your account and all associated data will be permanently
deleted. You will lose your <strong>{{ authStore.currentUser.coins_balance }} coins</strong> forever.
</p> </p>
</div> </div>
</div> </div>
@@ -379,18 +546,12 @@
</div> </div>
<div class="p-6 border-t border-gray-300 flex gap-3"> <div class="p-6 border-t border-gray-300 flex gap-3">
<button <button @click="showDeleteConfirmation = false" :disabled="deletingAccount"
@click="showDeleteConfirmation = false" class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
:disabled="deletingAccount"
class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
Cancel Cancel
</button> </button>
<button <button @click="deleteAccount" :disabled="deletingAccount"
@click="deleteAccount" class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed">
:disabled="deletingAccount"
class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
Yes, Delete My Account Yes, Delete My Account
</button> </button>
</div> </div>
@@ -398,7 +559,8 @@
</div> </div>
<!-- No Data State --> <!-- No Data State -->
<div v-else-if="!authStore.isLoggedIn" class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full"> <div v-else-if="!authStore.isLoggedIn"
class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full">
<div class="flex flex-col items-center gap-6"> <div class="flex flex-col items-center gap-6">
<div class="spinner"></div> <div class="spinner"></div>
<p>Redirecting to login...</p> <p>Redirecting to login...</p>
@@ -408,10 +570,10 @@
</template> </template>
<script setup> <script setup>
import { ref, onMounted, inject, reactive } from 'vue' import { ref, onMounted, inject, reactive, watch, nextTick } from 'vue'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import { useAPIStore } from '@/stores/api' import { useAPIStore } from '@/stores/api'
import { useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import axios from 'axios' import axios from 'axios'
const authStore = useAuthStore() const authStore = useAuthStore()
@@ -424,7 +586,6 @@ const error = ref(null)
const activeTab = ref('info') const activeTab = ref('info')
const fileInput = ref(null) const fileInput = ref(null)
// Profile form
const profileForm = reactive({ const profileForm = reactive({
name: '', name: '',
nickname: '' nickname: ''
@@ -433,7 +594,6 @@ const updatingProfile = ref(false)
const profileMessage = ref('') const profileMessage = ref('')
const profileMessageType = ref('') const profileMessageType = ref('')
// Password form
const passwordForm = reactive({ const passwordForm = reactive({
current_password: '', current_password: '',
new_password: '', new_password: '',
@@ -443,11 +603,211 @@ const updatingPassword = ref(false)
const passwordMessage = ref('') const passwordMessage = ref('')
const passwordMessageType = ref('') const passwordMessageType = ref('')
// Delete account
const deleteConfirmEmail = ref('') const deleteConfirmEmail = ref('')
const showDeleteConfirmation = ref(false) const showDeleteConfirmation = ref(false)
const deletingAccount = ref(false) const deletingAccount = ref(false)
const transactions = ref([]);
const games = ref([]);
const observerTarget = ref(null);
const observer = ref(null);
const isLoading = ref(false);
const pagination = ref({
transactions: { page: 1, hasMore: true },
games: { page: 1, hasMore: true }
});
const filters = ref({
type: 'all',
variant: 'all',
outcome: 'all',
startDate: '',
endDate: '',
sort: {
column: 'began_at',
order: 'desc'
}
});
const handleSortChange = (column) => {
if (filters.value.sort.column === column) {
filters.value.sort.order = filters.value.sort.order === 'asc' ? 'desc' : 'asc';
} else {
filters.value.sort.column = column;
filters.value.sort.order = 'desc';
}
resetAndFetch();
};
watch(activeTab, async (newTab) => {
if (newTab !== 'transaction-history' && newTab !== 'game-history') return;
await nextTick();
if (transactions.value.length !== 0 && games.value.length !== 0) return;
await fetchData();
setupObserver();
});
const fetchData = async () => {
const currentTab = activeTab.value;
const isTransaction = currentTab === 'transaction-history';
const isGame = currentTab === 'game-history';
const state = isTransaction ? pagination.value.transactions : pagination.value.games;
if (isLoading.value || !state.hasMore) return;
isLoading.value = true;
try {
let newData = [];
if (isTransaction) {
const apiParams = {
page: state.page,
type: filters.value.type === 'credit' ? 'C' : filters.value.type === 'debit' ? 'D' : undefined,
date_from: filters.value.startDate || undefined,
date_to: filters.value.endDate || undefined,
};
const response = await apiStore.getCurrentUserTransactions(apiParams);
const apiTxns = response.data.data;
newData = apiTxns.map(txn => ({
id: txn.id.toString(),
type: txn.type.type === 'D' ? 'debit' : 'credit',
category: txn.type.name,
amount: Math.abs(txn.coins),
began_at: txn.transaction_datetime,
reference: txn.match_id ? `Match #${txn.match_id}` : txn.game_id ? `Game #${txn.game_id}` : 'N/A'
}));
transactions.value.push(...newData);
}
if (isGame) {
const apiParams = {
page: state.page,
type: filters.value.variant !== 'all' ? filters.value.variant : undefined,
outcome: filters.value.outcome !== 'all' ? filters.value.outcome : undefined,
status: 'Ended',
date_from: filters.value.startDate || undefined,
date_to: filters.value.endDate || undefined,
sort_by: filters.value.sort.column,
sort_direction: filters.value.sort.order,
};
const response = await apiStore.getCurrentUserMatches(apiParams);
const apiGames = response.data.data;
newData = apiGames.map(game => {
const isPlayer1 = game.player1_user_id === authStore.currentUser.id;
const opponent = isPlayer1 ? game.player2 : game.player1;
let outcome = 'loss';
if (game.is_draw) outcome = 'draw';
else if (game.winner_user_id === authStore.currentUser.id) outcome = 'win';
return {
id: game.id,
variant: `Type ${game.type}`,
outcome: outcome,
opponent: opponent?.nickname || 'Unknown Player',
amount: isPlayer1 ? game.player1_points : game.player2_points,
duration: `${Math.floor(game.total_time / 60)}m ${game.total_time % 60}s`,
began_at: game.began_at,
details: {
capotes: 0,
bandeiras: 0
}
};
});
games.value.push(...newData);
}
if (newData.length < 10) state.hasMore = false;
state.page++;
} catch (error) {
console.error("Fetch failed", error);
} finally {
isLoading.value = false;
}
};
const setupObserver = () => {
if (observer.value) observer.value.disconnect();
const scrollContainer = document.querySelector('.custom-scrollbar');
observer.value = new IntersectionObserver(async (entries) => {
const isGame = activeTab.value === 'game-history';
const hasMore = isGame ? pagination.value.games.hasMore : pagination.value.transactions.hasMore;
if (entries[0].isIntersecting && !isLoading.value && hasMore) {
fetchData();
}
}, {
root: scrollContainer,
threshold: 0.1,
rootMargin: '100px'
});
if (observerTarget.value) observer.value.observe(observerTarget.value);
};
const resetAndFetch = async () => {
if (activeTab.value === 'transaction-history') {
transactions.value = [];
pagination.value.transactions = { page: 1, hasMore: true };
}
if (activeTab.value === 'game-history') {
games.value = [];
pagination.value.games = { page: 1, hasMore: true };
}
await nextTick();
await fetchData();
setupObserver();
};
const clearFilters = () => {
const isGameTab = activeTab.value === 'game-history';
const defaultSortColumn = isGameTab ? 'began_at' : 'transaction_datetime';
const isAlreadyDefault =
filters.value.startDate === '' &&
filters.value.endDate === '' &&
filters.value.sort.column === defaultSortColumn &&
filters.value.sort.order === 'desc' &&
(isGameTab
? (filters.value.variant === 'all' && filters.value.outcome === 'all')
: (filters.value.type === 'all')
);
if (isAlreadyDefault) {
return;
}
if (isGameTab) {
filters.value.variant = 'all';
filters.value.outcome = 'all';
} else {
filters.value.type = 'all';
}
filters.value.startDate = '';
filters.value.endDate = '';
filters.value.sort = {
column: defaultSortColumn,
order: 'desc'
};
resetAndFetch();
};
const formatDate = (dateString) => { const formatDate = (dateString) => {
const date = new Date(dateString) const date = new Date(dateString)
return date.toLocaleDateString('en-US', { return date.toLocaleDateString('en-US', {
@@ -587,13 +947,10 @@ const deleteAccount = async () => {
try { try {
await axios.delete(`${API_BASE_URL}/users/me`) await axios.delete(`${API_BASE_URL}/users/me`)
// Logout user
await authStore.logout() await authStore.logout()
// Close modal
showDeleteConfirmation.value = false showDeleteConfirmation.value = false
// Redirect to home/login
router.push('/login') router.push('/login')
} catch (err) { } catch (err) {
deletingAccount.value = false deletingAccount.value = false
@@ -607,6 +964,11 @@ onMounted(async () => {
router.push('/login') router.push('/login')
return return
} }
const route = useRoute()
if (route.query.tab) {
activeTab.value = route.query.tab;
router.replace({ query: {} });
}
if (!authStore.currentUser) { if (!authStore.currentUser) {
await fetchProfile() await fetchProfile()
+28 -16
View File
@@ -2,14 +2,17 @@ import HomePage from '@/pages/home/HomePage.vue'
import LoginPage from '@/pages/login/LoginPage.vue' import LoginPage from '@/pages/login/LoginPage.vue'
import LaravelPage from '@/pages/testing/LaravelPage.vue' import LaravelPage from '@/pages/testing/LaravelPage.vue'
import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue' import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue'
import UserPage from '@/pages/user/UserPage.vue'
import { createRouter, createWebHistory } from 'vue-router'
import TestAnimations from '@/pages/TestAnimations.vue' import TestAnimations from '@/pages/TestAnimations.vue'
import TestDealing from '@/pages/TestDealing.vue' import TestDealing from '@/pages/TestDealing.vue'
import TestAllAnimations from '@/pages/TestAllAnimations.vue' import TestAllAnimations from '@/pages/TestAllAnimations.vue'
import TestGameBoard from '@/pages/TestGameBoard.vue' import TestGameBoard from '@/pages/TestGameBoard.vue'
import UserPage from '@/pages/user/UserPage.vue'
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue' import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
import { createRouter, createWebHistory } from 'vue-router' import RegisterPage from '@/pages/register/RegisterPage.vue'
import { toast } from 'vue-sonner' import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
import { useAuthStore } from '@/stores/auth'
import AdminPage from '@/pages/admin/AdminPage.vue'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@@ -18,6 +21,7 @@ const router = createRouter({
path: '/', path: '/',
name: 'home', name: 'home',
component: HomePage, component: HomePage,
meta: { requiresAdmin: false }
}, },
{ {
path: '/login', path: '/login',
@@ -25,25 +29,16 @@ const router = createRouter({
component: LoginPage, component: LoginPage,
}, },
{ {
path: '/game/3', path: '/register',
name: 'bisca3', name: 'register',
component: SinglePlayerGamePage, component: RegisterPage,
props: { gameType: 3 },
meta: { requiresAuth: true },
},
{
path: '/game/9',
name: 'bisca9',
component: SinglePlayerGamePage,
props: { gameType: 9 },
meta: { requiresAuth: true },
}, },
{ {
path: '/game/3', path: '/game/3',
name: 'bisca3', name: 'bisca3',
component: SinglePlayerGamePage, component: SinglePlayerGamePage,
props: { gameType: 3 }, props: { gameType: 3 },
meta: { requiresAuth: true }, meta: { requiresAuth: true, requiresAdmin: false },
}, },
{ {
path: '/game/9', path: '/game/9',
@@ -55,6 +50,18 @@ const router = createRouter({
{ {
path: '/user', path: '/user',
component: UserPage, component: UserPage,
meta: { requiresAuth: true },
},
{
path: '/coins-purchase',
component: CoinsPurchasePage,
meta: { requiresAuth: true },
},
{
path: '/admin',
name: 'admin',
component: AdminPage,
meta: { requiresAuth: true, requiresAdmin: true },
}, },
{ {
path: '/testing', path: '/testing',
@@ -90,6 +97,7 @@ const router = createRouter({
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth) const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
const requiresAdmin = to.matched.some((record) => record.meta.requiresAdmin)
if (requiresAuth) { if (requiresAuth) {
const token = localStorage.getItem('token') const token = localStorage.getItem('token')
@@ -98,6 +106,10 @@ router.beforeEach((to, from, next) => {
return next({ name: 'login' }) return next({ name: 'login' })
} }
} }
if (useAuthStore().isAdmin && to.name === 'home') return next({ name: 'admin' })
if (requiresAdmin && !useAuthStore().isAdmin) return next({ name: 'home' })
next() next()
}) })
+102 -2
View File
@@ -53,12 +53,10 @@ export const useAPIStore = defineStore('api', () => {
delete axios.defaults.headers.common['Authorization'] delete axios.defaults.headers.common['Authorization']
} }
// Users
const getAuthUser = () => { const getAuthUser = () => {
return axios.get(`${API_BASE_URL}/users/me`) return axios.get(`${API_BASE_URL}/users/me`)
} }
//Games
const getGames = (resetPagination = false) => { const getGames = (resetPagination = false) => {
if (resetPagination) { if (resetPagination) {
gameQueryParameters.value.page = 1 gameQueryParameters.value.page = 1
@@ -78,11 +76,113 @@ export const useAPIStore = defineStore('api', () => {
return axios.get(`${API_BASE_URL}/games?${queryParams}`) return axios.get(`${API_BASE_URL}/games?${queryParams}`)
} }
const getCurrentUserMatches = (params = {}) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
...(params.type && { type: params.type }),
...(params.outcome && { outcome: params.outcome }),
...(params.status && { status: params.status }),
...(params.date_from && { date_from: params.date_from }),
...(params.date_to && { date_to: params.date_to }),
sort_by: params.sort_by || 'began_at',
sort_direction: params.sort_direction || 'desc',
}).toString()
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/matches?${queryParams}`)
}
const getCurrentUserTransactions = (params = {}) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
...(params.type && { type: params.type }),
...(params.blocked && { blocked: params.blocked }),
}).toString()
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`)
}
const getLeaderboard = (params = {}) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
}).toString()
return axios.get(`${API_BASE_URL}/leaderboard?${queryParams}`)
}
const getCurrentUserStats = () => {
return axios.get(`${API_BASE_URL}/statistics/me`)
}
const getPublicStats = () => {
return axios.get(`${API_BASE_URL}/statistics/public`)
}
const getAdminStats = () => {
return axios.get(`${API_BASE_URL}/admin/statistics`)
}
const getAdminUsers = (params) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
...(params.type && { type: params.type }),
...(params.blocked && { blocked: params.blocked }),
}).toString()
return axios.get(`${API_BASE_URL}/admin/users?${queryParams}`)
}
const blockUser = (user) => {
return axios.post(`${API_BASE_URL}/admin/users/${user.id}/block`)
}
const unblockUser = (user) => {
return axios.post(`${API_BASE_URL}/admin/users/${user.id}/unblock`)
}
const deleteUser = (user) => {
return axios.delete(`${API_BASE_URL}/admin/users/${user.id}`)
}
const getAdminTransactions = (params) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
...(params.sort_datetime == 'asc' && { sort_datetime: 'asc' }),
...(params.sort_coins && { sort_coins: params.sort_coins }),
}).toString()
return axios.get(`${API_BASE_URL}/admin/transactions?${queryParams}`)
}
const getAdminGames = (params) => {
const queryParams = new URLSearchParams({
page: params.page || 1,
...(params.sort_direction == 'asc' && { sort_direction: 'asc' }),
...(params.type && { type: params.type }),
}).toString()
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
}
const postAdmin = async (credentials) => {
return axios.post(`${API_BASE_URL}/admin/users`, credentials)
}
return { return {
postLogin, postLogin,
postLogout, postLogout,
getAuthUser, getAuthUser,
getGames, getGames,
getCurrentUserMatches,
getCurrentUserTransactions,
getCurrentUserStats,
getLeaderboard,
getPublicStats,
getAdminStats,
getAdminUsers,
blockUser,
unblockUser,
deleteUser,
getAdminTransactions,
getAdminGames,
postAdmin,
gameQueryParameters, gameQueryParameters,
} }
}) })
+20 -17
View File
@@ -4,11 +4,9 @@ import { useAPIStore } from './api'
export const useAuthStore = defineStore('auth', () => { export const useAuthStore = defineStore('auth', () => {
const DEFAULT_TIMEOUT = 5 * 60 * 1000 const DEFAULT_TIMEOUT = 30 * 60 * 1000
const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000 const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000
const currentUser = ref(undefined) const currentUser = ref(undefined)
const token = ref(localStorage.getItem('token') || null) const token = ref(localStorage.getItem('token') || null)
const tokenExpiry = ref(localStorage.getItem('tokenExpiry') ? parseInt(localStorage.getItem('tokenExpiry')) : null) const tokenExpiry = ref(localStorage.getItem('tokenExpiry') ? parseInt(localStorage.getItem('tokenExpiry')) : null)
@@ -22,6 +20,10 @@ export const useAuthStore = defineStore('auth', () => {
return currentUser.value?.id return currentUser.value?.id
}) })
const isAdmin = computed(() => {
return currentUser.value?.type === 'A'
})
const isTokenAlmostExpired = () => { const isTokenAlmostExpired = () => {
if (!tokenExpiry.value) return false; if (!tokenExpiry.value) return false;
return Date.now() > (tokenExpiry.value - 60 * 1000); return Date.now() > (tokenExpiry.value - 60 * 1000);
@@ -54,10 +56,14 @@ export const useAuthStore = defineStore('auth', () => {
const login = async (credentials) => { const login = async (credentials) => {
const apiStore = useAPIStore() const apiStore = useAPIStore()
const loginResp = await apiStore.postLogin(credentials) const loginResp = await apiStore.postLogin(credentials)
const userResp = await apiStore.getAuthUser() return await setLocalStorageUser(apiStore, loginResp, true)
}
const jwtToken = loginResp.data.token const setLocalStorageUser = async (api, response, rememberMe) => {
setToken(jwtToken, credentials.rememberMe) const userResp = await api.getAuthUser()
const jwtToken = response.data.token
setToken(jwtToken, rememberMe)
currentUser.value = userResp.data currentUser.value = userResp.data
localStorage.setItem('currentUser', JSON.stringify(userResp.data)) localStorage.setItem('currentUser', JSON.stringify(userResp.data))
@@ -72,15 +78,8 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.removeItem('currentUser') localStorage.removeItem('currentUser')
} }
const checkTokenExpiry = () => {
if (isTokenAlmostExpired()) {
logout()
return false
}
return true
}
const restoreSession = async () => { const restoreSession = async () => {
const apiStore = useAPIStore()
const storedToken = localStorage.getItem('token') const storedToken = localStorage.getItem('token')
const storedUser = localStorage.getItem('currentUser') const storedUser = localStorage.getItem('currentUser')
const storedTokenExpiry = localStorage.getItem('tokenExpiry') const storedTokenExpiry = localStorage.getItem('tokenExpiry')
@@ -102,7 +101,6 @@ export const useAuthStore = defineStore('auth', () => {
try { try {
currentUser.value = JSON.parse(storedUser) currentUser.value = JSON.parse(storedUser)
} catch (e) { } catch (e) {
// If stored user data is corrupted, fetch fresh data from API
try { try {
const userResp = await apiStore.getAuthUser() const userResp = await apiStore.getAuthUser()
currentUser.value = userResp.data currentUser.value = userResp.data
@@ -118,19 +116,24 @@ export const useAuthStore = defineStore('auth', () => {
return true return true
} }
const updateCurrentUserCoins = (coins) => {
if (!currentUser.value) return;
currentUser.value.coins_balance = coins
}
return { return {
currentUser, currentUser,
isLoggedIn, isLoggedIn,
currentUserID, currentUserID,
isAdmin,
token, token,
rememberMe, rememberMe,
setToken,
getToken, getToken,
login, login,
logout, logout,
resetTokenExpiry, resetTokenExpiry,
isTokenAlmostExpired, isTokenAlmostExpired,
checkTokenExpiry,
restoreSession, restoreSession,
updateCurrentUserCoins,
} }
}) })
+16
View File
@@ -0,0 +1,16 @@
import axios from 'axios'
import { defineStore } from 'pinia'
import { inject } from 'vue'
export const usePurchaseStore = defineStore('purchase', () => {
const API_BASE_URL = inject('apiBaseURL')
const purchase = async (data) => {
return await axios.post(`${API_BASE_URL}/coin-purchases`, data)
}
return {
purchase,
}
})
+16
View File
@@ -0,0 +1,16 @@
import axios from 'axios'
import { defineStore } from 'pinia'
import { inject } from 'vue'
export const useRegisterStore = defineStore('register', () => {
const API_BASE_URL = inject('apiBaseURL')
const register = async (data) => {
return await axios.post(`${API_BASE_URL}/register`, data)
}
return {
register,
}
})
+14 -46
View File
@@ -1,58 +1,26 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import axios from 'axios' import axios from 'axios'
import { inject, ref } from 'vue'
import { useAuthStore } from './auth' import { useAuthStore } from './auth'
export const useUserStore = defineStore('user', { export const useUserStore = defineStore('user', () => {
state: () => ({ const API_BASE_URL = inject('apiBaseURL')
user: null, const coins = ref(0)
loading: false,
error: null
}),
getters: {
currentUser: (state) => state.user
},
actions: {
async fetchUserProfile() {
const authStore = useAuthStore()
const token = authStore.getToken()
if (!token) {
this.error = 'No authentication token found'
throw new Error('No authentication token found')
}
this.loading = true
this.error = null
const fetchCoins = async () => {
try { try {
const response = await axios.get('/api/users/me', { const response = await axios.get(`${API_BASE_URL}/users/me/coins`)
headers: { coins.value = response.data?.coins || 0
Authorization: `Bearer ${token}`, useAuthStore().updateCurrentUserCoins(coins.value)
Accept: 'application/json' return response
}
})
this.user = response.data
return response.data
} catch (error) { } catch (error) {
this.error = error.response?.data?.message || 'Failed to fetch user profile' console.error('Error fetching coins', error)
if (error.response?.status === 401) {
authStore.logout()
}
throw error throw error
} finally {
this.loading = false
} }
}, }
clearUser() { return {
this.user = null coins,
this.error = null fetchCoins,
this.loading = false
}
} }
}) })
+57 -10
View File
@@ -6,6 +6,9 @@ class BiscaGame {
this.deck = []; this.deck = [];
this.trumpCard = null; this.trumpCard = null;
this.trumpSuit = null; this.trumpSuit = null;
this.timer = null;
this.turnDeadline = null;
this.timeoutCallback = null;
this.table = { this.table = {
playerCard: null, playerCard: null,
@@ -14,7 +17,7 @@ class BiscaGame {
}; };
this.currentTurn = null; this.currentTurn = null;
this.status = "pending"; this.status = 'pending';
this.startTime = null; this.startTime = null;
this.players = { this.players = {
@@ -47,11 +50,51 @@ class BiscaGame {
this.currentTurn = playerIds.find((id) => id != 1) || playerIds[0]; this.currentTurn = playerIds.find((id) => id != 1) || playerIds[0];
this.startTime = Date.now(); this.startTime = Date.now();
this.status = "playing"; this.status = 'playing';
}
startTurnTimer(callback) {
if (this.timer) clearTimeout(this.timer);
this.timeoutCallback = callback;
const DURATION_MS = 20000;
this.turnDeadline = Date.now() + DURATION_MS;
console.log(`[Game ${this.id}] Timer started for User ${this.currentTurn}`);
this.timer = setTimeout(() => {
this.handleTimeout();
}, DURATION_MS);
}
stopTimer() {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.turnDeadline = null;
}
handleTimeout() {
console.log(
`[Game ${this.id}] Timeout! Auto-playing for ${this.currentTurn}`,
);
const lowestCard = this.getLowestCard(this.currentTurn);
if (lowestCard && this.timeoutCallback) {
this.timeoutCallback(this.currentTurn, lowestCard.id);
}
}
getLowestCard(userId) {
const hand = this.players[userId].hand;
if (!hand || hand.length === 0) return null;
const sortedHand = [...hand].sort((a, b) => a.strength - b.strength);
return sortedHand[0];
} }
createDeck() { createDeck() {
const suits = ["c", "e", "o", "p"]; const suits = ['c', 'e', 'o', 'p'];
const ranks = [1, 2, 3, 4, 5, 6, 7, 11, 12, 13]; const ranks = [1, 2, 3, 4, 5, 6, 7, 11, 12, 13];
let deck = []; let deck = [];
@@ -87,7 +130,7 @@ class BiscaGame {
} }
playCard(userId, cardId) { playCard(userId, cardId) {
if (this.currentTurn != userId) return { error: "Not your turn!" }; if (this.currentTurn != userId) return { error: 'Not your turn!' };
const player = this.players[userId]; const player = this.players[userId];
const cardIndex = player.hand.findIndex((c) => c.id === cardId); const cardIndex = player.hand.findIndex((c) => c.id === cardId);
@@ -101,17 +144,19 @@ class BiscaGame {
const suitToFollow = this.table.playerCard.suit; const suitToFollow = this.table.playerCard.suit;
const hasSuit = player.hand.some((c) => c.suit === suitToFollow); const hasSuit = player.hand.some((c) => c.suit === suitToFollow);
if (hasSuit && card.suit !== suitToFollow) { if (hasSuit && card.suit !== suitToFollow) {
return { error: "You must follow the suit!" }; return { error: 'You must follow the suit!' };
} }
} }
this.stopTimer();
player.hand.splice(cardIndex, 1); player.hand.splice(cardIndex, 1);
if (!this.table.playerCard) { if (!this.table.playerCard) {
this.table.playerCard = card; this.table.playerCard = card;
this.table.firstPlayerId = userId; this.table.firstPlayerId = userId;
this.currentTurn = this.getOpponentId(userId); this.currentTurn = this.getOpponentId(userId);
return { action: "next_turn" }; return { action: 'next_turn' };
} else { } else {
this.table.opponentCard = card; this.table.opponentCard = card;
return this.resolveTrick(); return this.resolveTrick();
@@ -151,7 +196,8 @@ class BiscaGame {
this.table = { playerCard: null, opponentCard: null, firstPlayerId: null }; this.table = { playerCard: null, opponentCard: null, firstPlayerId: null };
if (this.players[winnerId].hand.length === 0) { if (this.players[winnerId].hand.length === 0) {
this.status = "finished"; this.status = 'finished';
this.stopTimer();
const pIds = Object.keys(this.players); const pIds = Object.keys(this.players);
const p1Obj = this.players[pIds[0]]; const p1Obj = this.players[pIds[0]];
@@ -174,7 +220,7 @@ class BiscaGame {
: p1Obj.id; : p1Obj.id;
return { return {
action: "game_ended", action: 'game_ended',
trickResult, trickResult,
winnerId: finalWinner, winnerId: finalWinner,
loserId: finalLoser, loserId: finalLoser,
@@ -187,7 +233,7 @@ class BiscaGame {
}; };
} }
return { action: "trick_resolved", trickResult }; return { action: 'trick_resolved', trickResult };
} }
getStateForPlayer(userId) { getStateForPlayer(userId) {
@@ -205,6 +251,7 @@ class BiscaGame {
points: this.players[oppId].points, points: this.players[oppId].points,
cardCount: this.players[oppId].hand.length, cardCount: this.players[oppId].hand.length,
}, },
turnDeadline: this.turnDeadline,
}; };
} }
@@ -232,4 +279,4 @@ class BiscaGame {
} }
} }
module.exports = BiscaGame; export default BiscaGame;
+8 -11
View File
@@ -1,4 +1,4 @@
import { addUser, removeUser } from "../state/connection"; import { addUser, removeUser } from '../state/connection.js';
const HEARTBEAT_INTERVAL = 30000; // 30 seconds const HEARTBEAT_INTERVAL = 30000; // 30 seconds
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
@@ -8,39 +8,36 @@ export const handleConnectionEvents = (io, socket) => {
let heartbeatTimeout; let heartbeatTimeout;
const startHeartbeat = () => { const startHeartbeat = () => {
heartbeatInterval = setInterval(() => { heartbeatInterval = setInterval(() => {
socket.emit("heartbeat"); socket.emit('heartbeat');
heartbeatTimeout = setTimeout(() => { heartbeatTimeout = setTimeout(() => {
console.log( console.log(
`[Heartbeat] No response from ${socket.id}, disconnecting...` `[Heartbeat] No response from ${socket.id}, disconnecting...`,
); );
socket.disconnect(true); socket.disconnect(true);
}, HEARTBEAT_TIMEOUT); }, HEARTBEAT_TIMEOUT);
}, HEARTBEAT_INTERVAL); }, HEARTBEAT_INTERVAL);
}; };
socket.on("heartbeat_ack", () => { socket.on('heartbeat_ack', () => {
clearTimeout(heartbeatTimeout); clearTimeout(heartbeatTimeout);
console.log(`[Heartbeat] Received pong from ${socket.id}`); console.log(`[Heartbeat] Received pong from ${socket.id}`);
}); });
socket.on("join", (user) => { socket.on('join', (user) => {
addUser(socket, user); addUser(socket, user);
console.log(`[Connection] User ${user.name} has joined the server`); console.log(`[Connection] User ${user.name} has joined the server`);
console.log(`[Connection] ${getUserCount()} users online`);
}); });
socket.on("leave", () => { socket.on('leave', () => {
const user = removeUser(socket.id); const user = removeUser(socket.id);
if (user) { if (user) {
console.log(`[Connection] User ${user.name} has left the server`); console.log(`[Connection] User ${user.name} has left the server`);
console.log(`[Connection] ${getUserCount()} users online`);
} }
}); });
socket.on("disconnect", () => { socket.on('disconnect', () => {
console.log("Connection Lost:", socket.id); console.log('Connection Lost:', socket.id);
removeUser(socket.id); removeUser(socket.id);
console.log(`[Connection] ${getUserCount()} users online`);
}); });
}; };
+145 -2
View File
@@ -28,6 +28,78 @@ async function saveGameResult(gameId, result, token) {
} }
} }
const handleGameMove = (io, gameId, userId, cardId) => {
const game = getGame(gameId);
if (!game) return;
const result = game.playCard(userId, cardId);
if (result.error) {
console.log(`[Game Error] ${result.error}`);
return;
}
const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id]) {
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
}
if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult);
}
if (result.action === "game_ended") {
io.to(roomName).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
});
let tokenToUse = null;
const playerIds = Object.keys(game.players);
for (const pid of playerIds) {
if (game.players[pid] && game.players[pid].token) {
tokenToUse = game.players[pid].token;
break;
}
}
if (tokenToUse) {
saveGameResult(gameId, result, tokenToUse);
console.log(`[DB] Jogo salvo usando o token de um dos jogadores.`);
} else {
console.error(
`[DB Error] CRÍTICO: Nenhum jogador tem token. O jogo ${gameId} não foi salvo.`
);
}
}
if (result.action === "next_turn" || result.action === "trick_resolved") {
game.startTurnTimer((timeoutUserId, timeoutCardId) => {
handleGameMove(io, gameId, timeoutUserId, timeoutCardId);
});
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id])
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
}
};
export default (io, socket) => { export default (io, socket) => {
socket.on("join-game", async ({ gameId }) => { socket.on("join-game", async ({ gameId }) => {
const user = getUser(socket.id); const user = getUser(socket.id);
@@ -47,6 +119,39 @@ export default (io, socket) => {
const gameData = response.data.data || response.data; const gameData = response.data.data || response.data;
console.log(
`[Join Debug] API Data recebida para Jogo ${gameId}:`,
gameData ? "OK" : "NULL"
);
if (
gameData.player2_user_id == 1 &&
user.id != gameData.player1_user_id
) {
try {
console.log(
`[API Sync] A oficializar User ${user.id} como Player 2 na BD...`
);
await axios.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
);
console.log(`[API Sync] Sucesso! O jogo passou a 'Playing' na BD.`);
gameData.player2_user_id = user.id;
gameData.player2 = { name: user.name };
gameData.status = "Playing";
} catch (joinError) {
console.error(
`[API Sync Error] Falha ao fazer join na BD:`,
joinError.message
);
}
}
if (gameData.status === "Ended") { if (gameData.status === "Ended") {
socket.emit("error", { message: "Game already finished." }); socket.emit("error", { message: "Game already finished." });
return; return;
@@ -71,7 +176,18 @@ export default (io, socket) => {
{ id: gameData.player1_user_id, name: p1Name }, { id: gameData.player1_user_id, name: p1Name },
{ id: gameData.player2_user_id, name: p2Name } { id: gameData.player2_user_id, name: p2Name }
); );
console.log(
`[Join Debug] Jogo criado?`,
game ? "SIM" : "NÃO (Undefined)"
);
} catch (error) { } catch (error) {
if (error.response) {
console.error(`[Join Error] Status: ${error.response.status}`);
console.error(`[Join Error] Data:`, error.response.data);
} else {
console.error(`[Join Error] Message:`, error.message);
}
socket.emit("error", { message: "Failed to join game." }); socket.emit("error", { message: "Failed to join game." });
return; return;
} }
@@ -80,8 +196,13 @@ export default (io, socket) => {
const GHOST_ID = 1; const GHOST_ID = 1;
if (game && game.players) { if (game && game.players) {
if (!game.players[user.id]) { if (game.players[user.id]) {
if (game.players[GHOST_ID]) { game.players[user.id].token = socket.handshake.auth.token;
}
if (!game.players[user.id] && game.players[GHOST_ID]) {
console.log(`[Ghost Swap] User ${user.name} substituiu o Fantasma.`);
delete game.players[GHOST_ID]; delete game.players[GHOST_ID];
game.players[user.id] = { game.players[user.id] = {
id: user.id, id: user.id,
@@ -89,8 +210,23 @@ export default (io, socket) => {
hand: [], hand: [],
points: 0, points: 0,
tricks: 0, tricks: 0,
token: socket.handshake.auth.token,
}; };
const token = socket.handshake.auth.token;
axios
.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
} }
)
.then(() =>
console.log(`[API Sync] Sucesso! BD atualizada para 'Playing'.`)
)
.catch((err) => console.error(`[API Sync Error]`, err.message));
} }
} }
@@ -99,6 +235,11 @@ export default (io, socket) => {
if (game && game.players[user.id]) { if (game && game.players[user.id]) {
socket.emit("game-state", game.getStateForPlayer(user.id)); socket.emit("game-state", game.getStateForPlayer(user.id));
console.log(`--> Estado enviado para User ${user.id}`); console.log(`--> Estado enviado para User ${user.id}`);
game.players[user.id].token = socket.handshake.auth.token;
if (!game.timer && game.status === "playing") {
game.startTurnTimer((uId, cId) => handleGameMove(io, gameId, uId, cId));
}
socket.emit("game-state", game.getStateForPlayer(user.id));
} else { } else {
socket.emit("error", { message: "Error joining game state." }); socket.emit("error", { message: "Error joining game state." });
} }
@@ -117,6 +258,8 @@ export default (io, socket) => {
return; return;
} }
handleGameMove(io, gameId, user.id, cardId);
const roomName = `game_${gameId}`; const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName); const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) { if (socketsInRoom) {
+1
View File
@@ -2,6 +2,7 @@
"name": "websockets", "name": "websockets",
"version": "1.0.0", "version": "1.0.0",
"main": "index.js", "main": "index.js",
"type": "module",
"scripts": { "scripts": {
"dev": "nodemon index.js", "dev": "nodemon index.js",
"start": "bun index.js " "start": "bun index.js "
+12 -5
View File
@@ -18,15 +18,22 @@ export const serverStart = (port) => {
}); });
server.io.use(async (socket, next) => { server.io.use(async (socket, next) => {
const token = socket.handshake.auth.token; let token = socket.handshake.auth.token;
if (!token) { if (!token) {
return next(new Error("Authentication error: No token provided")); return next(new Error("Authentication error: No token provided"));
} }
if (!token.startsWith("Bearer ")) {
token = "Bearer " + token;
}
try { try {
const response = await axios.get(`${API_URL}/users/me`, { const response = await axios.get(`${API_URL}/users/me`, {
headers: { Authorization: token }, headers: {
Authorization: token,
Accept: "application/json"
},
}); });
const user = response.data.data || response.data; const user = response.data.data || response.data;
@@ -35,6 +42,9 @@ export const serverStart = (port) => {
return next(new Error("Authentication error: User data not found")); return next(new Error("Authentication error: User data not found"));
} }
socket.user = user;
socket.handshake.auth.token = token;
addUser(socket.id, user); addUser(socket.id, user);
next(); next();
@@ -53,15 +63,12 @@ export const serverStart = (port) => {
}); });
server.io.on("connection", (socket) => { server.io.on("connection", (socket) => {
console.log("New connection:", socket.id);
gameEvents(server.io, socket); gameEvents(server.io, socket);
handleConnectionEvents(server.io, socket); handleConnectionEvents(server.io, socket);
socket.on("disconnect", () => { socket.on("disconnect", () => {
removeUser(socket.id); removeUser(socket.id);
console.log("Disconnected:", socket.id);
}); });
}); });
}; };
+6 -6
View File
@@ -1,4 +1,4 @@
const BiscaGame = require("../classes/BiscaGame"); import BiscaGame from '../classes/BiscaGame.js';
const activeGames = new Map(); const activeGames = new Map();
@@ -18,12 +18,12 @@ const getGame = (id) => {
}; };
const removeGame = (id) => { const removeGame = (id) => {
const game = activeGames.get(id);
if (game) {
game.stopTimer();
activeGames.delete(id); activeGames.delete(id);
console.log(`[Game State] Game removed: ${id}`); console.log(`[Game State] Game removed: ${id}`);
}
}; };
module.exports = { export { createGame, getGame, removeGame };
createGame,
getGame,
removeGame,
};