Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0af76abd3 | ||
|
|
ff16a57a97 | ||
|
|
cf238d5451 | ||
|
|
50ae1b7f1f | ||
|
|
5975208877 | ||
|
|
f3e8ffc400 | ||
|
|
1b03558f93 | ||
|
|
881a60a388 |
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\CoinPurchase;
|
||||||
|
use App\Models\CoinTransaction;
|
||||||
|
use App\Models\CoinTransactionType;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class CoinPurchaseController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Request $request)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'euros' => 'required|numeric|min:1|max:100',
|
||||||
|
'payment_type' => 'required|in:MBWAY,MB,VISA,PAYPAL',
|
||||||
|
'payment_reference' => [
|
||||||
|
'required',
|
||||||
|
function ($attribute, $value, $fail) use ($request) {
|
||||||
|
$type = $request->payment_type;
|
||||||
|
$regex = null;
|
||||||
|
|
||||||
|
switch ($type) {
|
||||||
|
case 'MBWAY': $regex = '/^9[0-9]{8}$/'; break;
|
||||||
|
case 'MB': $regex = '/^[0-9]{5}-[0-9]{9}$/'; break;
|
||||||
|
case 'VISA': $regex = '/^4[0-9]{15}$/'; break;
|
||||||
|
case 'PAYPAL':
|
||||||
|
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
||||||
|
$fail("Invalid PayPal email.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($regex && !preg_match($regex, $value)) {
|
||||||
|
$fail("Invalid format for $type.");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
$coinsAmount = $validated['euros'] * 10;
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($user, $validated, $coinsAmount) {
|
||||||
|
|
||||||
|
$type = CoinTransactionType::firstOrCreate(['name' => 'Coin purchase'], ['type' => 'C']);
|
||||||
|
|
||||||
|
$transaction = CoinTransaction::create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'coin_transaction_type_id' => $type->id,
|
||||||
|
'transaction_datetime' => now(),
|
||||||
|
'coins' => $coinsAmount,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$purchase = CoinPurchase::create([
|
||||||
|
'purchase_datetime' => now(),
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'coin_transaction_id' => $transaction->id,
|
||||||
|
'euros' => $validated['euros'],
|
||||||
|
'payment_type' => $validated['payment_type'],
|
||||||
|
'payment_reference' => $validated['payment_reference'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user->increment('coins_balance', $coinsAmount);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Purchase successful',
|
||||||
|
'balance' => $user->coins_balance,
|
||||||
|
'transaction_id' => $transaction->id,
|
||||||
|
'purchase' => $purchase,
|
||||||
|
], 201);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,7 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\Game;
|
use App\Models\Game;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use App\Http\Requests\StoreGameRequest;
|
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use App\Models\MatchGame;
|
|
||||||
|
|
||||||
class GameController extends Controller
|
class GameController extends Controller
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\MatchGame;
|
use App\Models\MatchGame;
|
||||||
use App\Models\Game;
|
use App\Models\Game;
|
||||||
|
use App\Models\CoinTransaction;
|
||||||
|
use App\Models\CoinTransactionType;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use App\Http\Requests\StoreMatchRequest;
|
use App\Http\Requests\StoreMatchRequest;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
class MatchController extends Controller
|
class MatchController extends Controller
|
||||||
{
|
{
|
||||||
@@ -30,42 +33,59 @@ class MatchController extends Controller
|
|||||||
public function store(StoreMatchRequest $request)
|
public function store(StoreMatchRequest $request)
|
||||||
{
|
{
|
||||||
$validated = $request->validated();
|
$validated = $request->validated();
|
||||||
$user = Auth::user();
|
$user = $request->user();
|
||||||
|
$stake = $validated['stake'];
|
||||||
|
|
||||||
|
if ($user->coins_balance < $stake) {
|
||||||
|
return response()->json(['message' => 'Insufficient coin balance'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
$q->where('player1_user_id', $user->id)
|
$q->where('player1_user_id', $user->id)
|
||||||
->orWhere('player2_user_id', $user->id);
|
->orWhere('player2_user_id', $user->id);
|
||||||
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
||||||
|
|
||||||
$activeGame = Game::where(function ($q) use ($user) {
|
if ($activeMatch) {
|
||||||
$q->where('player1_user_id', $user->id)
|
return response()->json(['message' => 'You already have an active match.'], 400);
|
||||||
->orWhere('player2_user_id', $user->id);
|
|
||||||
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
|
||||||
|
|
||||||
if ($activeMatch || $activeGame) {
|
|
||||||
return response()->json(['message' => 'You already have an active game or match.'], 400);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($validated, $user, $stake) {
|
||||||
|
$GHOST_ID = 1;
|
||||||
|
|
||||||
|
$user->decrement('coins_balance', $stake);
|
||||||
|
|
||||||
|
$stakeType = CoinTransactionType::firstOrCreate(
|
||||||
|
['name' => 'Match stake'],
|
||||||
|
['type' => 'D'] // Debit
|
||||||
|
);
|
||||||
|
|
||||||
$match = MatchGame::create([
|
$match = MatchGame::create([
|
||||||
'type' => $validated['type'],
|
'type' => $validated['type'],
|
||||||
'status' => 'Pending',
|
'status' => 'Pending',
|
||||||
'player1_user_id' => $user->id,
|
'player1_user_id' => $user->id,
|
||||||
'player2_user_id' => $user->id,
|
'player2_user_id' => $GHOST_ID,
|
||||||
'winner_user_id' => $user->id,
|
'winner_user_id' => $GHOST_ID,
|
||||||
'loser_user_id' => $user->id,
|
'loser_user_id' => $GHOST_ID,
|
||||||
'stake' => $validated['stake'],
|
'stake' => $stake,
|
||||||
'began_at' => now(),
|
'began_at' => now(),
|
||||||
'player1_marks' => 0,
|
'player1_marks' => 0, 'player2_marks' => 0,
|
||||||
'player2_marks' => 0,
|
'player1_points' => 0, 'player2_points' => 0,
|
||||||
'player1_points' => 0,
|
]);
|
||||||
'player2_points' => 0,
|
|
||||||
'custom' => null
|
CoinTransaction::create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'match_id' => $match->id,
|
||||||
|
'coin_transaction_type_id' => $stakeType->id,
|
||||||
|
'transaction_datetime' => now(),
|
||||||
|
'coins' => -$stake,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'message' => 'Match created successfully',
|
'message' => 'Match created successfully',
|
||||||
'match' => $match
|
'match' => $match,
|
||||||
|
'balance' => $user->coins_balance
|
||||||
], 201);
|
], 201);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(MatchGame $match)
|
public function show(MatchGame $match)
|
||||||
@@ -76,16 +96,19 @@ class MatchController extends Controller
|
|||||||
|
|
||||||
public function join(MatchGame $match)
|
public function join(MatchGame $match)
|
||||||
{
|
{
|
||||||
$user = Auth::user();
|
$user = request()->user();
|
||||||
|
|
||||||
if ($match->player1_user_id == $user->id) {
|
if ($match->player1_user_id == $user->id) {
|
||||||
return response()->json(['message' => 'Waiting for opponent...', 'match' => $match]);
|
return response()->json(['message' => 'You cannot join your own match'], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($match->status !== 'Pending') {
|
if ($match->status !== 'Pending') {
|
||||||
return response()->json(['message' => 'Match is full or started'], 400);
|
return response()->json(['message' => 'Match is full or started'], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($user->coins_balance < $match->stake) {
|
||||||
|
return response()->json(['message' => 'Insufficient coin balance to join this match'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
$q->where('player1_user_id', $user->id)
|
$q->where('player1_user_id', $user->id)
|
||||||
->orWhere('player2_user_id', $user->id);
|
->orWhere('player2_user_id', $user->id);
|
||||||
@@ -95,6 +118,22 @@ class MatchController extends Controller
|
|||||||
return response()->json(['message' => 'You are already in another active match.'], 400);
|
return response()->json(['message' => 'You are already in another active match.'], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($match, $user) {
|
||||||
|
$user->decrement('coins_balance', $match->stake);
|
||||||
|
|
||||||
|
$stakeType = CoinTransactionType::firstOrCreate(
|
||||||
|
['name' => 'Match stake'],
|
||||||
|
['type' => 'D']
|
||||||
|
);
|
||||||
|
|
||||||
|
CoinTransaction::create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'match_id' => $match->id,
|
||||||
|
'coin_transaction_type_id' => $stakeType->id,
|
||||||
|
'transaction_datetime' => now(),
|
||||||
|
'coins' => -$match->stake,
|
||||||
|
]);
|
||||||
|
|
||||||
$match->update([
|
$match->update([
|
||||||
'status' => 'Playing',
|
'status' => 'Playing',
|
||||||
'player2_user_id' => $user->id
|
'player2_user_id' => $user->id
|
||||||
@@ -102,8 +141,10 @@ class MatchController extends Controller
|
|||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'message' => 'Joined match successfully!',
|
'message' => 'Joined match successfully!',
|
||||||
'match' => $match
|
'match' => $match,
|
||||||
|
'balance' => $user->coins_balance
|
||||||
]);
|
]);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function update(Request $request, MatchGame $match)
|
public function update(Request $request, MatchGame $match)
|
||||||
@@ -123,12 +164,36 @@ class MatchController extends Controller
|
|||||||
'total_time' => 'numeric'
|
'total_time' => 'numeric'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($match, $data) {
|
||||||
|
|
||||||
if (isset($data['status']) && $data['status'] === 'Ended') {
|
if (isset($data['status']) && $data['status'] === 'Ended') {
|
||||||
$data['ended_at'] = now();
|
$data['ended_at'] = now();
|
||||||
}
|
}
|
||||||
|
|
||||||
$match->update($data);
|
$match->update($data);
|
||||||
|
|
||||||
|
if ($match->status === 'Ended' && $match->stake > 0 && $match->winner_user_id) {
|
||||||
|
|
||||||
|
$payoutType = CoinTransactionType::firstOrCreate(
|
||||||
|
['name' => 'Match payout'],
|
||||||
|
['type' => 'C'] // Credit
|
||||||
|
);
|
||||||
|
|
||||||
|
$totalPrize = $match->stake * 2;
|
||||||
|
|
||||||
|
CoinTransaction::create([
|
||||||
|
'user_id' => $match->winner_user_id,
|
||||||
|
'match_id' => $match->id,
|
||||||
|
'coin_transaction_type_id' => $payoutType->id,
|
||||||
|
'transaction_datetime' => now(),
|
||||||
|
'coins' => $totalPrize,
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
$match->winner->increment('coins_balance', $totalPrize);
|
||||||
|
}
|
||||||
|
|
||||||
return response()->json($match);
|
return response()->json($match);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,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);
|
||||||
@@ -230,7 +279,7 @@ class UserController extends Controller
|
|||||||
|
|
||||||
if ($request->has('type')) {
|
if ($request->has('type')) {
|
||||||
$query->whereHas('type', function ($q) use ($request) {
|
$query->whereHas('type', function ($q) use ($request) {
|
||||||
$q->where('name', $request->type);
|
$q->where('type', $request->type);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class CoinPurchase extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $table = 'coin_purchases';
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'purchase_datetime',
|
||||||
|
'user_id',
|
||||||
|
'coin_transaction_id',
|
||||||
|
'euros',
|
||||||
|
'payment_type',
|
||||||
|
'payment_reference',
|
||||||
|
'custom'
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'purchase_datetime' => 'datetime',
|
||||||
|
'custom' => 'array',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function transaction()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(CoinTransaction::class, 'coin_transaction_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\MatchController;
|
|||||||
use App\Http\Controllers\ProfileController;
|
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 Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('v1')->group(function () {
|
Route::prefix('v1')->group(function () {
|
||||||
@@ -19,6 +20,7 @@ Route::prefix('v1')->group(function () {
|
|||||||
// Authenticated Routes
|
// Authenticated Routes
|
||||||
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
|
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||||
Route::post('/logout', [AuthController::class, 'logout']);
|
Route::post('/logout', [AuthController::class, 'logout']);
|
||||||
|
Route::post('/coin-purchases', [CoinPurchaseController::class, 'store']);
|
||||||
Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']);
|
Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']);
|
||||||
Route::prefix('users/me')->group(function () {
|
Route::prefix('users/me')->group(function () {
|
||||||
Route::get('/', [ProfileController::class, 'show']);
|
Route::get('/', [ProfileController::class, 'show']);
|
||||||
|
|||||||
@@ -25,8 +25,32 @@ Content-Type: application/json
|
|||||||
Accept: application/json
|
Accept: application/json
|
||||||
Authorization: Bearer {{token}}
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### Get me coins
|
||||||
|
GET http://localhost:8000/api/v1/users/me/coins
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
### Get me matches
|
### Get me matches
|
||||||
GET http://localhost:8000/api/v1/users/{{id}}/matches
|
GET http://localhost:8000/api/v1/users/{{id}}/matches
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
Accept: application/json
|
Accept: application/json
|
||||||
Authorization: Bearer {{token}}
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### Get me transactions
|
||||||
|
GET http://localhost:8000/api/v1/users/{{id}}/transactions?type=C
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### post coin-purchases
|
||||||
|
POST http://localhost:8000/api/v1/coin-purchases
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
{
|
||||||
|
"euros": 1,
|
||||||
|
"payment_type": "MBWAY",
|
||||||
|
"payment_reference": "912345678"
|
||||||
|
}
|
||||||
@@ -23,14 +23,14 @@
|
|||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
<NavigationMenuItem v-else class="flex flex-row gap-4">
|
<NavigationMenuItem v-else class="flex flex-row gap-4">
|
||||||
<NavigationMenuLink v-if="coins > 0" href="/user?tab=transaction-history"
|
<NavigationMenuLink v-if="userStore.coins > 0" href="/coins-purchase"
|
||||||
class="flex flex-row items-center gap-1">
|
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">
|
<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>
|
<span class="text-[10px] font-bold text-purple-900">$</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="text-sm font-medium tabular-nums">
|
<span class="text-sm font-medium tabular-nums">
|
||||||
{{ coins }} <span class="text-muted-foreground text-xs">Coins</span>
|
{{ userStore.coins }} <span class="text-muted-foreground text-xs">Coins</span>
|
||||||
</span>
|
</span>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
<NavigationMenuLink>
|
<NavigationMenuLink>
|
||||||
@@ -56,13 +56,12 @@ 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 { watch } from 'vue';
|
||||||
import { useUserStore } from '@/stores/user';
|
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()
|
||||||
|
|
||||||
@@ -84,22 +83,13 @@ const logoutClickHandler = () => {
|
|||||||
router.push('/login')
|
router.push('/login')
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchUserCoins = async () => {
|
const userStore = useUserStore()
|
||||||
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) => {
|
watch(() => userLoggedIn, async (isLoggedIn) => {
|
||||||
if (isLoggedIn) {
|
if (isLoggedIn) {
|
||||||
await fetchUserCoins()
|
await userStore.fetchCoins()
|
||||||
} else {
|
} else {
|
||||||
coins.value = 0
|
userStore.coins = 0
|
||||||
}
|
}
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
</script>
|
</script>
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex min-h-screen items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
|
||||||
|
<div class="w-full max-w-md space-y-8">
|
||||||
|
<div>
|
||||||
|
<h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">Buy Coins</h2>
|
||||||
|
<p class="mt-2 text-center text-sm text-gray-600">€1.00 = 10 Coins</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="mt-8 space-y-4" @submit.prevent="handleSubmit">
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Amount (Euros)</label>
|
||||||
|
<Input v-model.number="formData.euros" type="number" min="1" max="100" placeholder="Ex: 10"
|
||||||
|
required />
|
||||||
|
<p class="mt-1 text-xs text-blue-600 font-medium">
|
||||||
|
You will receive: {{ formData.euros * 10 }} coins
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
|
||||||
|
<select v-model="formData.payment_type"
|
||||||
|
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
|
||||||
|
<option value="MBWAY">MB WAY</option>
|
||||||
|
<option value="MB">Multibanco (MB)</option>
|
||||||
|
<option value="VISA">VISA</option>
|
||||||
|
<option value="PAYPAL">PayPal</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{{ referenceLabel }}
|
||||||
|
</label>
|
||||||
|
<Input v-model="formData.payment_reference" type="text" :placeholder="referencePlaceholder"
|
||||||
|
required />
|
||||||
|
<p v-if="errors.payment_reference" class="mt-1 text-xs text-red-500">
|
||||||
|
{{ errors.payment_reference }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pt-4">
|
||||||
|
<Button type="submit" class="w-full">
|
||||||
|
Confirm Purchase (€{{ formData.euros }})
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { usePurchaseStore } from '@/stores/purchase'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
const purchaseStore = usePurchaseStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const formData = ref({
|
||||||
|
euros: 1,
|
||||||
|
payment_type: 'MBWAY',
|
||||||
|
payment_reference: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const errors = ref({})
|
||||||
|
|
||||||
|
const referenceLabel = computed(() => {
|
||||||
|
const labels = {
|
||||||
|
MBWAY: 'Phone Number',
|
||||||
|
MB: 'Entity-Reference',
|
||||||
|
VISA: 'Card Number',
|
||||||
|
PAYPAL: 'PayPal Email'
|
||||||
|
}
|
||||||
|
return labels[formData.value.payment_type]
|
||||||
|
})
|
||||||
|
|
||||||
|
const referencePlaceholder = computed(() => {
|
||||||
|
const placeholders = {
|
||||||
|
MBWAY: '912345678',
|
||||||
|
MB: '12345-123456789',
|
||||||
|
VISA: '1234 5678 9012 3456',
|
||||||
|
PAYPAL: '[email protected]'
|
||||||
|
}
|
||||||
|
return placeholders[formData.value.payment_type]
|
||||||
|
})
|
||||||
|
|
||||||
|
const validateForm = () => {
|
||||||
|
errors.value = {}
|
||||||
|
const type = formData.value.payment_type
|
||||||
|
const refValue = formData.value.payment_reference
|
||||||
|
|
||||||
|
const patterns = {
|
||||||
|
MBWAY: /^9[0-9]{8}$/,
|
||||||
|
MB: /^[0-9]{5}-[0-9]{9}$/,
|
||||||
|
VISA: /^4[0-9]{15}$/,
|
||||||
|
PAYPAL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!patterns[type].test(refValue)) {
|
||||||
|
errors.value.payment_reference = `Invalid format for ${type}`
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.value.euros < 1 || formData.value.euros > 100) {
|
||||||
|
toast.error("Amount must be between 1 and 100")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!validateForm()) return
|
||||||
|
|
||||||
|
const promise = purchaseStore.purchase(formData.value)
|
||||||
|
|
||||||
|
toast.promise(promise, {
|
||||||
|
loading: 'Processing transaction...',
|
||||||
|
success: (res) => {
|
||||||
|
userStore.fetchCoins()
|
||||||
|
router.push('/')
|
||||||
|
return `Purchase successful! New balance: ${res.data.balance} coins`
|
||||||
|
},
|
||||||
|
error: (error) => {
|
||||||
|
if (error.response?.status === 422) {
|
||||||
|
errors.value = error.response.data.errors
|
||||||
|
return "Please check the highlighted fields"
|
||||||
|
}
|
||||||
|
return error.response?.data?.message || "Transaction failed"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -229,11 +229,6 @@
|
|||||||
|
|
||||||
<!-- Transaction History Tab -->
|
<!-- Transaction History Tab -->
|
||||||
<div v-if="activeTab === 'transaction-history'" class="p-8">
|
<div v-if="activeTab === 'transaction-history'" class="p-8">
|
||||||
<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 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">
|
||||||
@@ -248,7 +243,7 @@
|
|||||||
|
|
||||||
<div class="flex flex-col gap-1">
|
<div class="flex flex-col gap-1">
|
||||||
<label class="text-xs font-medium text-muted-foreground">From</label>
|
<label class="text-xs font-medium text-muted-foreground">From</label>
|
||||||
<input type="date" v-model="filters.startDate" :max="filters.endDate" @change="handleStartDateChange"
|
<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" />
|
class="bg-background border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500 outline-none" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -263,11 +258,15 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</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"
|
<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="flex items-center justify-between p-4 mb-3 border rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500"
|
||||||
:class="[
|
:class="[transaction.type === 'credit' ? 'border-green-500/30' : 'border-red-500/30']">
|
||||||
transaction.type === 'credit' ? 'border-green-500/30' : 'border-red-500/30'
|
|
||||||
]">
|
|
||||||
|
|
||||||
<div class="flex items-center gap-4">
|
<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"
|
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold"
|
||||||
@@ -277,12 +276,12 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col">
|
<div class="flex flex-col">
|
||||||
<div class="font-semibold text-sm capitalize">
|
<div class="font-semibold text-sm">
|
||||||
{{ transaction.type }} Payment
|
{{ transaction.category }} </div>
|
||||||
</div>
|
|
||||||
<div class="text-xs text-muted-foreground">
|
<div class="text-xs text-muted-foreground">
|
||||||
{{ new Date(transaction.created_at).toLocaleDateString() }} • {{ new
|
{{ new Date(transaction.began_at).toLocaleDateString() }} •
|
||||||
Date(transaction.created_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>
|
||||||
@@ -290,11 +289,10 @@
|
|||||||
<div class="text-right">
|
<div class="text-right">
|
||||||
<div class="font-bold text-sm"
|
<div class="font-bold text-sm"
|
||||||
:class="transaction.type === 'credit' ? 'text-green-600' : 'text-red-600'">
|
:class="transaction.type === 'credit' ? 'text-green-600' : 'text-red-600'">
|
||||||
{{ transaction.type === 'credit' ? '+' : '-' }}${{ transaction.amount.toLocaleString() }}
|
{{ transaction.type === 'credit' ? '+' : '-' }}{{ transaction.amount }} coins
|
||||||
</div>
|
</div>
|
||||||
<div class="text-[10px] text-muted-foreground uppercase tracking-wider">
|
<div class="text-[10px] text-muted-foreground uppercase tracking-wider">
|
||||||
{{ transaction.id.split('_')[0] }}
|
{{ transaction.reference }} </div>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -308,12 +306,6 @@
|
|||||||
|
|
||||||
<!-- Game History Tab -->
|
<!-- Game History Tab -->
|
||||||
<div v-if="activeTab === 'game-history'" class="p-8">
|
<div v-if="activeTab === 'game-history'" class="p-8">
|
||||||
<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 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>
|
||||||
@@ -337,6 +329,18 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</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">
|
<button @click="clearFilters" class="text-xs text-purple-500 hover:underline pb-2">
|
||||||
Clear Filters
|
Clear Filters
|
||||||
</button>
|
</button>
|
||||||
@@ -363,7 +367,11 @@
|
|||||||
</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"
|
<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">
|
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 justify-between">
|
||||||
@@ -383,13 +391,13 @@
|
|||||||
<div class="text-right">
|
<div class="text-right">
|
||||||
<div class="font-bold text-sm">{{ game.amount }} pts</div>
|
<div class="font-bold text-sm">{{ game.amount }} pts</div>
|
||||||
<div class="text-[10px] text-muted-foreground">
|
<div class="text-[10px] text-muted-foreground">
|
||||||
{{ new Date(game.created_at).toLocaleTimeString() }}
|
{{ new Date(game.began_at).toLocaleDateString() }} • {{ new
|
||||||
|
Date(game.began_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-3 pt-3 border-t flex gap-4 text-[10px] uppercase font-medium text-muted-foreground">
|
<div class="mt-3 pt-3 border-t flex gap-4 text-[10px] uppercase font-medium text-muted-foreground">
|
||||||
<span>Marks: {{ game.details.marks }}</span>
|
|
||||||
<span>Capotes: {{ game.details.capotes }}</span>
|
<span>Capotes: {{ game.details.capotes }}</span>
|
||||||
<span>Bandeiras: {{ game.details.bandeiras }}</span>
|
<span>Bandeiras: {{ game.details.bandeiras }}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -579,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: ''
|
||||||
@@ -588,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: '',
|
||||||
@@ -598,7 +604,6 @@ 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)
|
||||||
@@ -622,13 +627,12 @@ const filters = ref({
|
|||||||
startDate: '',
|
startDate: '',
|
||||||
endDate: '',
|
endDate: '',
|
||||||
sort: {
|
sort: {
|
||||||
column: 'created_at',
|
column: 'began_at',
|
||||||
order: 'desc'
|
order: 'desc'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleSortChange = (column) => {
|
const handleSortChange = (column) => {
|
||||||
// If clicking same column, toggle order, else default to desc
|
|
||||||
if (filters.value.sort.column === column) {
|
if (filters.value.sort.column === column) {
|
||||||
filters.value.sort.order = filters.value.sort.order === 'asc' ? 'desc' : 'asc';
|
filters.value.sort.order = filters.value.sort.order === 'asc' ? 'desc' : 'asc';
|
||||||
} else {
|
} else {
|
||||||
@@ -660,18 +664,26 @@ const fetchData = async () => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
let newData = [];
|
let newData = [];
|
||||||
if (isTransaction) {
|
|
||||||
// const response = await apiStore.getTransactions(params);
|
|
||||||
// Logic: if response.data.length < limit, set hasMore.value = false
|
|
||||||
|
|
||||||
for (let i = 0; i < 15; i++) {
|
if (isTransaction) {
|
||||||
newData.push({
|
const apiParams = {
|
||||||
id: `txn_${Date.now()}_${i}`,
|
page: state.page,
|
||||||
amount: Math.floor(Math.random() * 1000),
|
type: filters.value.type === 'credit' ? 'C' : filters.value.type === 'debit' ? 'D' : undefined,
|
||||||
type: Math.random() > 0.5 ? 'credit' : 'debit',
|
date_from: filters.value.startDate || undefined,
|
||||||
created_at: new Date().toISOString()
|
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);
|
transactions.value.push(...newData);
|
||||||
}
|
}
|
||||||
@@ -680,25 +692,24 @@ const fetchData = async () => {
|
|||||||
const apiParams = {
|
const apiParams = {
|
||||||
page: state.page,
|
page: state.page,
|
||||||
type: filters.value.variant !== 'all' ? filters.value.variant : undefined,
|
type: filters.value.variant !== 'all' ? filters.value.variant : undefined,
|
||||||
status: filters.value.outcome !== 'all' ? 'Ended' : 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_by: filters.value.sort.column,
|
||||||
sort_direction: filters.value.sort.order
|
sort_direction: filters.value.sort.order,
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await apiStore.getCurrentUserMatches(apiParams);
|
const response = await apiStore.getCurrentUserMatches(apiParams);
|
||||||
const apiGames = response.data.data
|
const apiGames = response.data.data;
|
||||||
|
|
||||||
newData = apiGames.map(game => {
|
newData = apiGames.map(game => {
|
||||||
const isPlayer1 = game.player1_user_id === authStore.currentUserID;
|
const isPlayer1 = game.player1_user_id === authStore.currentUser.id;
|
||||||
const opponent = isPlayer1 ? game.player2 : game.player1;
|
const opponent = isPlayer1 ? game.player2 : game.player1;
|
||||||
|
|
||||||
let outcome = 'loss';
|
let outcome = 'loss';
|
||||||
if (game.is_draw) outcome = 'draw';
|
if (game.is_draw) outcome = 'draw';
|
||||||
else if (game.winner_user_id === authStore.currentUserID) outcome = 'win';
|
else if (game.winner_user_id === authStore.currentUser.id) outcome = 'win';
|
||||||
|
|
||||||
const minutes = Math.floor(game.total_time / 60);
|
|
||||||
const seconds = game.total_time % 60;
|
|
||||||
const durationStr = `${minutes}m ${seconds}s`;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: game.id,
|
id: game.id,
|
||||||
@@ -706,16 +717,14 @@ const fetchData = async () => {
|
|||||||
outcome: outcome,
|
outcome: outcome,
|
||||||
opponent: opponent?.nickname || 'Unknown Player',
|
opponent: opponent?.nickname || 'Unknown Player',
|
||||||
amount: isPlayer1 ? game.player1_points : game.player2_points,
|
amount: isPlayer1 ? game.player1_points : game.player2_points,
|
||||||
duration: durationStr,
|
duration: `${Math.floor(game.total_time / 60)}m ${game.total_time % 60}s`,
|
||||||
created_at: game.began_at,
|
began_at: game.began_at,
|
||||||
details: {
|
details: {
|
||||||
marks: game.custom?.marks || 0,
|
capotes: 0,
|
||||||
capotes: game.custom?.capotes || 0,
|
bandeiras: 0
|
||||||
bandeiras: game.custom?.bandeiras || 0
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
games.value.push(...newData);
|
games.value.push(...newData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -733,16 +742,23 @@ const setupObserver = () => {
|
|||||||
|
|
||||||
const scrollContainer = document.querySelector('.custom-scrollbar');
|
const scrollContainer = document.querySelector('.custom-scrollbar');
|
||||||
|
|
||||||
observer.value = new IntersectionObserver((entries) => {
|
observer.value = new IntersectionObserver(async (entries) => {
|
||||||
if (entries[0].isIntersecting && !isLoading.value) {
|
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();
|
fetchData();
|
||||||
}
|
}
|
||||||
}, { root: scrollContainer, threshold: 0.1 });
|
}, {
|
||||||
|
root: scrollContainer,
|
||||||
|
threshold: 0.1,
|
||||||
|
rootMargin: '100px'
|
||||||
|
});
|
||||||
|
|
||||||
if (observerTarget.value) observer.value.observe(observerTarget.value);
|
if (observerTarget.value) observer.value.observe(observerTarget.value);
|
||||||
};
|
};
|
||||||
|
|
||||||
const resetAndFetch = () => {
|
const resetAndFetch = async () => {
|
||||||
if (activeTab.value === 'transaction-history') {
|
if (activeTab.value === 'transaction-history') {
|
||||||
transactions.value = [];
|
transactions.value = [];
|
||||||
pagination.value.transactions = { page: 1, hasMore: true };
|
pagination.value.transactions = { page: 1, hasMore: true };
|
||||||
@@ -753,7 +769,44 @@ const resetAndFetch = () => {
|
|||||||
pagination.value.games = { page: 1, hasMore: true };
|
pagination.value.games = { page: 1, hasMore: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchData();
|
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) => {
|
||||||
@@ -895,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
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ 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 RegisterPage from '@/pages/register/RegisterPage.vue'
|
import RegisterPage from '@/pages/register/RegisterPage.vue'
|
||||||
|
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHistory(import.meta.env.BASE_URL),
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
@@ -46,6 +47,12 @@ const router = createRouter({
|
|||||||
{
|
{
|
||||||
path: '/user',
|
path: '/user',
|
||||||
component: UserPage,
|
component: UserPage,
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/coins-purchase',
|
||||||
|
component: CoinsPurchasePage,
|
||||||
|
meta: { requiresAuth: true },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/testing',
|
path: '/testing',
|
||||||
|
|||||||
@@ -80,22 +80,35 @@ 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.outcome && { outcome: params.outcome }),
|
||||||
...(params.status && { status: params.status }),
|
...(params.status && { status: params.status }),
|
||||||
sort_by: params.sort || 'began_at',
|
...(params.date_from && { date_from: params.date_from }),
|
||||||
sort_direction: params.direction || 'desc',
|
...(params.date_to && { date_to: params.date_to }),
|
||||||
|
sort_by: params.sort_by || 'began_at',
|
||||||
|
sort_direction: params.sort_direction || 'desc',
|
||||||
}).toString()
|
}).toString()
|
||||||
|
|
||||||
console.log(params, queryParams)
|
|
||||||
|
|
||||||
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/matches?${queryParams}`)
|
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,
|
getCurrentUserMatches,
|
||||||
|
getCurrentUserTransactions,
|
||||||
gameQueryParameters,
|
gameQueryParameters,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { inject } from 'vue'
|
||||||
|
|
||||||
|
export const usePurchaseStore = defineStore('purchase', () => {
|
||||||
|
|
||||||
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
|
|
||||||
|
const purchase = async (data) => {
|
||||||
|
return await axios.post(`${API_BASE_URL}/coin-purchases`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
purchase,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -1,16 +1,24 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { inject } from 'vue'
|
import { inject, ref } from 'vue'
|
||||||
|
|
||||||
export const useUserStore = defineStore('user', () => {
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
|
||||||
const API_BASE_URL = inject('apiBaseURL')
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
|
const coins = ref(0)
|
||||||
|
|
||||||
const getCoins = async () => {
|
const fetchCoins = async () => {
|
||||||
return await axios.get(`${API_BASE_URL}/users/me/coins`)
|
try {
|
||||||
|
const response = await axios.get(`${API_BASE_URL}/users/me/coins`)
|
||||||
|
coins.value = response.data?.coins || 0
|
||||||
|
return response
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching coins', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getCoins,
|
coins,
|
||||||
|
fetchCoins,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
Reference in New Issue
Block a user