Version 1.0 #102

Merged
FernandoJVideira merged 163 commits from develop into master 2026-01-03 14:49:00 +00:00
23 changed files with 1786 additions and 317 deletions
Showing only changes of commit 25d21f7cf8 - Show all commits
+28 -39
View File
@@ -13,19 +13,16 @@ class GameController extends Controller
public function index(Request $request) public function index(Request $request)
{ {
$this->authorize('viewAny', Game::class); $this->authorize('viewAny', Game::class);
$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);
@@ -55,7 +52,7 @@ class GameController extends Controller
public function store(Request $request) public function store(Request $request)
{ {
$this->authorize('create', Game::class); $this->authorize('create', Game::class);
$validated = $request->validate([ $validated = $request->validate([
"type" => "required|in:3,9", "type" => "required|in:3,9",
]); ]);
@@ -77,7 +74,7 @@ class GameController extends Controller
"type" => $validated["type"], "type" => $validated["type"],
"status" => "Pending", "status" => "Pending",
"player1_user_id" => $user->id, "player1_user_id" => $user->id,
"player2_user_id" => self::GHOST_ID, "player2_user_id" => self::GHOST_ID,
"winner_user_id" => self::GHOST_ID, "winner_user_id" => self::GHOST_ID,
"loser_user_id" => self::GHOST_ID, "loser_user_id" => self::GHOST_ID,
"began_at" => now(), "began_at" => now(),
@@ -92,38 +89,30 @@ class GameController extends Controller
], 201); ], 201);
} }
public function join(Game $game) public function join(Request $request, Game $game)
{ {
$this->authorize('join', $game); // Prevent joining if already full or started
if ($game->status !== 'Pending' || $game->player2_user_id !== 1) {
$user = Auth::user(); return response()->json(['message' => 'Game is not available'], 400);
if ($game->player1_user_id == $user->id) {
return response()->json([
"message" => "You are the host. Waiting for opponent...",
"game" => $game
], 200);
}
if ($game->player2_user_id !== self::GHOST_ID) {
return response()->json(["message" => "Game is full"], 400);
}
$game->update([
"status" => "Playing",
"player2_user_id" => $user->id,
]);
return response()->json([
"message" => "Joined successfully!",
"game" => $game,
], 200);
} }
// Prevent joining your own game
if ($game->player1_user_id === $request->user()->id) {
return response()->json(['message' => 'Cannot join your own game'], 400);
}
$game->update([
'player2_user_id' => $request->user()->id,
'status' => 'Playing',
]);
return response()->json($game);
}
public function show(Game $game) public function show(Game $game)
{ {
$this->authorize('view', $game); $this->authorize('view', $game);
$game->load(["player1", "player2", "winner"]); $game->load(["player1", "player2", "winner"]);
return response()->json($game); return response()->json($game);
} }
@@ -131,7 +120,7 @@ class GameController extends Controller
public function update(Request $request, Game $game) public function update(Request $request, Game $game)
{ {
$this->authorize('update', $game); $this->authorize('update', $game);
if ($game->status == "Ended") { if ($game->status == "Ended") {
return response()->json(["message" => "Game already ended"], 400); return response()->json(["message" => "Game already ended"], 400);
} }
@@ -158,13 +147,13 @@ class GameController extends Controller
public function resign(Game $game) public function resign(Game $game)
{ {
$this->authorize('resign', $game); $this->authorize('resign', $game);
$user = Auth::user(); $user = Auth::user();
$game->update([ $game->update([
'status' => 'Ended', 'status' => 'Ended',
'winner_user_id' => $game->player1_user_id === $user->id 'winner_user_id' => $game->player1_user_id === $user->id
? $game->player2_user_id ? $game->player2_user_id
: $game->player1_user_id, : $game->player1_user_id,
'loser_user_id' => $user->id, 'loser_user_id' => $user->id,
'ended_at' => now(), 'ended_at' => now(),
@@ -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);
}
}
+4 -2
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',
+11
View File
@@ -29,11 +29,22 @@ class Game extends Model
'match_id' 'match_id'
]; ];
protected $casts = [
'began_at' => 'datetime',
'ended_at' => 'datetime',
'is_draw' => 'boolean',
];
public function winner() public function winner()
{ {
return $this->belongsTo(User::class, "winner_user_id"); return $this->belongsTo(User::class, "winner_user_id");
} }
public function loser()
{
return $this->belongsTo(User::class, "loser_user_id");
}
public function player1() public function player1()
{ {
return $this->belongsTo(User::class, 'player1_user_id'); return $this->belongsTo(User::class, 'player1_user_id');
@@ -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;
}
}
+41 -13
View File
@@ -7,6 +7,7 @@ use App\Http\Controllers\ProfileController;
use App\Http\Controllers\StatisticsController; use App\Http\Controllers\StatisticsController;
use App\Http\Controllers\UserController; use App\Http\Controllers\UserController;
use App\Http\Controllers\CoinPurchaseController; 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 () {
@@ -46,24 +47,50 @@ Route::prefix('v1')->group(function () {
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']); Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
}); });
// Game Resources
Route::prefix('games')->group(function () { Route::prefix('games')->group(function () {
Route::apiResource('/', GameController::class)->parameters([ //Host a new multiplayer game - MUST come before resource routes
'' => 'game', Route::post('host', function (\Illuminate\Http\Request $request) {
]); $request->validate([
Route::post('/{game}/join', [GameController::class, 'join']); 'type' => 'required|in:3,9'
]);
$game = \App\Models\Game::create([
'type' => $request->type,
'status' => 'Pending',
'player1_user_id' => $request->user()->id,
'player2_user_id' => 1, // Ghost player
'began_at' => now(),
]);
return response()->json($game);
});
// List open games (available to join)
Route::get('open', function (\Illuminate\Http\Request $request) {
$type = $request->query('type', '9');
$games = \App\Models\Game::where('status', 'Pending')
->where('player2_user_id', 1) // Only games waiting for a second player
->where('type', $type)
->with('player1') // Load player1 relationship
->orderBy('began_at', 'asc')
->paginate(10);
return response()->json($games);
});
Route::get('/', [GameController::class, 'index']);
Route::get('/{game}', [GameController::class, 'show']);
Route::post('/', [GameController::class, 'store']);
Route::put('/{game}', [GameController::class, 'update']);
Route::delete('/{game}', [GameController::class, 'destroy']);
Route::post('/{game}/resign', [GameController::class, 'resign']); Route::post('/{game}/resign', [GameController::class, 'resign']);
Route::post('/{game}/join', [GameController::class, 'join']);
}); });
// Match Resources
Route::prefix('matches')->group(function () { Route::prefix('matches')->group(function () {
Route::apiResource('/', MatchController::class)->parameters([ Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
'' => 'match', Route::post('/{match}/join', [MatchController::class, 'join']);
]);
Route::post('/{match}/join', [
MatchController::class,
'join',
]);
}); });
// Admin Routes // Admin Routes
@@ -71,6 +98,7 @@ Route::prefix('v1')->group(function () {
->prefix('admin') ->prefix('admin')
->group(function () { ->group(function () {
Route::get('/statistics', [StatisticsController::class, 'getAdminStats']); 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']);
+20 -3
View File
@@ -5,7 +5,7 @@ Content-Type: application/json
Accept: application/json Accept: application/json
{ {
"email": "p[email protected]", "email": "a1@mail.pt",
"password": "123" "password": "123"
} }
@@ -14,7 +14,7 @@ Accept: application/json
@id = {{login.response.body.user.id}} @id = {{login.response.body.user.id}}
### Get All matches ### Get All matches
GET http://localhost:8000/api/v1/matches GET http://localhost:8000/api/v1/games
Content-Type: application/json Content-Type: application/json
Accept: application/json Accept: application/json
Authorization: Bearer {{token}} Authorization: Bearer {{token}}
@@ -55,7 +55,7 @@ Authorization: Bearer {{token}}
"payment_reference": "912345678" "payment_reference": "912345678"
} }
### Get public stats ### Get leaderboard
GET http://localhost:8000/api/v1/leaderboard GET http://localhost:8000/api/v1/leaderboard
Content-Type: application/json Content-Type: application/json
Accept: application/json Accept: application/json
@@ -64,4 +64,21 @@ Accept: application/json
GET http://localhost:8000/api/v1/statistics/me GET http://localhost:8000/api/v1/statistics/me
Content-Type: application/json Content-Type: application/json
Accept: 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
Accept: application/json
Authorization: Bearer {{token}} Authorization: Bearer {{token}}
+4 -5
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(), {
@@ -44,7 +42,8 @@ const logout = () => {
onMounted(async () => { onMounted(async () => {
await authStore.restoreSession() await authStore.restoreSession()
socketStore.handleConnection() // REMOVED - The WebSocket for multiplayer is handled separately in the WebSocketStore
// socketStore.handleConnection()
}) })
</script> </script>
+7 -1
View File
@@ -7,6 +7,8 @@
:player-score="playerScore" :player-score="playerScore"
:opponent-score="opponentScore" :opponent-score="opponentScore"
:current-turn="currentTurn" :current-turn="currentTurn"
:player-name="playerName"
:opponent-name="opponentName"
:round-number="1" :round-number="1"
/> />
</div> </div>
@@ -62,16 +64,20 @@ const props = defineProps({
// REMOVIDO: playableCardIndices (já não precisamos dele) // REMOVIDO: playableCardIndices (já não precisamos dele)
playerScore: { type: Number, default: 0 }, playerScore: { type: Number, default: 0 },
opponentScore: { type: Number, default: 0 }, opponentScore: { type: Number, default: 0 },
playerName: { type: String, default: 'You' },
opponentName: { type: String, default: 'Bot' },
currentTurn: { currentTurn: {
type: String, type: String,
default: 'player', default: 'player',
validator: (value) => ['player', 'opponent'].includes(value), validator: (value) => ['player', 'opponent'].includes(value),
}, },
isMyTurn: { type: Boolean, default: false },
}) })
const emit = defineEmits(['play-card']) const emit = defineEmits(['play-card'])
const handleCardClick = (payload) => { const handleCardClick = (payload) => {
if (!props.isMyTurn) return
emit('play-card', payload.card) emit('play-card', payload.card)
} }
</script> </script>
+6 -2
View File
@@ -51,6 +51,10 @@ const props = defineProps({
default: 3, default: 3,
validator: (value) => [3, 9].includes(value), validator: (value) => [3, 9].includes(value),
}, },
isDisabled: {
type: Boolean,
default: false,
},
}) })
const emit = defineEmits(['card-clicked']) const emit = defineEmits(['card-clicked'])
@@ -81,7 +85,7 @@ const overlapPercentage = computed(() => {
return props.maxCards === 3 ? 0.7 : 0.85 return props.maxCards === 3 ? 0.7 : 0.85
}) })
const cardWidth = 128 const cardWidth = 128
const getCardStyle = (index) => { const getCardStyle = (index) => {
const totalCards = props.cards.length const totalCards = props.cards.length
const overlapOffset = cardWidth * (1 - overlapPercentage.value) const overlapOffset = cardWidth * (1 - overlapPercentage.value)
@@ -105,4 +109,4 @@ const getCardStyle = (index) => {
zIndex: hoveredIndex.value === index ? 50 : index + 1, zIndex: hoveredIndex.value === index ? 50 : index + 1,
} }
} }
</script> </script>
@@ -33,7 +33,8 @@
turnChanged && 'animate-pulse', turnChanged && 'animate-pulse',
]" ]"
> >
{{ currentTurn === 'player' ? 'Your Turn' : "Bot's Turn" }} <!-- You can replace the above line with the following if you want to show names instead -->
{{ currentTurn === 'player' ? playerName + "'s Turn" : opponentName + "'s Turn" }}
</div> </div>
<span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium"> <span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium">
Round {{ roundNumber }} Round {{ roundNumber }}
+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>
@@ -0,0 +1,323 @@
<template>
<div class="relative min-h-screen overflow-hidden bg-green-900">
<div v-if="shouldShowBoard && !gameOver" class="absolute top-4 right-4 z-50">
<button
@click="handleSurrender"
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
>
<span>🏳</span> Surrender
</button>
</div>
<div v-if="!wsStore.connected && hasConnectedOnce" class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
<div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
<span class="text-white text-sm">Reconnecting...</span>
</div>
<div v-if="shouldShowBoard && !gameOver && isMyTurn" class="absolute top-4 left-1/2 -translate-x-1/2 z-50">
<div class="bg-gray-800 px-6 py-3 rounded-lg border-2 shadow-xl transition-colors duration-300"
:class="timeLeft <= 5 ? 'border-red-500 bg-red-900/20' : 'border-gray-700'">
<div class="flex items-center gap-3">
<svg class="w-6 h-6" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="2"/>
<polyline points="12 6 12 12 16 14" stroke-width="2"/>
</svg>
<span :class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">
{{ timeLeft }}
</span>
</div>
</div>
</div>
<div v-if="shouldShowBoard">
<GameBoard
:trump-card="trumpCard"
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
:player-hand="visibleHand"
:opponent-hand="opponentHand"
:player-score="playerScore"
:opponent-score="opponentScore"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
:current-turn="currentTurnLabel"
:current-trick="displayedTrick"
:is-my-turn="isMyTurn"
@play-card="handlePlayCard"
/>
</div>
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
<div class="text-center p-8 bg-green-800/50 rounded-2xl border border-green-700 shadow-2xl backdrop-blur-sm">
<div class="relative mx-auto mb-6 h-16 w-16">
<div class="absolute inset-0 rounded-full border-4 border-green-600"></div>
<div class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
</div>
<h2 class="text-2xl font-bold mb-2">
Waiting for Opponent...
</h2>
<p class="text-green-100 mb-8 max-w-sm">
Share the game code or wait for a player to join your lobby.
</p>
<button
@click="handleCloseModal"
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20"
>
Cancel & Return Home
</button>
</div>
</div>
<GameOver
:is-visible="gameOver"
:winner="winnerResult"
:player-score="playerScore"
:opponent-score="opponentScore"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
:stats="{ playerTricks: 0, opponentTricks: 0 }"
:is-logging-out="false"
@play-again="handleCloseModal"
@close="handleCloseModal"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSocketStore } from '@/stores/socket'
import { useAuthStore } from '@/stores/auth'
import { toast } from 'vue-sonner'
import axios from 'axios'
import GameBoard from '@/components/game/GameBoard.vue'
import GameOver from '@/components/game/GameOver.vue'
const route = useRoute()
const router = useRouter()
const wsStore = useSocketStore()
const authStore = useAuthStore()
const API_BASE_URL = inject('apiBaseURL')
const gameId = ref(route.params.id)
const visibleHand = ref([])
const gameOver = ref(false)
const isDealing = ref(false)
const hasInitialDealHappened = ref(false)
const winnerResult = ref('draw')
const timeLeft = ref(20)
const timerInterval = ref(null)
const hasConnectedOnce = ref(false)
const gameMetadata = ref({
p1_id: null,
p1_name: 'Player 1',
p2_id: null,
p2_name: 'Opponent'
})
const displayedTrick = ref({ playerCard: null, opponentCard: null })
const trickClearTimer = ref(null)
// --- COMPUTED ---
const myUserId = computed(() => authStore.currentUser?.id)
const shouldShowBoard = computed(() => {
const s = wsStore.gameState;
if (s && s.player2 && s.player2.id > 1) {
return true;
}
return false;
})
const amIHost = computed(() => {
if (gameMetadata.value.p1_id) {
return String(gameMetadata.value.p1_id) === String(myUserId.value)
}
const p1Id = wsStore.gameState?.player1_user_id || wsStore.gameState?.player1?.id
return String(p1Id) === String(myUserId.value)
})
const myDisplayName = computed(() => amIHost.value ? gameMetadata.value.p1_name : gameMetadata.value.p2_name)
const opponentDisplayName = computed(() => amIHost.value ? gameMetadata.value.p2_name : gameMetadata.value.p1_name)
const mappedTrick = computed(() => {
const table = wsStore.gameState?.table
if (!table) return { playerCard: null, opponentCard: null }
if (amIHost.value) {
return { playerCard: table.playerCard, opponentCard: table.opponentCard }
} else {
return { playerCard: table.opponentCard, opponentCard: table.playerCard }
}
})
const currentTurnLabel = computed(() => {
const turnId = wsStore.gameState?.currentTurn
if (!turnId) return 'player'
return String(turnId) === String(myUserId.value) ? 'player' : 'opponent'
})
const trumpCard = computed(() => wsStore.gameState?.trumpCard || null)
const deckCount = computed(() => wsStore.gameState?.deckCount || 0)
const playerScore = computed(() => wsStore.gameState?.points || 0)
const opponentScore = computed(() => wsStore.gameState?.opponent?.points || 0)
const serverHand = computed(() => wsStore.gameState?.hand || [])
const isMyTurn = computed(() => String(wsStore.gameState?.currentTurn) === String(myUserId.value))
const opponentHand = computed(() => {
const count = wsStore.gameState?.opponent?.cardCount || 0
return Array.from({ length: count }, (_, i) => ({ id: `opp-${i}`, suit: 'back', rank: 0 }))
})
// --- WATCHERS ---
watch(() => wsStore.connected, (isConnected) => {
if (isConnected) {
hasConnectedOnce.value = true
wsStore.joinGame(gameId.value)
}
}, { immediate: true })
watch(() => wsStore.gameState, async (newState, oldState) => {
const oldP2 = oldState?.player2?.id;
const newP2 = newState?.player2?.id;
if (newP2 && newP2 > 1 && newP2 !== oldP2) {
await fetchGameMetadata();
}
}, { deep: true })
watch(mappedTrick, (newVal) => {
if (newVal.playerCard || newVal.opponentCard) {
if (trickClearTimer.value) clearTimeout(trickClearTimer.value)
displayedTrick.value = { ...newVal }
} else {
const currentlyShowing = displayedTrick.value.playerCard || displayedTrick.value.opponentCard
if (currentlyShowing) {
trickClearTimer.value = setTimeout(() => {
displayedTrick.value = { playerCard: null, opponentCard: null }
}, 1500)
} else {
displayedTrick.value = { playerCard: null, opponentCard: null }
}
}
}, { deep: true })
// --- FIX: TIMER GHOSTING ---
const startTimer = () => {
if (timerInterval.value) clearInterval(timerInterval.value)
if (!shouldShowBoard.value && wsStore.gameState?.status !== 'playing') {
timeLeft.value = 20;
return;
}
// FORCE RESET to avoid showing old time for 1 frame
timeLeft.value = 20;
const startAt = wsStore.gameState?.turnStartedAt ? new Date(wsStore.gameState.turnStartedAt).getTime() : Date.now()
// Define update function
const update = () => {
const now = Date.now()
const elapsed = Math.floor((now - startAt) / 1000)
timeLeft.value = Math.max(0, 20 - elapsed)
if (timeLeft.value <= 0) clearInterval(timerInterval.value)
}
// EXECUTE IMMEDIATELY
update();
// Then set interval
timerInterval.value = setInterval(update, 1000)
}
watch(() => wsStore.gameState?.currentTurn, (newTurn) => {
if (newTurn) startTimer()
}, { immediate: true })
const animateDeal = async (cards) => {
if (isDealing.value) return
isDealing.value = true
visibleHand.value = []
for (const card of cards) {
visibleHand.value.push(card)
await new Promise(r => setTimeout(r, 150))
}
isDealing.value = false
}
watch(serverHand, (newHand) => {
if (visibleHand.value.length === 0 && newHand.length > 0 && !hasInitialDealHappened.value) {
animateDeal(newHand)
hasInitialDealHappened.value = true
} else if (!isDealing.value) {
visibleHand.value = [...newHand]
}
}, { deep: true })
// --- METHODS ---
const fetchGameMetadata = async () => {
try {
const response = await axios.get(`${API_BASE_URL}/games/${gameId.value}`)
const game = response.data.data || response.data
gameMetadata.value = {
p1_id: game.player1_user_id,
p1_name: game.player1?.nickname || 'Host',
p2_id: game.player2_user_id,
p2_name: game.player2?.nickname || 'Opponent'
}
} catch (e) {
console.error("Failed to load metadata", e)
}
}
const handlePlayCard = (card) => {
if (!isMyTurn.value || gameOver.value) return
visibleHand.value = visibleHand.value.filter(c => c.id !== card.id)
wsStore.playCard(gameId.value, card.id)
}
// --- FIX: SURRENDER LOGIC ---
const handleSurrender = () => {
if(confirm('Are you sure you want to surrender? You will lose.')) {
// Send event to server. Do NOT disconnect locally yet.
// Wait for the server to send "Game Over" event back.
wsStore.surrender(gameId.value)
}
}
const handleCloseModal = () => {
wsStore.disconnect()
router.push({ name: 'home' })
}
// --- LIFECYCLE ---
onMounted(async () => {
await fetchGameMetadata()
wsStore.connect()
wsStore.onTrickEnd((result) => {
const winnerName = result.winnerId == authStore.currentUser?.id ? "You" : "Opponent"
toast.success(`${winnerName} won the trick!`, { position: 'top-center', duration: 1500 })
})
wsStore.onGameOver((result) => {
gameOver.value = true
if (result.isDraw) winnerResult.value = 'draw'
else winnerResult.value = result.winnerId == authStore.currentUser?.id ? 'player' : 'opponent'
})
})
onUnmounted(() => {
if (timerInterval.value) clearInterval(timerInterval.value)
wsStore.disconnect()
})
</script>
+92 -8
View File
@@ -12,6 +12,7 @@ import {
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' import { useAuthStore } from '@/stores/auth'
import axios from 'axios'
const API_BASE_URL = inject('apiBaseURL') const API_BASE_URL = inject('apiBaseURL')
const apiStore = useAPIStore() const apiStore = useAPIStore()
@@ -36,6 +37,7 @@ const lbPage = ref(1)
const lbObserverTarget = ref(null) const lbObserverTarget = ref(null)
const lbObserver = ref(null) const lbObserver = ref(null)
const lbMorePages = ref(true) const lbMorePages = ref(true)
const publicStats = ref(null)
const setupGamesObserver = () => { const setupGamesObserver = () => {
if (gObserver.value) gObserver.value.disconnect(); if (gObserver.value) gObserver.value.disconnect();
@@ -55,19 +57,33 @@ const getPendingGames = async (mode = selectedMode.value) => {
if (gLoading.value) return; if (gLoading.value) return;
gLoading.value = true; gLoading.value = true;
apiStore.gameQueryParameters.page = gPage.value++;
apiStore.gameQueryParameters.filters.sort_direction = "asc"
apiStore.gameQueryParameters.filters.type = mode
apiStore.gameQueryParameters.filters.status = 'Pending'
try { try {
const response = await apiStore.getGames(); const response = await axios.get(`${API_BASE_URL}/games/open`, {
params: {
type: mode,
page: gPage.value
}
});
const newGames = response.data.data; const newGames = response.data.data;
openGames.value = [...openGames.value, ...newGames]; openGames.value = [...openGames.value, ...newGames];
gPage.value++;
} catch (error) {
console.error('Failed to fetch games:', error);
} finally { } finally {
gLoading.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 () => { const openStats = async () => {
showStatsModal.value = true showStatsModal.value = true
statsLoading.value = true statsLoading.value = true
@@ -155,10 +171,57 @@ const toggleReady = () => {
} }
onMounted(async () => { onMounted(async () => {
await fetchPublicStats();
await getPendingGames(); await getPendingGames();
await nextTick(); await nextTick();
setupGamesObserver(); setupGamesObserver();
}) })
const hostGame = async () => {
showHostModal.value = true
try {
const response = await axios.post(`${API_BASE_URL}/games/host`, {
type: selectedMode.value
})
const gameId = response.data.id
console.log('Game hosted:', gameId)
router.push({
name: 'multiplayer-game',
params: { id: gameId },
query: { type: selectedMode.value }
})
} catch (error) {
console.error('Failed to host game:', error)
console.error('Error details:', error.response?.data)
showHostModal.value = false
alert('Failed to host game: ' + (error.response?.data?.message || error.message))
}
}
const joinGame = async (game) => {
selectedGame.value = game
try {
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
console.log('Joined game:', game.id)
router.push({
name: 'multiplayer-game',
params: { id: game.id },
query: { type: selectedMode.value }
})
} catch (error) {
console.error('Failed to join game:', error)
console.error('Error details:', error.response?.data)
alert('Failed to join game: ' + (error.response?.data?.message || error.message))
}
}
</script> </script>
<template> <template>
@@ -166,6 +229,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">
@@ -212,7 +296,7 @@ onMounted(async () => {
<Card class="w-full max-w-2xl"> <Card class="w-full max-w-2xl">
<CardHeader> <CardHeader>
<CardTitle class="text-3xl font-bold text-center"> <CardTitle class="text-3xl font-bold text-center">
MultiPlayer Multi Player
</CardTitle> </CardTitle>
<CardDescription class="text-center"> <CardDescription class="text-center">
Go one on one with another player! Go one on one with another player!
@@ -226,7 +310,7 @@ onMounted(async () => {
</div> </div>
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1"> <div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
<div v-for="(game, index) in openGames" :key="game.id" @click="JoinGameModal(game)" <div v-for="(game, index) in openGames" :key="game.id" @click="joinGame(game)"
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500"> class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
@@ -249,7 +333,7 @@ onMounted(async () => {
</div> </div>
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<Button @click="hostGameModal()" size="lg" variant="secondary" <Button @click="hostGame()" size="lg" variant="secondary"
class="hover:bg-purple-500 hover:text-slate-200"> class="hover:bg-purple-500 hover:text-slate-200">
Host Game Host Game
</Button> </Button>
+7 -8
View File
@@ -77,12 +77,12 @@
@click="activeTab = 'edit'"> @click="activeTab = 'edit'">
Edit Profile Edit Profile
</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 === 'transaction-history' }]" :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'"> @click="activeTab = 'transaction-history'">
Transaction History Transaction History
</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 === 'game-history' }]" :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'"> @click="activeTab = 'game-history'">
Game History Game History
@@ -92,7 +92,7 @@
@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
@@ -228,7 +228,7 @@
</div> </div>
<!-- Transaction History Tab --> <!-- Transaction History Tab -->
<div v-if="activeTab === 'transaction-history'" class="p-8"> <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-wrap gap-4 mb-6 items-end">
<div class="flex flex-col gap-1"> <div class="flex flex-col gap-1">
@@ -280,8 +280,7 @@
{{ transaction.category }} </div> {{ transaction.category }} </div>
<div class="text-xs text-muted-foreground"> <div class="text-xs text-muted-foreground">
{{ new Date(transaction.began_at).toLocaleDateString() }} {{ new Date(transaction.began_at).toLocaleDateString() }}
{{ new Date(transaction.began_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) {{ new Date(transaction.began_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }}
}}
</div> </div>
</div> </div>
</div> </div>
@@ -305,7 +304,7 @@
</div> </div>
<!-- Game History Tab --> <!-- Game History Tab -->
<div v-if="activeTab === 'game-history'" class="p-8"> <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-wrap gap-4 mb-6 items-end">
<div class="flex flex-col gap-1"> <div class="flex flex-col gap-1">
<label class="text-xs font-medium text-muted-foreground">Variant</label> <label class="text-xs font-medium text-muted-foreground">Variant</label>
@@ -457,7 +456,7 @@
</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">
+22 -1
View File
@@ -9,8 +9,11 @@ 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 SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue' import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
import MultiplayerGamePage from '@/pages/game/MultiplayerGamePage.vue'
import RegisterPage from '@/pages/register/RegisterPage.vue' import RegisterPage from '@/pages/register/RegisterPage.vue'
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue' 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),
@@ -19,6 +22,7 @@ const router = createRouter({
path: '/', path: '/',
name: 'home', name: 'home',
component: HomePage, component: HomePage,
meta: { requiresAdmin: false }
}, },
{ {
path: '/login', path: '/login',
@@ -35,7 +39,7 @@ const router = createRouter({
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',
@@ -44,6 +48,12 @@ const router = createRouter({
props: { gameType: 9 }, props: { gameType: 9 },
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{
path: '/game/multiplayer/:id',
name: 'multiplayer-game',
component: MultiplayerGamePage,
meta: { requiresAuth: true }
},
{ {
path: '/user', path: '/user',
component: UserPage, component: UserPage,
@@ -54,6 +64,12 @@ const router = createRouter({
component: CoinsPurchasePage, component: CoinsPurchasePage,
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{
path: '/admin',
name: 'admin',
component: AdminPage,
meta: { requiresAuth: true, requiresAdmin: true },
},
{ {
path: '/testing', path: '/testing',
children: [ children: [
@@ -88,6 +104,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')
@@ -96,6 +113,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()
}) })
+62 -2
View File
@@ -95,8 +95,7 @@ export const useAPIStore = defineStore('api', () => {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
page: params.page || 1, page: params.page || 1,
...(params.type && { type: params.type }), ...(params.type && { type: params.type }),
...(params.date_from && { date_from: params.date_from }), ...(params.blocked && { blocked: params.blocked }),
...(params.date_to && { date_to: params.date_to }),
}).toString() }).toString()
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`) return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`)
@@ -114,6 +113,58 @@ export const useAPIStore = defineStore('api', () => {
return axios.get(`${API_BASE_URL}/statistics/me`) 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,
@@ -123,6 +174,15 @@ export const useAPIStore = defineStore('api', () => {
getCurrentUserTransactions, getCurrentUserTransactions,
getCurrentUserStats, getCurrentUserStats,
getLeaderboard, getLeaderboard,
getPublicStats,
getAdminStats,
getAdminUsers,
blockUser,
unblockUser,
deleteUser,
getAdminTransactions,
getAdminGames,
postAdmin,
gameQueryParameters, gameQueryParameters,
} }
}) })
+12 -1
View File
@@ -4,7 +4,7 @@ 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)
@@ -20,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);
@@ -112,10 +116,16 @@ 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,
getToken, getToken,
@@ -124,5 +134,6 @@ export const useAuthStore = defineStore('auth', () => {
resetTokenExpiry, resetTokenExpiry,
isTokenAlmostExpired, isTokenAlmostExpired,
restoreSession, restoreSession,
updateCurrentUserCoins,
} }
}) })
+121 -15
View File
@@ -1,24 +1,130 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { inject } from 'vue' import { ref } from 'vue'
import { io } from 'socket.io-client'
import { useAuthStore } from './auth'
export const useSocketStore = defineStore('socket', () => { export const useSocketStore = defineStore('websocket', () => {
const socket = inject('socket') const authStore = useAuthStore()
const handleConnection = () => { const socket = ref(null)
try { const connected = ref(false)
socket.on('connect', () => { const gameState = ref(null)
console.log(`[Socket] Connected -- ${socket.id}`) const lastError = ref(null)
}) const currentGameId = ref(null)
socket.on('disconnect', () => {
console.log(`[Socket] Disconnected -- ${socket.id}`) const WS_URL = 'http://localhost:3000'
})
} catch (error) { const connect = () => {
console.error('[Socket] Connection error:', error) if (socket.value?.connected) return
const token = authStore.getToken()
if (!token) {
console.error('No token available for WebSocket connection')
return
}
socket.value = io(WS_URL, {
auth: { token: `Bearer ${token}` },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
})
socket.value.on('connect', () => {
if (currentGameId.value) {
console.log("Reconnected to socket. Rejoining game...");
socket.emit("join-game", { gameId: currentGameId.value });
}
connected.value = true
console.log('[WebSocket] Connected:', socket.value.id)
})
socket.value.on('disconnect', (reason) => {
connected.value = false
console.log('[WebSocket] Disconnected:', reason)
})
socket.value.on('connect_error', (error) => {
console.error('[WebSocket] Connection error:', error.message)
lastError.value = error.message
})
socket.value.on('heartbeat', () => {
socket.value.emit('heartbeat_ack')
})
socket.value.on('game-state', (state) => {
gameState.value = state
})
socket.value.on('game-error', (data) => {
lastError.value = data.message
console.error('[Game] Error:', data.message)
})
socket.value.on('error', (data) => {
lastError.value = data.message
console.error('[Socket] Error:', data.message)
})
}
const disconnect = () => {
if (socket.value) {
socket.value.disconnect()
socket.value = null
connected.value = false
gameState.value = null
lastError.value = null
currentGameId.value = null
}
}
const joinGame = (gameId) => {
currentGameId.value = gameId
if (!socket.value?.connected) return
console.log('[Game] Joining game:', gameId)
socket.value.emit('join-game', { gameId })
}
const playCard = (gameId, cardId) => {
if (!socket.value?.connected) return
socket.value.emit('play-card', { gameId, cardId })
}
// --- NEW: Surrender Action ---
const surrender = (gameId) => {
if (!socket.value?.connected) return
console.log('[Game] Surrendering:', gameId)
socket.value.emit('surrender', { gameId })
}
const onTrickEnd = (callback) => {
if (socket.value) {
socket.value.off('trick-end')
socket.value.on('trick-end', callback)
}
}
const onGameOver = (callback) => {
if (socket.value) {
socket.value.off('game-over')
socket.value.on('game-over', callback)
} }
} }
return { return {
handleConnection, socket,
connected,
gameState,
lastError,
currentGameId,
connect,
disconnect,
joinGame,
playCard,
surrender, // Exported
onTrickEnd,
onGameOver
} }
}) })
+2
View File
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import axios from 'axios' import axios from 'axios'
import { inject, ref } from 'vue' import { inject, ref } from 'vue'
import { useAuthStore } from './auth'
export const useUserStore = defineStore('user', () => { export const useUserStore = defineStore('user', () => {
const API_BASE_URL = inject('apiBaseURL') const API_BASE_URL = inject('apiBaseURL')
@@ -10,6 +11,7 @@ export const useUserStore = defineStore('user', () => {
try { try {
const response = await axios.get(`${API_BASE_URL}/users/me/coins`) const response = await axios.get(`${API_BASE_URL}/users/me/coins`)
coins.value = response.data?.coins || 0 coins.value = response.data?.coins || 0
useAuthStore().updateCurrentUserCoins(coins.value)
return response return response
} catch (error) { } catch (error) {
console.error('Error fetching coins', error) console.error('Error fetching coins', error)
+2
View File
@@ -1,4 +1,6 @@
import { addUser, removeUser } from "../state/connection.js"; import { addUser, removeUser } from "../state/connection.js";
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
+194 -203
View File
@@ -4,6 +4,71 @@ import { getUser } from "../state/connection.js";
const API_URL = "http://localhost:8000/api/v1"; const API_URL = "http://localhost:8000/api/v1";
// --- HELPER: Card Strength for Auto-Play ---
const getStrength = (rank) => {
const strengthMap = { 1: 10, 7: 9, 13: 8, 11: 7, 12: 6, 6: 5, 5: 4, 4: 3, 3: 2, 2: 1 };
return strengthMap[rank] || 0;
};
// --- HELPER: Draw Card Logic ---
const drawCard = (game, playerId) => {
const player = game.players[playerId];
if (!player) return;
if (game.deck && game.deck.length > 0) {
const card = game.deck.pop();
player.hand.push(card);
} else if (game.trumpCard) {
player.hand.push(game.trumpCard);
game.trumpCard = null;
}
};
// --- HELPER: Sanitize Data ---
const sanitizeState = (state, game) => {
if (!state) return null;
const p1 = game.player1 || state.player1 || {};
const p2 = game.player2 || state.player2 || {};
return {
id: state.id,
status: state.status || game.status,
player1: { id: p1.id, name: p1.name },
player2: { id: p2.id, name: p2.name },
players: state.players,
hand: state.hand,
points: state.points,
opponent: {
id: state.opponent?.id,
name: state.opponent?.name,
points: state.opponent?.points,
cardCount: state.opponent?.cardCount
},
table: state.table,
trumpCard: state.trumpCard,
deckCount: game.deck ? game.deck.length : (state.deckCount || 0),
currentTurn: state.currentTurn,
turnStartedAt: state.turnStartedAt
};
};
const broadcastState = (io, gameId, game) => {
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]) {
const rawState = game.getStateForPlayer(u.id);
const cleanState = sanitizeState(rawState, game);
s.emit("game-state", cleanState);
}
}
}
}
async function saveGameResult(gameId, result, token) { async function saveGameResult(gameId, result, token) {
try { try {
const payload = { const payload = {
@@ -13,90 +78,105 @@ async function saveGameResult(gameId, result, token) {
player1_points: result.player1_points, player1_points: result.player1_points,
player2_points: result.player2_points, player2_points: result.player2_points,
}; };
if (!result.isDraw && result.winnerId) { if (!result.isDraw && result.winnerId) {
payload.winner_user_id = result.winnerId; payload.winner_user_id = result.winnerId;
payload.loser_user_id = result.loserId; payload.loser_user_id = result.loserId;
} }
await axios.put(`${API_URL}/games/${gameId}`, payload, { await axios.put(`${API_URL}/games/${gameId}`, payload, {
headers: { Authorization: token }, headers: { Authorization: token },
}); });
console.log(`[DB] Game ${gameId} saved.`);
} catch (error) { } catch (error) {
console.error(`[DB Error] Game ${gameId}:`, error.message); console.error(`[DB Error] Game ${gameId}:`, error.message);
} }
} }
// --- SHARED END GAME LOGIC ---
const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
const result = {
action: "game_ended",
winnerId: parseInt(winnerId),
loserId: parseInt(loserId),
isDraw: false,
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
reason: reason
};
game.status = "ended";
if (game.timer) clearInterval(game.timer);
io.to(`game_${gameId}`).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over"
});
const anyId = Object.keys(game.players)[0];
const token = game.players[anyId]?.token;
if (token) saveGameResult(gameId, result, token);
}
const handleTimeout = (io, gameId, userId) => {
const game = getGame(gameId);
if (!game || game.status === 'ended') return;
console.log(`[Timeout] User ${userId} auto-playing lowest card.`);
const player = game.players[userId];
if (!player || !player.hand || player.hand.length === 0) return;
const trumpSuit = game.trumpCard?.suit || '';
const sortedHand = [...player.hand].sort((a, b) => {
const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0);
const strengthB = getStrength(b.rank) + (b.suit === trumpSuit ? 100 : 0);
return strengthA - strengthB;
});
const cardToPlay = sortedHand[0];
if (cardToPlay) {
handleGameMove(io, gameId, userId, cardToPlay.id);
}
};
const handleGameMove = (io, gameId, userId, cardId) => { const handleGameMove = (io, gameId, userId, cardId) => {
const game = getGame(gameId); const game = getGame(gameId);
if (!game) return; if (!game) return;
const result = game.playCard(userId, cardId); const result = game.playCard(userId, cardId);
if (result.error) {
console.log(`[Game Error] ${result.error}`);
return;
}
const roomName = `game_${gameId}`; const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
broadcastState(io, gameId, game);
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") { if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult); io.to(roomName).emit("trick-end", result.trickResult);
setTimeout(() => {
if (game.status !== "ended") {
const canDraw = (game.deck && game.deck.length > 0) || game.trumpCard !== null;
if (canDraw) {
const winnerId = result.trickResult.winnerId;
const loserId = Object.keys(game.players).find(id => String(id) !== String(winnerId));
if (winnerId) drawCard(game, winnerId);
if (loserId) drawCard(game, loserId);
}
broadcastState(io, gameId, game);
}
}, 1500);
} }
if (result.action === "game_ended") { if (result.action === "game_ended") {
io.to(roomName).emit("game-over", { performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
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") { if (result.action === "next_turn" || result.action === "trick_resolved") {
game.startTurnTimer((timeoutUserId, timeoutCardId) => { game.startTurnTimer((timeoutUserId) => {
handleGameMove(io, gameId, timeoutUserId, timeoutCardId); handleTimeout(io, gameId, timeoutUserId);
}); });
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));
}
}
} }
}; };
@@ -109,181 +189,92 @@ export default (io, socket) => {
} }
let game = getGame(gameId); let game = getGame(gameId);
let gameData = null;
if (!game) { try {
try {
const token = socket.handshake.auth.token; const token = socket.handshake.auth.token;
const response = await axios.get(`${API_URL}/games/${gameId}`, { const response = await axios.get(`${API_URL}/games/${gameId}`, {
headers: { Authorization: token }, headers: { Authorization: token },
}); });
gameData = response.data.data || response.data;
} catch (e) { console.error("DB Sync Failed"); }
const gameData = response.data.data || response.data; if (!game && gameData) {
const p1Name = gameData.player1?.nickname || "Player 1";
console.log( const p2Name = gameData.player2?.nickname || "Player 2";
`[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") {
socket.emit("error", { message: "Game already finished." });
return;
}
if (
gameData.player1_user_id != user.id &&
gameData.player2_user_id != user.id &&
gameData.player2_user_id !== 1
) {
socket.emit("error", { message: "You are not in this game." });
return;
}
const p1Name = gameData.player1?.name || "Player 1";
const p2Name = gameData.player2?.name || "Player 2";
const type = gameData.type == "9" ? 9 : 3; const type = gameData.type == "9" ? 9 : 3;
game = createGame( game = createGame(
gameId, gameId,
type, type,
{ 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( game.status = gameData.status === 'Playing' ? 'playing' : 'pending';
`[Join Debug] Jogo criado?`,
game ? "SIM" : "NÃO (Undefined)"
);
} 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." });
return;
}
} }
const GHOST_ID = 1; if (!game) {
socket.emit("error", { message: "Game not found." });
return;
}
if (game && game.players) { const myId = user.id;
if (game.players[user.id]) { const ghostKey = Object.keys(game.players).find(key => key == 1);
game.players[user.id].token = socket.handshake.auth.token; const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
}
if (!game.players[user.id] && game.players[GHOST_ID]) { if (!game.players[myId] && (ghostKey || amIDbPlayer2)) {
console.log(`[Ghost Swap] User ${user.name} substituiu o Fantasma.`); let ghostHand = [];
let ghostPoints = 0;
let ghostTricks = 0;
if (ghostKey && game.players[ghostKey]) {
ghostHand = game.players[ghostKey].hand || [];
ghostPoints = game.players[ghostKey].points || 0;
ghostTricks = game.players[ghostKey].tricks || 0;
delete game.players[ghostKey];
}
delete game.players[GHOST_ID]; game.players[myId] = {
game.players[user.id] = { id: myId,
id: user.id, name: user.nickname,
name: user.name, hand: ghostHand,
hand: [], points: ghostPoints,
points: 0, tricks: ghostTricks,
tricks: 0, token: socket.handshake.auth.token,
token: socket.handshake.auth.token,
}; };
game.player2 = { id: myId, name: user.nickname };
const token = socket.handshake.auth.token; game.status = 'playing';
if(!game.timer) {
axios game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId));
.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));
}
} }
socket.join(`game_${gameId}`); socket.join(`game_${gameId}`);
if (game && game.players[user.id]) { if (game.players[myId]) {
socket.emit("game-state", game.getStateForPlayer(user.id)); game.players[myId].token = socket.handshake.auth.token;
console.log(`--> Estado enviado para User ${user.id}`);
game.players[user.id].token = socket.handshake.auth.token; const rawState = game.getStateForPlayer(myId);
if (!game.timer && game.status === "playing") { const cleanState = sanitizeState(rawState, game);
game.startTurnTimer((uId, cId) => handleGameMove(io, gameId, uId, cId));
} socket.emit("game-state", cleanState);
socket.emit("game-state", game.getStateForPlayer(user.id)); broadcastState(io, gameId, game);
} else {
socket.emit("error", { message: "Error joining game state." });
} }
}); });
socket.on("play-card", ({ gameId, cardId }) => { socket.on("play-card", ({ gameId, cardId }) => {
const user = getUser(socket.id); const user = getUser(socket.id);
const game = getGame(gameId); if (user) handleGameMove(io, gameId, user.id, cardId);
});
if (!game || !user) return; // --- NEW: SURRENDER HANDLER ---
socket.on("surrender", ({ gameId }) => {
const user = getUser(socket.id);
const game = getGame(gameId);
if (!game || !user || !game.players[user.id]) return;
const result = game.playCard(user.id, cardId); console.log(`[Game] User ${user.nickname} surrendered.`);
if (result.error) { const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id));
socket.emit("game-error", { message: result.error }); performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
return;
}
handleGameMove(io, gameId, user.id, cardId);
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,
});
saveGameResult(gameId, result, socket.handshake.auth.token);
}
}); });
}; };
+25 -13
View File
@@ -3,27 +3,39 @@ import BiscaGame from "../classes/BiscaGame.js";
const activeGames = new Map(); const activeGames = new Map();
const createGame = (id, type, player1, player2) => { const createGame = (id, type, player1, player2) => {
const game = new BiscaGame(id, type, player1, player2); const existingGame = activeGames.get(id);
if (existingGame) {
console.log(
`[Game State] Game ${id} already exists, returning existing instance`,
);
return existingGame;
}
const game = new BiscaGame(id, type, player1, player2);
game.init(); game.init();
activeGames.set(id, game); activeGames.set(id, game);
console.log(`[Game State] Game created: ${id} (Type: ${type})`); console.log(`[Game State] Game created: ${id} (Type: ${type})`);
return game; return game;
}; };
const getGame = (id) => { const getGame = (id) => {
return activeGames.get(id); return activeGames.get(id);
}; };
const removeGame = (id) => { const removeGame = (id) => {
const game = activeGames.get(id); const game = activeGames.get(id);
if (game) { if (game) {
game.stopTimer(); game.stopTimer();
activeGames.delete(id); activeGames.delete(id);
console.log(`[Game State] Game removed: ${id}`); console.log(`[Game State] Game removed: ${id}`);
} }
};
module.exports = {
createGame,
getGame,
removeGame,
}; };
export { createGame, getGame, removeGame };