Compare commits

..
Author SHA1 Message Date
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
21 changed files with 1062 additions and 258 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,
@@ -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
{ {
@@ -73,4 +74,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,
]
]);
}
} }
+111 -7
View File
@@ -127,6 +127,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 +183,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 +268,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',
]; ];
} }
} }
+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);
}
} }
+5 -1
View File
@@ -4,8 +4,8 @@ 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 Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function () { Route::prefix('v1')->group(function () {
@@ -23,6 +23,7 @@ Route::prefix('v1')->group(function () {
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 +31,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 +41,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 +68,7 @@ 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::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']);
+22 -3
View File
@@ -1,6 +1,6 @@
### 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
@@ -9,11 +9,30 @@ Accept: application/json
"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/matches
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 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 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"
}
}
+38 -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="coins > 0" href="/user?tab=transaction-history"
<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">
{{ 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,16 +56,20 @@ import {
NavigationMenuTrigger, NavigationMenuTrigger,
} from '@/components/ui/navigation-menu' } from '@/components/ui/navigation-menu'
import router from '@/router'; import router from '@/router';
import { ref, watch } from 'vue';
import { useUserStore } from '@/stores/user';
const emits = defineEmits(['logout']) const emits = defineEmits(['logout'])
const { userLoggedIn } = defineProps(['userLoggedIn']) const { userLoggedIn } = defineProps(['userLoggedIn'])
const coins = ref(0);
const biscaStore = useBiscaStore() 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 +81,25 @@ const logoutClickHandler = () => {
} }
emits('logout') emits('logout')
router.push('/login')
router.push({ name: 'home' })
} }
const fetchUserCoins = async () => {
if (userLoggedIn) {
try {
const response = await useUserStore().getCoins()
coins.value = response.data?.coins || 0
} catch (error) {
console.error('Error fetching user coins', error)
}
}
}
watch(() => userLoggedIn, async (isLoggedIn) => {
if (isLoggedIn) {
await fetchUserCoins()
} else {
coins.value = 0
}
}, { immediate: true })
</script> </script>
+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,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>
+486 -123
View File
@@ -9,7 +9,8 @@
</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" />
@@ -17,7 +18,8 @@
</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" />
@@ -27,37 +29,33 @@
</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"
stroke-width="1.5" />
<circle cx="12" cy="13" r="4" 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>
@@ -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
: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
: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
: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>
@@ -119,7 +123,8 @@
</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>
@@ -134,7 +139,8 @@
</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>
@@ -149,14 +155,16 @@
<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" />
@@ -164,7 +172,8 @@
</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>
@@ -177,7 +186,8 @@
</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,94 +199,258 @@
<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'" 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'" 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>
@@ -287,7 +461,8 @@
<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"
stroke="currentColor" stroke-width="2">
<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" /> <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="9" x2="12" y2="13" /> <line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" /> <line x1="12" y1="17" x2="12.01" y2="17" />
@@ -299,7 +474,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 +488,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 +513,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,7 +523,8 @@
<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"
stroke-width="2">
<circle cx="12" cy="12" r="10" /> <circle cx="12" cy="12" r="10" />
<line x1="15" y1="9" x2="9" y2="15" /> <line x1="15" y1="9" x2="9" y2="15" />
<line x1="9" y1="9" x2="15" y2="15" /> <line x1="9" y1="9" x2="15" y2="15" />
@@ -367,7 +534,8 @@
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 +547,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 +560,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 +571,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 +587,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 +595,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 +604,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 +948,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 +965,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()
+6 -15
View File
@@ -2,14 +2,14 @@ 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'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@@ -25,18 +25,9 @@ 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',
+28 -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,39 @@ 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.date_from && { date_from: params.date_from }),
...(params.date_to && { date_to: params.date_to }),
}).toString()
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`)
}
return { return {
postLogin, postLogin,
postLogout, postLogout,
getAuthUser, getAuthUser,
getGames, getGames,
getCurrentUserMatches,
getCurrentUserTransactions,
gameQueryParameters, gameQueryParameters,
} }
}) })
+8 -16
View File
@@ -7,8 +7,6 @@ export const useAuthStore = defineStore('auth', () => {
const DEFAULT_TIMEOUT = 5 * 60 * 1000 const DEFAULT_TIMEOUT = 5 * 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)
@@ -54,10 +52,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 +74,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 +97,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
@@ -124,13 +118,11 @@ export const useAuthStore = defineStore('auth', () => {
currentUserID, currentUserID,
token, token,
rememberMe, rememberMe,
setToken,
getToken, getToken,
login, login,
logout, logout,
resetTokenExpiry, resetTokenExpiry,
isTokenAlmostExpired, isTokenAlmostExpired,
checkTokenExpiry,
restoreSession, restoreSession,
} }
}) })
+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,
}
})
+7 -49
View File
@@ -1,58 +1,16 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import axios from 'axios' import axios from 'axios'
import { useAuthStore } from './auth' import { inject } from 'vue'
export const useUserStore = defineStore('user', { export const useUserStore = defineStore('user', () => {
state: () => ({
user: null,
loading: false,
error: null
}),
getters: { const API_BASE_URL = inject('apiBaseURL')
currentUser: (state) => state.user
},
actions: { const getCoins = async () => {
async fetchUserProfile() { return await axios.get(`${API_BASE_URL}/users/me/coins`)
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 return {
this.error = null getCoins,
try {
const response = await axios.get('/api/users/me', {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
})
this.user = response.data
return response.data
} catch (error) {
this.error = error.response?.data?.message || 'Failed to fetch user profile'
if (error.response?.status === 401) {
authStore.logout()
}
throw error
} finally {
this.loading = false
}
},
clearUser() {
this.user = null
this.error = null
this.loading = false
}
} }
}) })