=== .\app\Http\Controllers\LobbyHubController.php === 340: $now = now(); 341: 342: $reportPayload = [ 343: 'training_match_id' => $lobbyId, 344: 'reported_by' => $userId, 345: 'team_a_score' => $scoreA, 346: 'team_b_score' => $scoreB, 347: 'winner_team' => $winner, 348: 'notes' => trim((string) ($request->input('considerations') ?: $resultText)), 349: 'updated_at' => $now, 350: ]; 351: 352: $existingReport = DB::table('lobby_match_reports')->where('training_match_id', $lobbyId)->first(); 353: if ($existingReport) { 354: DB::table('lobby_match_reports')->where('id', $existingReport->id)->update($reportPayload); 355: } else { 356: $reportPayload['created_at'] = $now; 357: DB::table('lobby_match_reports')->insert($reportPayload); 358: } 359: 360: $participants = DB::table('mix_training_participants') 361: ->where('training_match_id', $lobbyId) 362: ->whereNull('left_at') 363: ->select('user_id', 'team', 'joined_at') 364: ->get(); 365: 366: if ((bool) ($match->affects_rank ?? false) && $participants->count() !== 10) { 367: throw new \RuntimeException('Partida ranqueada precisa possuir exatamente 10 jogadores ativos no encerramento.'); 368: } 369: 370: // Idempotência: history é o selo de que pontuação já foi aplicada. 371: $alreadyRanked = Schema::hasTable('mix_match_history') 372: && DB::table('mix_match_history')->where('match_id', $lobbyId)->exists(); 373: 374: if (Schema::hasTable('mix_match_players')) { 375: foreach ($participants as $p) { 376: $exists = DB::table('mix_match_players') 377: ->where('match_id', $lobbyId) 378: ->where('user_id', (int) $p->user_id) 379: ->exists(); 380: 381: if (!$exists) { 382: $captain = Schema::hasTable('lobby_match_captains') 383: && DB::table('lobby_match_captains') 384: ->where('training_match_id', $lobbyId) 385: ->where('user_id', (int) $p->user_id) 386: ->exists(); 387: 388: DB::table('mix_match_players')->insert([ 389: 'match_id' => $lobbyId, 390: 'user_id' => (int) $p->user_id, 391: 'team' => (int) $p->team, 392: 'is_captain' => $captain ? 1 : 0, 393: 'created_at' => $now, 394: ]); 395: } 396: } 397: } 398: 399: if (Schema::hasTable('mix_match_results') 400: && !DB::table('mix_match_results')->where('match_id', $lobbyId)->exists()) { 401: DB::table('mix_match_results')->insert([ 402: 'match_id' => $lobbyId, 403: 'winning_team' => $winner, 404: 'ace_user_id' => null, 405: 'mvp_user_id' => null, 406: 'result_text' => $resultText, 407: 'recorded_at' => $now, 408: ]); 409: } 410: 411: if (Schema::hasTable('mix_match_history') && !$alreadyRanked) { 412: $duration = null; 413: if (!empty($match->started_at)) { 414: $duration = max(0, \Carbon\Carbon::parse($match->started_at)->diffInSeconds($now)); 415: } 416: 417: DB::table('mix_match_history')->insert([ 418: 'match_id' => $lobbyId, 419: 'winning_team' => $winner, 420: 'map_played' => (string) ($match->map_name ?? ''), 421: 'duration_seconds' => $duration, 422: 'completed_at' => $now, 423: ]); 424: } 425: 426: // Pontuação oficial: Vitória +5 / Derrota -3. Uma única vez. 427: if ((bool) ($match->affects_rank ?? false) && $winner !== null && !$alreadyRanked) { 428: $gameSlug = strtolower(trim((string) ($match->game_slug ?? 'crossfire'))) ?: 'crossfire'; 429: $queueMode = strtolower(trim((string) ($match->queue_mode ?? 'casual'))); 430: $queueMode = in_array($queueMode, ['profissional', 'professional', 'pro', 'ranked', 'competitivo', 'competitive'], true) 431: ? 'profissional' 432: : 'casual'; 433: 434: foreach ($participants as $p) { 435: $uid = (int) $p->user_id; 436: $won = (int) $p->team === (int) $winner; 437: $delta = $won ? 5 : -3; 438: 439: // Ranking mostrado no dashboard atual. 440: if (Schema::hasTable('mix_ranking_modes')) { 441: $rank = DB::table('mix_ranking_modes') 442: ->where('user_id', $uid) 443: ->where('game_slug', $gameSlug) 444: ->where('queue_mode', $queueMode) 445: ->lockForUpdate() 446: ->first(); 447: 448: if ($rank) { 449: DB::table('mix_ranking_modes') 450: ->where('id', $rank->id) 451: ->update([ 452: 'points' => (int) ($rank->points ?? 1000) + $delta, 453: 'matches_played' => (int) ($rank->matches_played ?? 0) + 1, 454: 'wins' => (int) ($rank->wins ?? 0) + ($won ? 1 : 0), 455: 'losses' => (int) ($rank->losses ?? 0) + ($won ? 0 : 1), 456: 'updated_at' => $now, 457: ]); 458: } else { 459: DB::table('mix_ranking_modes')->insert([ 460: 'user_id' => $uid, 461: 'game_slug' => $gameSlug, 462: 'queue_mode' => $queueMode, 463: 'points' => 1000 + $delta, 464: 'wins' => $won ? 1 : 0, 465: 'losses' => $won ? 0 : 1, 466: 'matches_played' => 1, 467: 'kd_ratio' => 0, 468: 'created_at' => $now, 469: 'updated_at' => $now, 470: ]); 471: } 472: } 473: 474: // Mantém o XP mensal/lifetime sincronizado. 475: if (Schema::hasTable('gx_player_experience')) { 476: $xp = DB::table('gx_player_experience')->where('user_id', $uid)->lockForUpdate()->first(); 477: 478: if ($xp) { 479: DB::table('gx_player_experience')->where('user_id', $uid)->update([ 480: 'lifetime_xp' => max(0, (int) ($xp->lifetime_xp ?? 0) + $delta), 481: 'monthly_xp' => max(0, (int) ($xp->monthly_xp ?? 0) + $delta), 482: 'synced_matches' => (int) ($xp->synced_matches ?? 0) + 1, 483: 'synced_wins' => (int) ($xp->synced_wins ?? 0) + ($won ? 1 : 0), 484: 'synced_losses' => (int) ($xp->synced_losses ?? 0) + ($won ? 0 : 1), 485: 'updated_at' => $now, 486: ]); 487: } else { 488: DB::table('gx_player_experience')->insert([ 489: 'user_id' => $uid, 490: 'lifetime_xp' => max(0, $delta), 491: 'monthly_xp' => max(0, $delta), 492: 'level' => 1, 493: 'synced_matches' => 1, 494: 'synced_wins' => $won ? 1 : 0, 495: 'synced_losses' => $won ? 0 : 1, 496: 'created_at' => $now, 497: 'updated_at' => $now, 498: ]); 499: } 500: } 501: } 502: } 503: 504: $update = ['status' => 'finished']; 505: if (Schema::hasColumn('mix_training_matches', 'ended_at')) $update['ended_at'] = $now; 506: if (Schema::hasColumn('mix_training_matches', 'updated_at')) $update['updated_at'] = $now; 507: 508: DB::table('mix_training_matches')->where('id', $lobbyId)->update($update); 509: }, 3); 510: } catch (\Throwable $e) { === .\app\Http\Controllers\CaptainMatchCloseController.php === 1: userId(); 19: if (!$userId || !$service->isCaptain($matchId, $userId)) { 20: return response()->json(['success' => false, 'message' => 'Somente capitães desta partida podem solicitar o encerramento.'], 403); 21: } 22: 23: if (!Schema::hasTable('mix_match_close_requests')) { 24: return response()->json(['success' => false, 'message' => 'Execute as migrations antes de usar o encerramento por capitães.'], 500); 25: } 26: 27: try { 28: DB::beginTransaction(); 29: 30: $match = DB::table('mix_training_matches') 31: ->where('id', $matchId) 32: ->lockForUpdate() 33: ->first(); 34: 35: if (!$match || strtolower((string) $match->status) !== 'in_progress') { 36: DB::rollBack(); 37: return response()->json(['success' => false, 'message' => 'A partida não está em andamento.'], 422); 38: } 39: 40: $pending = DB::table('mix_match_close_requests') 41: ->where('match_id', $matchId) 42: ->where('status', 'pending') 43: ->lockForUpdate() 44: ->first(); 45: 46: if ($pending) { 47: DB::rollBack(); 48: if ((int) $pending->requested_by === $userId) { 49: return response()->json(['success' => true, 'pending' => true, 'message' => 'Solicitação já enviada. Aguardando o outro capitão.']); 50: } 51: return response()->json(['success' => false, 'message' => 'O outro capitão já solicitou o encerramento. Use CONFIRMAR ENCERRAMENTO.'], 409); 52: } 53: 54: $id = DB::table('mix_match_close_requests')->insertGetId([ 55: 'match_id' => $matchId, 56: 'requested_by' => $userId, 57: 'confirmed_by' => null, 58: 'status' => 'pending', 59: 'requested_at' => now(), 60: 'confirmed_at' => null, 61: 'cancelled_at' => null, 62: 'created_at' => now(), 63: 'updated_at' => now(), 64: ]); 65: 66: DB::commit(); 67: $this->clearStatusCaches($matchId); 68: 69: Log::info('GIGAX CAPTAIN CLOSE solicitado', [ 70: 'match_id' => $matchId, 71: 'request_id' => $id, 72: 'requested_by' => $userId, 73: ]); 74: 75: return response()->json([ 76: 'success' => true, 77: 'pending' => true, 78: 'message' => 'Solicitação enviada. Aguardando confirmação do outro capitão.', 79: ]); 80: } catch (\Throwable $e) { 81: try { DB::rollBack(); } catch (\Throwable $ignored) {} 82: Log::error('GIGAX CAPTAIN CLOSE erro ao solicitar', ['match_id' => $matchId, 'error' => $e->getMessage()]); 83: return response()->json(['success' => false, 'message' => 'Não foi possível solicitar o encerramento.'], 500); 84: } 85: } 86: 87: public function confirmClose(Request $request, int $matchId, CaptainMatchCloseService $service) 88: { 89: $userId = $this->userId(); 90: if (!$userId || !$service->isCaptain($matchId, $userId)) { 91: return response()->json(['success' => false, 'message' => 'Somente o outro capitão pode confirmar o encerramento.'], 403); 92: } 93: 94: try { 95: DB::beginTransaction(); 96: 97: $match = DB::table('mix_training_matches') 98: ->where('id', $matchId) 99: ->lockForUpdate() 100: ->first(); 101: 102: if (!$match || strtolower((string) $match->status) !== 'in_progress') { 103: DB::rollBack(); 104: return response()->json(['success' => false, 'message' => 'A partida não está em andamento.'], 422); 105: } 106: 107: $pending = DB::table('mix_match_close_requests') 108: ->where('match_id', $matchId) 109: ->where('status', 'pending') 110: ->lockForUpdate() 111: ->first(); 112: 113: if (!$pending) { 114: DB::rollBack(); 115: return response()->json(['success' => false, 'message' => 'Não existe solicitação pendente.'], 404); 116: } 117: 118: if ((int) $pending->requested_by === $userId) { 119: DB::rollBack(); 120: return response()->json(['success' => false, 'message' => 'O mesmo capitão não pode solicitar e confirmar.'], 403); 121: } 122: 123: $captainCount = DB::table('lobby_match_captains') 124: ->where('training_match_id', $matchId) 125: ->whereIn('user_id', [(int) $pending->requested_by, $userId]) 126: ->distinct() 127: ->count('user_id'); 128: 129: if ($captainCount < 2) { 130: DB::rollBack(); 131: return response()->json(['success' => false, 'message' => 'A confirmação precisa vir do outro capitão oficial.'], 403); 132: } 133: 134: DB::table('mix_match_close_requests') 135: ->where('id', $pending->id) 136: ->update([ 137: 'confirmed_by' => $userId, 138: 'status' => 'confirmed', 139: 'confirmed_at' => now(), 140: 'updated_at' => now(), 141: ]); 142: 143: $update = [ 144: 'status' => 'cancelled', 145: 'ended_at' => now(), 146: 'updated_at' => now(), 147: ]; 148: if (Schema::hasColumn('mix_training_matches', 'cancel_reason')) { 149: $update['cancel_reason'] = 'captains_agreement'; 150: } 151: if (Schema::hasColumn('mix_training_matches', 'ready_status')) { 152: $update['ready_status'] = 'closed'; 153: } 154: 155: DB::table('mix_training_matches')->where('id', $matchId)->update($update); 156: 157: DB::table('mix_training_participants') 158: ->where('training_match_id', $matchId) 159: ->whereNull('left_at') 160: ->update(['left_at' => now()]); 161: 162: DB::commit(); 163: $this->clearStatusCaches($matchId); 164: 165: $voice = null; 166: try { 167: $voice = app(VoiceMatchService::class)->finishForMatch($matchId); 168: } catch (\Throwable $voiceError) { 169: Log::warning('GIGAX CAPTAIN CLOSE falha ao remover voz', ['match_id' => $matchId, 'error' => $voiceError->getMessage()]); 170: } 171: 172: 173: Log::info('GIGAX CAPTAIN CLOSE confirmado', [ 174: 'match_id' => $matchId, 175: 'requested_by' => (int) $pending->requested_by, 176: 'confirmed_by' => $userId, 177: ]); 178: 179: return response()->json([ 180: 'success' => true, 181: 'closed' => true, 182: 'message' => 'Os dois capitães confirmaram. A partida foi encerrada sem resultado e sem pontuação.', 183: 'voice' => $voice, 184: ]); 185: } catch (\Throwable $e) { 186: try { DB::rollBack(); } catch (\Throwable $ignored) {} 187: Log::error('GIGAX CAPTAIN CLOSE erro ao confirmar', ['match_id' => $matchId, 'error' => $e->getMessage()]); 188: return response()->json(['success' => false, 'message' => 'Não foi possível encerrar a partida.'], 500); 189: } 190: } 191: 192: public function cancelRequest(Request $request, int $matchId, CaptainMatchCloseService $service) 193: { 194: $userId = $this->userId(); 195: if (!$userId || !$service->isCaptain($matchId, $userId)) { 196: return response()->json(['success' => false, 'message' => 'Somente o capitão solicitante pode cancelar.'], 403); 197: } 198: 199: $updated = DB::table('mix_match_close_requests') 200: ->where('match_id', $matchId) 201: ->where('requested_by', $userId) 202: ->where('status', 'pending') 203: ->update([ 204: 'status' => 'cancelled', 205: 'cancelled_at' => now(), 206: 'updated_at' => now(), 207: ]); 208: 209: $this->clearStatusCaches($matchId); 210: 211: return response()->json([ 212: 'success' => (bool) $updated, 213: 'message' => $updated ? 'Solicitação de encerramento cancelada.' : 'Nenhuma solicitação sua estava pendente.', 214: ], $updated ? 200 : 404); 215: } 216: 217: private function userId(): int 218: { 219: return (int) (session('user_id') ?: auth()->id() ?: 0); 220: } 221: 222: private function clearStatusCaches(int $matchId): void 223: { 224: Cache::forget('gigax:veto-status:' . $matchId); 225: Cache::forget('gigax:veto-captains:' . $matchId); 226: Cache::forget('gigax:captain-close:' . $matchId); 227: } 228: } === .\app\Services\CaptainMatchCloseService.php === 1: emptyStatus(); 14: } 15: 16: $match = DB::table('mix_training_matches') 17: ->where('id', $matchId) 18: ->select('id', 'status') 19: ->first(); 20: 21: if (!$match) { 22: return $this->emptyStatus(); 23: } 24: 25: $captains = DB::table('lobby_match_captains as c') 26: ->leftJoin('users as u', 'u.id', '=', 'c.user_id') 27: ->where('c.training_match_id', $matchId) 28: ->orderBy('c.team') 29: ->get(['c.user_id', 'c.team', 'u.nickname']); 30: 31: $me = $captains->first(fn ($c) => (int) $c->user_id === $userId); 32: $other = $me 33: ? $captains->first(fn ($c) => (int) $c->user_id !== $userId) 34: : null; 35: 36: $request = null; 37: if (Schema::hasTable('mix_match_close_requests')) { 38: $request = DB::table('mix_match_close_requests') 39: ->where('match_id', $matchId) 40: ->where('status', 'pending') 41: ->first(); 42: } 43: 44: $isCaptain = $me !== null; 45: $requestedByMe = $request && (int) $request->requested_by === $userId; 46: $requestedByOther = $request && (int) $request->requested_by !== $userId; 47: 48: $requester = null; 49: if ($request) { 50: $requester = $captains->first(fn ($c) => (int) $c->user_id === (int) $request->requested_by); 51: } 52: 53: return [ 54: 'enabled' => true, 55: 'match_active' => strtolower((string) $match->status) === 'in_progress', 56: 'match_status' => (string) $match->status, 57: 'is_captain' => $isCaptain, 58: 'captain_team' => $me ? (int) $me->team : null, 59: 'captain_name' => $me->nickname ?? null, 60: 'other_captain_id' => $other ? (int) $other->user_id : null, 61: 'other_captain_name' => $other->nickname ?? null, 62: 'pending' => (bool) $request, 63: 'request_id' => $request ? (int) $request->id : null, 64: 'requested_by' => $request ? (int) $request->requested_by : null, 65: 'requested_by_name' => $requester->nickname ?? null, 66: 'requested_by_me' => (bool) $requestedByMe, 67: 'requested_by_other' => (bool) $requestedByOther, 68: 'can_request' => $isCaptain && !$request && strtolower((string) $match->status) === 'in_progress', 69: 'can_confirm' => $isCaptain && $requestedByOther && strtolower((string) $match->status) === 'in_progress', 70: 'can_cancel' => $isCaptain && $requestedByMe && strtolower((string) $match->status) === 'in_progress', 71: ]; 72: } 73: 74: public function isCaptain(int $matchId, int $userId): bool 75: { 76: if ($matchId <= 0 || $userId <= 0 || !Schema::hasTable('lobby_match_captains')) { 77: return false; 78: } 79: 80: return DB::table('lobby_match_captains') 81: ->where('training_match_id', $matchId) 82: ->where('user_id', $userId) 83: ->exists(); 84: } 85: 86: private function emptyStatus(): array 87: { 88: return [ 89: 'enabled' => false, 90: 'match_active' => false, 91: 'match_status' => null, 92: 'is_captain' => false, 93: 'captain_team' => null, 94: 'captain_name' => null, 95: 'other_captain_id' => null, 96: 'other_captain_name' => null, 97: 'pending' => false, 98: 'request_id' => null, 99: 'requested_by' => null, 100: 'requested_by_name' => null, 101: 'requested_by_me' => false, 102: 'requested_by_other' => false, 103: 'can_request' => false, 104: 'can_confirm' => false, 105: 'can_cancel' => false, 106: ]; 107: } 108: } === .\app\Services\GigaxGlobalSkillService.php === 1: ['win' => 50, 'loss' => 20], 17: 'draft' => ['win' => 30, 'loss' => 10], 18: 'tournament' => ['win' => 30, 'loss' => 10], 19: 'event' => ['win' => 30, 'loss' => 10], 20: 'other_mode' => ['win' => 18, 'loss' => 5], 21: ]; 22: 23: /** 24: * Return ['credited'=>bool, 'points'=>int, 'balance'=>int]. 25: * $referenceId MUST be a stable persisted match/season ID, never a random value. 26: */ 27: public function awardMatch(int $userId, string $mode, string $outcome, string $referenceId): array 28: { 29: if (!array_key_exists($mode, self::RULES)) { 30: throw new InvalidArgumentException('Invalid Skill mode.'); 31: } 32: if (!in_array($outcome, ['win', 'loss', 'final_champion', 'final_runner_up'], true)) { 33: throw new InvalidArgumentException('Invalid Skill outcome.'); 34: } 35: if (str_starts_with($outcome, 'final_') && !in_array($mode, ['draft', 'tournament', 'event'], true)) { 36: throw new InvalidArgumentException('Final awards only apply to official competitions.'); 37: } 38: $points = match ($outcome) { 39: 'final_champion' => 100, 40: 'final_runner_up' => 50, 41: default => self::RULES[$mode][$outcome], 42: }; 43: // Same source + match ID for normal and final results: finals REPLACE regular awards. 44: return $this->credit($userId, 'match_' . $mode, 'match', $referenceId, $points, [ 45: 'mode' => $mode, 46: 'outcome' => $outcome, 47: ]); 48: } 49: 50: public function awardMonthlyTopTen(int $userId, string $season): array 51: { 52: if (!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $season)) { 53: throw new InvalidArgumentException('Season must be YYYY-MM.'); 54: } 55: // Eligibility MUST be verified by the trusted monthly closing workflow. 56: return $this->credit($userId, 'pug_monthly_top10', 'season', $season, 100, [ 57: 'season' => $season, 58: 'award' => 'top10', 59: ]); 60: } 61: 62: private function credit(int $userId, string $source, string $referenceType, string $referenceId, int $points, array $meta): array 63: { 64: if ($userId <= 0 || $referenceId === '' || strlen($referenceId) > 100 || strlen($source) > 40) { 65: throw new InvalidArgumentException('Invalid credit identifier.'); 66: } 67: return DB::transaction(function () use ($userId, $source, $referenceType, $referenceId, $points, $meta) { 68: // Serializes awards per user, including first profile creation on SQL Server. 69: $user = DB::table('users')->where('id', $userId)->lockForUpdate()->first(['id']); 70: if (!$user) { 71: throw new RuntimeException('User not found.'); 72: } 73: $profile = DB::table('gigax_skill_profiles')->where('user_id', $userId)->lockForUpdate()->first(); 74: if (!$profile) { 75: DB::table('gigax_skill_profiles')->insert([ 76: 'user_id' => $userId, 'skill_rating' => 0, 'skill_tier' => 'OPEN', 77: 'placement_matches' => 0, 'matches_played' => 0, 78: 'wins' => 0, 'losses' => 0, 'created_at' => now(), 'updated_at' => now(), 79: ]); 80: $profile = DB::table('gigax_skill_profiles')->where('user_id', $userId)->lockForUpdate()->first(); 81: } 82: $exists = DB::table('gigax_skill_ledger') 83: ->where('user_id', $userId)->where('source', $source) 84: ->where('reference_type', $referenceType)->where('reference_id', $referenceId) 85: ->exists(); 86: if ($exists) { 87: return ['credited' => false, 'points' => 0, 'balance' => (int) $profile->skill_rating]; 88: } 89: DB::table('gigax_skill_ledger')->insert([ 90: 'user_id' => $userId, 'source' => $source, 91: 'reference_type' => $referenceType, 'reference_id' => $referenceId, 92: 'points' => $points, 'meta' => json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 93: 'created_at' => now(), 'updated_at' => now(), 94: ]); 95: $balance = (int) $profile->skill_rating + $points; 96: DB::table('gigax_skill_profiles')->where('user_id', $userId)->update([ 97: 'skill_rating' => $balance, 'updated_at' => now(), 98: ]); 99: return ['credited' => true, 'points' => $points, 'balance' => $balance]; 100: }, 3); 101: } 102: }