diff --git a/tournaments/urls.py b/tournaments/urls.py index 85fbf48..9af3aa2 100644 --- a/tournaments/urls.py +++ b/tournaments/urls.py @@ -55,6 +55,7 @@ urlpatterns = [ path('login/', CustomLoginView.as_view(), name='custom-login'), path('custom_password_change/', views.custom_password_change, name='custom_password_change'), path('logout/', views.custom_logout, name='custom_logout'), + path('/utils/xls-to-csv/', views.xls_to_csv, name='xls-to-csv'), path('signup/', views.signup, name='signup'), # URL pattern for signup # path('profile/', views.profile, name='profile'), # URL pattern for signup path('my-tournaments/', views.my_tournaments, name='my-tournaments'), # URL pattern for signup diff --git a/tournaments/views.py b/tournaments/views.py index 27c1d65..7505abf 100644 --- a/tournaments/views.py +++ b/tournaments/views.py @@ -27,6 +27,10 @@ import time import json import asyncio import zipfile +import pandas as pd +from tournaments.utils.extensions import create_random_filename +from django.core.files.storage import default_storage +from django.core.files.base import ContentFile from api.tokens import account_activation_token @@ -1516,6 +1520,47 @@ def confirm_call(request, tournament_id): return redirect('tournament-info', tournament_id=tournament_id) +def xls_to_csv(request): + # Check if the request has a file + if 'file' in request.FILES: + uploaded_file = request.FILES['file'] + + # Save the uploaded file + directory = 'tmp/csv/' + file_path = os.path.join(directory, uploaded_file.name) + file_name = default_storage.save(file_path, ContentFile(uploaded_file.read())) + + # Check available sheets and look for 'inscriptions' + xls = pd.ExcelFile(file_name) + sheet_names = xls.sheet_names + + # Determine which sheet to use + target_sheet = 0 # Default to first sheet + if 'inscriptions' in [name.lower() for name in sheet_names]: + for i, name in enumerate(sheet_names): + if name.lower() == 'inscriptions': + target_sheet = i # or use the name directly: target_sheet = name + break + + # Convert to csv and save + data_xls = pd.read_excel(file_name, sheet_name=target_sheet, index_col=None) + csv_file_name = create_random_filename('players', 'csv') + output_path = os.path.join(directory, csv_file_name) + data_xls.to_csv(output_path, sep=';', index=False, encoding='utf-8') + + # Send the processed file back + with default_storage.open(output_path, 'rb') as file: + response = HttpResponse(file.read(), content_type='application/octet-stream') + response['Content-Disposition'] = f'attachment; filename="players.csv"' + + # Clean up: delete both files + default_storage.delete(file_path) + default_storage.delete(output_path) + + return response + else: + return HttpResponse("No file was uploaded", status=400) + class UserListExportView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): users = CustomUser.objects.order_by('date_joined')