Skip to content

Commit

Permalink
a
Browse files Browse the repository at this point in the history
  • Loading branch information
hu8813 committed Apr 27, 2024
1 parent f7508f2 commit ec05a73
Show file tree
Hide file tree
Showing 11 changed files with 363 additions and 39 deletions.
6 changes: 4 additions & 2 deletions srcs/backend/myapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@ class Meta:
db_table = 'myapp_user_permissions'

class Tournament(models.Model):
name = models.CharField(max_length=100)
start_date = models.DateField()
name = models.CharField(max_length=100, default='pong42')
saved_date = models.DateField(default=timezone.now)
winner = models.CharField(max_length=100, default='')
matches = models.TextField(default='')

class Meta:
db_table = 'tournaments'
Expand Down
83 changes: 82 additions & 1 deletion srcs/backend/myapp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1370,4 +1370,85 @@ def deactivate_2fa(request):
except MyAppUser.DoesNotExist:
return JsonResponse({'error': 'User not found'}, status=404)
else:
return JsonResponse({'error': 'Method not allowed'}, status=405)
return JsonResponse({'error': 'Method not allowed'}, status=405)

def save_tournament_data(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
tournament_data = data.get('tournamentData', [])
tournament_name = data.get('tournamentName')

if not tournament_name:
tournament_name = 'Tournament ' + str(timezone.now().strftime('%Y%m%d%H%M%S'))

tournament, created = Tournament.objects.get_or_create(name=tournament_name)

# Clear the matches field before appending match information
tournament.matches = ''

for game in tournament_data:
match_number = game.get('matchNumber')
players = game.get('players')
result = game.get('result')

match_info = f"{players[0]} - {players[1]}, 🏆 {result}\n" # Use cup emoji for winner
tournament.matches += match_info

if match_number == len(tournament_data):
tournament.winner = result

tournament.save()
return JsonResponse({'message': 'Tournament data saved successfully'})
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
else:
return JsonResponse({'error': 'Only POST method is allowed'}, status=405)

if request.method == 'POST':
try:
data = json.loads(request.body)
tournament_data = data.get('tournamentData', [])
tournament_name = data.get('tournamentName')

if not tournament_name:
tournament_name = 'Tournament ' + str(timezone.now().strftime('%Y%m%d%H%M%S'))

tournament, created = Tournament.objects.get_or_create(name=tournament_name)

for game in tournament_data:
match_number = game.get('matchNumber')
players = game.get('players')
result = game.get('result')

match_info = f"{players[0]} - {players[1]}, {result}\n"
tournament.matches += match_info

if match_number == len(tournament_data):
tournament.winner = result

tournament.save()
return JsonResponse({'message': 'Tournament data saved successfully'})
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
else:
return JsonResponse({'error': 'Only POST method is allowed'}, status=405)

def get_tournament_data(request):
try:
tournaments = Tournament.objects.order_by('-saved_date')[:100]

tournament_data_list = []

for tournament in tournaments:
tournament_data = {
'name': tournament.name,
'saved_date': tournament.saved_date.strftime('%Y-%m-%d'),
'winner': tournament.winner,
'matches': tournament.matches.splitlines()
}
tournament_data_list.append(tournament_data)

return JsonResponse({'tournamentData': tournament_data_list})
except Exception as e:
return JsonResponse({'error': str(e)}, status=401)
3 changes: 2 additions & 1 deletion srcs/backend/myproject/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@
path('api/block-user', views.block_user, name='block_user'),
path('api/unblock-user', views.unblock_user, name='unblock_user'),
path('api/remove-friend', views.remove_friend, name='remove_friend'),

path('api/friends', views.get_friends, name='get_friends'),
path('api/save_tournament_data', views.save_tournament_data, name='save_tournament_data'),
path('api/get_tournament_data', views.get_tournament_data, name='get_tournament_data'),
path('api/fetch_achievements', views.fetch_achievements, name='fetch_achievements'),
path('api/fetch_game_history', views.fetch_game_history, name='fetch_game_history'),
path('api/get-blocked-users/', views.get_blocked_users, name='get_blocked_users'),
Expand Down
1 change: 1 addition & 0 deletions srcs/frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
<script src="./js/tic1.js"></script>
<script src="./js/tic2.js"></script>
<script src="./js/tournament.js"></script>
<script src="./js/AllTournaments.js"></script>
<script src="./js/ViewProfile.js"></script>
<script src="./js/rps.js"></script>
<script src="./js/manage2fa.js"></script>
Expand Down
102 changes: 102 additions & 0 deletions srcs/frontend/js/AllTournaments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
function allTournaments() {
const apiUrl = '/api/get_tournament_data';
const itemsPerPage = 10; // Adjust as needed

let currentPage = 1;
let totalTournaments = 0;

async function fetchTournaments(page) {
try {
const jwtToken = localStorage.getItem('jwtToken');
const csrfToken = await getCSRFCookie();

const response = await fetch(`${apiUrl}?page=${page}&items=${itemsPerPage}`, {
headers: {
'Authorization': `Bearer ${jwtToken}`,
'X-CSRFToken': csrfToken
}
});

if (response.ok) {
const data = await response.json();
return data;
} else {
throw new Error('Failed to fetch tournaments');
}
} catch (error) {
console.error('Error fetching tournaments:', error);
return null;
}
}

async function displayTournaments(page) {
const tournamentList = document.getElementById('tournament-list');
if (tournamentList) {
tournamentList.innerHTML = '';

const data = await fetchTournaments(page);
if (data) {
totalTournaments = data.total;
const tournaments = data.tournaments;

tournaments.forEach(tournament => {
const listItem = document.createElement('li');
listItem.textContent = tournament.name;
listItem.addEventListener('click', () => {
showTournamentDetails(tournament);
});
tournamentList.appendChild(listItem);
});

renderPaginationControls();
}
}
}

function renderPaginationControls() {
const totalPages = Math.ceil(totalTournaments / itemsPerPage);

const paginationContainer = document.getElementById('pagination-container');
paginationContainer.innerHTML = '';

for (let i = 1; i <= totalPages; i++) {
const pageButton = document.createElement('button');
pageButton.textContent = i;
pageButton.addEventListener('click', () => {
currentPage = i;
displayTournaments(currentPage);
});
paginationContainer.appendChild(pageButton);
}
}

async function showTournamentDetails(tournament) {
// Display tournament details on the page
const tournamentDetailsContainer = document.getElementById('tournament-details');
tournamentDetailsContainer.innerHTML = '';

const tournamentName = document.createElement('h2');
tournamentName.textContent = tournament.name;
tournamentDetailsContainer.appendChild(tournamentName);

const savedDate = document.createElement('p');
savedDate.textContent = `Saved Date: ${tournament.saved_date}`;
tournamentDetailsContainer.appendChild(savedDate);

const winner = document.createElement('p');
winner.textContent = `Winner: ${tournament.winner}`;
tournamentDetailsContainer.appendChild(winner);

const matches = document.createElement('ul');
tournament.matches.forEach(match => {
const matchItem = document.createElement('li');
matchItem.textContent = match;
matches.appendChild(matchItem);
});
tournamentDetailsContainer.appendChild(matches);
}

// Initial display
displayTournaments(currentPage);

}
50 changes: 27 additions & 23 deletions srcs/frontend/js/Profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ function displayErrorMessage(message) {
errorMessageElement.style.fontSize = '0.6em';
}
}

async function showGameHistory2() {
window.addEventListener('click', function(event) {
const gameHistoryContainer = document.getElementById('gameHistory');
Expand All @@ -32,30 +31,34 @@ async function showGameHistory2() {
let cls = await translateKey("cls");
const gameHistoryContainer = document.getElementById('gameHistory');
if (gameHistoryContainer){
gameHistoryContainer.style.display = 'flex'; // Change display to flex
gameHistoryContainer.style.display = 'flex';
gameHistoryContainer.innerHTML = '<button id="closeGameHistoryBtn" class="close-button" onclick="closeGameHistory2()">'+cls+'</button>';
}
// Sort game history by date_time_played in descending order
gameHistoryData.sort((a, b) => new Date(b.date_time_played) - new Date(a.date_time_played));

let op = await translateKey("op");
let gm = await translateKey("gm");
let dt = await translateKey("dt");
let res = await translateKey("res");

gameHistoryData.forEach(game => {
const gameElement = document.createElement('div');
gameElement.classList.add('game-item', 'mb-3', 'border', 'border-primary', 'rounded', 'p-3');
gameElement.innerHTML = `
<div><strong>`+op+`:</strong> ${game.opponent || 'cpu'}</div>
<div><strong>`+gm+`:</strong> ${game.game_type}</div>
<div><strong>`+dt+`:</strong> ${game.date_time_played}</div>
<div><strong>`+res+`:</strong>
${game.tournaments_won ? '<i class="bi bi-trophy-fill text-success fs-5"></i>' : '<i class="bi bi-emoji-frown-fill text-danger fs-5"></i>'}
</div>
`;
gameHistoryContainer.appendChild(gameElement);
});
if (gameHistoryData.length === 0) {
let emptyGameHistory = await translateKey("emptyGameHistory");
gameHistoryContainer.innerHTML += `<div class="mb-3"><br/> `+ emptyGameHistory +` </div>`;
} else {
gameHistoryData.sort((a, b) => new Date(b.date_time_played) - new Date(a.date_time_played));

let op = await translateKey("op");
let gm = await translateKey("gm");
let dt = await translateKey("dt");
let res = await translateKey("res");

gameHistoryData.forEach(game => {
const gameElement = document.createElement('div');
gameElement.classList.add('game-item', 'mb-3', 'border', 'border-primary', 'rounded', 'p-3');
gameElement.innerHTML = `
<div><strong>`+op+`:</strong> ${game.opponent || 'cpu'}</div>
<div><strong>`+gm+`:</strong> ${game.game_type}</div>
<div><strong>`+dt+`:</strong> ${game.date_time_played}</div>
<div><strong>`+res+`:</strong>
${game.tournaments_won ? '<i class="bi bi-trophy-fill text-success fs-5"></i>' : '<i class="bi bi-emoji-frown-fill text-danger fs-5"></i>'}
</div>
`;
gameHistoryContainer.appendChild(gameElement);
});
}
} else {
throw new Error('Failed to fetch game history');
}
Expand All @@ -65,6 +68,7 @@ async function showGameHistory2() {
}
}


function isLocalDeployment() {
return window.location.href.includes("pong42");
}
Expand Down
7 changes: 6 additions & 1 deletion srcs/frontend/js/ViewProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async function fetchAndDisplayViewProfile(username) {
document.getElementById('nicknameadr2').textContent = nickname;
document.getElementById('scoreadr').textContent = score;
document.getElementById('gamesPlayed').textContent = gamesPlayed;
document.getElementById('winningRate').textContent = winningRate;
document.getElementById('winningRate').textContent = winningRate + '%';

const statusIndicator = document.getElementById('statusIndicator');
statusIndicator.classList.toggle('online', isOnline);
Expand Down Expand Up @@ -74,6 +74,10 @@ async function fetchAndDisplayViewProfile(username) {
gameHistoryContainer.innerHTML = '<button id="closeGameHistoryBtn" class="close-button" onclick="closeGameHistory()">'+cls+'</button>';
}
// Sort game history by date_time_played in descending order
if (gameHistoryData.length === 0) {
let emptyGameHistory = await translateKey("emptyGameHistory");
gameHistoryContainer.innerHTML += `<div class="mb-3"><br/> `+ emptyGameHistory +` </div>`;
} else {
gameHistoryData.sort((a, b) => new Date(b.date_time_played) - new Date(a.date_time_played));

let op = await translateKey("op");
Expand All @@ -94,6 +98,7 @@ async function fetchAndDisplayViewProfile(username) {
`;
gameHistoryContainer.appendChild(gameElement);
});
}
} else {
throw new Error('Failed to fetch game history');
}
Expand Down
11 changes: 8 additions & 3 deletions srcs/frontend/js/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const routes = {
"#tic1": "/views/tic1.html",
"#tic2": "/views/tic2.html",
"#tournament": "/views/tournament.html",
"#tournaments": "/views/alltournaments.html",
"#viewprofile": "/views/viewprofile.html",
"#rps" : "/views/rps.html",
"#chatselect" : "/views/chatselect.html",
Expand Down Expand Up @@ -351,10 +352,14 @@ const handleLocation = async () => {
case '#tic2':
showTic2();
break;
case '#tournaments':
allTournaments();
break;
case '#tournament':
const tournamentHtml = await fetch(routes[path]).then((data) => data.text());
document.getElementById("app").innerHTML = tournamentHtml;
askPlayerCount();
// const tournamentHtml = await fetch(routes[path]).then((data) => data.text());
// document.getElementById("app").innerHTML = tournamentHtml;
// askPlayerCount();
showTournamentPage();
break;
case '#contact':
showImprint();
Expand Down
Loading

0 comments on commit ec05a73

Please sign in to comment.