diff --git a/myproject/myapp/UserTokenModel.py b/myproject/myapp/UserTokenModel.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/myproject/myapp/decorators.py b/myproject/myapp/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9bbce1e71234f622f03b3dcaded06039b53c73 --- /dev/null +++ b/myproject/myapp/decorators.py @@ -0,0 +1,48 @@ +# decorators.py +from django.contrib.auth.decorators import user_passes_test +from django.utils.decorators import method_decorator +from django.contrib import messages +from django.shortcuts import redirect + +def user_type_required(user_type): + def decorator(view_func): + def wrap(request, *args, **kwargs): + if request.user.is_superuser or request.user.profile.user_type == user_type: + return view_func(request, *args, **kwargs) + else: + messages.error(request, 'You do not have permission to access this page.') + return redirect('index') + return wrap + return decorator + +admin_required = user_type_required(1) +ml_engineer_required = user_type_required(2) +accountant_required = user_type_required(3) + + +def login_required(view_func): + def wrap(request, *args, **kwargs): + if request.user.is_authenticated: + return view_func(request, *args, **kwargs) + else: + messages.error(request, 'You must be logged in to access this page.') + return redirect('login') + return wrap + +def admin_accountant_required(view_func): + def wrap(request, *args, **kwargs): + if request.user.is_superuser or request.user.profile.user_type in [1, 3]: + return view_func(request, *args, **kwargs) + else: + messages.error(request, 'You do not have permission to access this page.') + return redirect('index') + return wrap + +def admin_ml_engineer_required(view_func): + def wrap(request, *args, **kwargs): + if request.user.is_superuser or request.user.profile.user_type in [1, 2]: + return view_func(request, *args, **kwargs) + else: + messages.error(request, 'You do not have permission to access this page.') + return redirect('index') + return wrap \ No newline at end of file diff --git a/myproject/myapp/payments.py b/myproject/myapp/payments.py index b1108fd9e985622974b0b69dfa042f426da12ac8..532f38054936cdfdc96e8a6c0e731b5bb92a84dd 100644 --- a/myproject/myapp/payments.py +++ b/myproject/myapp/payments.py @@ -136,7 +136,7 @@ def execute_payment(request): if not payment_id or not payer_id: print("no payment id or payer_id") return Response({"error": "Error: No payment id or payer id was found."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - + # configure API paypalrestsdk.configure({ "mode": settings.PAYPAL_MODE, @@ -154,16 +154,19 @@ def execute_payment(request): # Allocate some tokens tokens_purchased = request.session.get("purchase_quantity") - add_tokens(request.user, tokens_purchased) - # log_data = { - # 'action': 'Tokens purchased', - # } + # Save payment details to the database + Payment.objects.create( + user=request.user, + amount=payment.transactions[0].amount.total, + payment_id=payment_id, + payer_id=payer_id + ) + log_data = get_log_data(request.user, Action.PAYMENT_SUCCESSFUL, 'success', description=f"Purchased {tokens_purchased} tokens") create_log(request.user if request.user.is_authenticated else None, log_data) - return redirect('success') else: print("exiting at the end of execute_payment(), incorrect payer id") diff --git a/myproject/myapp/pdf_generation.py b/myproject/myapp/pdf_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..cf552f5d44d16f601299547369c4358e4a9365ee --- /dev/null +++ b/myproject/myapp/pdf_generation.py @@ -0,0 +1,80 @@ +# pdf_generation.py +from io import BytesIO +from datetime import datetime +from reportlab.pdfgen import canvas +from reportlab.lib.pagesizes import letter +from reportlab.lib import colors +from reportlab.platypus import Table, TableStyle +from django.shortcuts import redirect +from django.http import HttpResponse +from django.contrib import messages +from django.contrib.auth.decorators import user_passes_test +from .models import Payment +from .decorators import admin_accountant_required, login_required, ml_engineer_required, admin_required, accountant_required +from reportlab.lib.units import inch + + +@login_required +@admin_accountant_required +def generate_financial_statement(request): + if request.method == 'POST': + start_date = request.POST.get('startDate') + end_date = request.POST.get('endDate') + + if start_date and end_date: + start_date = datetime.strptime(start_date, '%Y-%m-%d') + end_date = datetime.strptime(end_date, '%Y-%m-%d') + + payments = Payment.objects.filter(date__range=[start_date, end_date]) + + # Generate PDF + buffer = BytesIO() + p = canvas.Canvas(buffer, pagesize=letter) + + # Add title + p.setFont("Helvetica-Bold", 16) + p.drawString(inch, 10.5 * inch, f"Financial Statement from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}") + + # Add payment details table + data = [['User', 'Amount', 'Date']] + total_amount = 0 + for payment in payments: + data.append([payment.user.username, f"£{payment.amount}", payment.date.strftime('%Y-%m-%d')]) + total_amount += payment.amount + + table = Table(data) + table.setStyle(TableStyle([ + ('BACKGROUND', (0, 0), (-1, 0), colors.grey), + ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), + ('ALIGN', (0, 0), (-1, -1), 'CENTER'), + ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), + ('FONTSIZE', (0, 0), (-1, 0), 14), + ('BOTTOMPADDING', (0, 0), (-1, 0), 12), + ('BACKGROUND', (0, 1), (-1, -1), colors.beige), + ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), + ('ALIGN', (0, 1), (-1, -1), 'LEFT'), + ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), + ('FONTSIZE', (0, 1), (-1, -1), 12), + ('TOPPADDING', (0, 1), (-1, -1), 6), + ('BOTTOMPADDING', (0, 1), (-1, -1), 6), + ('GRID', (0, 0), (-1, -1), 1, colors.black), + ])) + # Adjust the y-coordinate where the table is drawn + table.wrapOn(p, inch, 8.5 * inch) + table.drawOn(p, inch, 8.5 * inch) + + # Add total amount + p.setFont("Helvetica-Bold", 14) + p.drawString(inch, 8 * inch, f"Total Amount: ${total_amount}") + + p.showPage() + p.save() + + # File response + buffer.seek(0) + return HttpResponse(buffer, content_type='application/pdf') + else: + messages.error(request, 'Please select both start and end dates.') + + return redirect('users') + diff --git a/myproject/myapp/receipts.py b/myproject/myapp/receipts.py deleted file mode 100644 index 1194d56808eb17a228a1095f00a7350ee0a8d5fc..0000000000000000000000000000000000000000 --- a/myproject/myapp/receipts.py +++ /dev/null @@ -1,8 +0,0 @@ -# We want to generate receipts for user monthly billing. -# We want the function to accept a user -# It should return the user's username, blanked out details and cost -from fpdf import FPDF - -class PDF(FPDF): - pass # do nothing when it's executed - diff --git a/myproject/myapp/templates/model_selection.html b/myproject/myapp/templates/model_selection.html index d14c882f552a27e1260ecb0641f247918004229b..947f19bb98665beec5a9b233552488dad09b011e 100644 --- a/myproject/myapp/templates/model_selection.html +++ b/myproject/myapp/templates/model_selection.html @@ -2,7 +2,7 @@ {% block content %} <h1>Model Version Selection</h1> - <form method="post"> + <form action="{% url 'model_selection' %}" method="post"> {% csrf_token %} <label for="model_version">Select Model Version:</label> <select name="model_version" id="model_version"> @@ -10,6 +10,6 @@ <option value="{{ version }}" {% if selected_model_version == version %}selected{% endif %}>{{ version }}</option> {% endfor %} </select> - <button type="submit">Save</button> + <button type="submit" class="p-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">Save</button> </form> {% endblock %} \ No newline at end of file diff --git a/myproject/myapp/templates/payment_success.html b/myproject/myapp/templates/payment_success.html index 51a411039e2529af3f8d003f8490d8531ffcc352..b9384178e07af4b160609802dffbafd4f71802eb 100644 --- a/myproject/myapp/templates/payment_success.html +++ b/myproject/myapp/templates/payment_success.html @@ -9,6 +9,4 @@ </div> </div> - - {% endblock content%} diff --git a/myproject/myapp/templates/user_page.html b/myproject/myapp/templates/user_page.html index 987c029969c603ccae4006aaed7ba29cd5c26af4..ad63561e9a22dbab427f1d2dcad4e476014a8b9e 100644 --- a/myproject/myapp/templates/user_page.html +++ b/myproject/myapp/templates/user_page.html @@ -43,59 +43,26 @@ </div> {% endif %} - {% if user_profile.user_type == 3 or user.is_superuser or user_profile.user_type == 1%} - <div - class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800" - > - - <h3 class="mb-4 text-xl font-semibold dark:text-white"> - Generate Financial Statement - </h3> - <form - action="/generate-statement" - method="post" - class="flex flex-col space-y-4" - > - <div class="flex flex-col"> - <label - for="startDate" - class="text-sm font-medium text-gray-600 dark:text-gray-300" - >From Date</label - > - <input - type="date" - id="startDate" - name="startDate" - class="p-2 border rounded-md" - required - /> - </div> - <div class="flex flex-col"> - <label - for="endDate" - class="text-sm font-medium text-gray-600 dark:text-gray-300" - >To Date</label - > - <input - type="date" - id="endDate" - name="endDate" - class="p-2 border rounded-md" - required - /> - </div> - <a href="{% url 'generate_pdf' %}" - <button - type="submit" - class="p-2 bg-blue-500 text-white rounded-md hover:bg-blue-600" - > - Download Financial Statement - </button> - </a> - </form> - {% comment %} REPLACE WITH LOGIC TO CHECK PROPER USER {% endcomment %} + {% if user_profile.user_type == 3 or user.is_superuser or user_profile.user_type == 1 %} + <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800"> + <h3 class="mb-4 text-xl font-semibold dark:text-white">Generate Financial Statement</h3> + <form action="{% url 'generate_financial_statement' %}" method="post" class="flex flex-col space-y-4"> + {% csrf_token %} + <div class="flex flex-col"> + <label for="startDate" class="text-sm font-medium text-gray-600 dark:text-gray-300">From Date</label> + <input type="date" id="startDate" name="startDate" class="p-2 border rounded-md" required /> + </div> + <div class="flex flex-col"> + <label for="endDate" class="text-sm font-medium text-gray-600 dark:text-gray-300">To Date</label> + <input type="date" id="endDate" name="endDate" class="p-2 border rounded-md" required /> + </div> + <button type="submit" class="p-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"> + Download Financial Statement + </button> + </form> </div> {% endif %} + {% if user_profile.user_type == 2 or user.is_superuser or user_profile.user_type == 1%} <div @@ -139,7 +106,7 @@ {% if user_profile.user_type == 2 or user.is_superuser %} <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800"> <h3 class="mb-4 text-xl font-semibold dark:text-white">Model Performance</h3> - <a href="{% url 'model_performance' %}" class="text-blue-500 hover:underline">View Model Performance</a> + <button class="p-2 bg-green-500 text-white rounded-md hover:bg-green-600"><a href="{% url 'model_performance' %}" class="hover:underline">View Model Performance</a></button> </div> {% endif %} <div diff --git a/myproject/myapp/urls.py b/myproject/myapp/urls.py index a7c38d019e636e988f655430977fb3a3eca36243..8a834a421dd905c9a3afc5fba1b53866b03fd7d6 100644 --- a/myproject/myapp/urls.py +++ b/myproject/myapp/urls.py @@ -1,13 +1,20 @@ from django.urls import path -from .views import InstrumentDetectionView, ModelPerformanceView, ModelSelectionView, index, log_fileupload, users, maintenance, \ -handler404, handler500, terms_conditions, privacy_policy, pricing, generate_pdf, admin_table,\ - change_user_type, submit_feedback + +from .views import InstrumentDetectionView, ModelPerformanceView, ModelSelectionView, index, maintenance, handler404, handler500, \ + terms_conditions, privacy_policy, pricing, submit_feedback + +from .pdf_generation import generate_financial_statement + +from .user_views import admin_table, change_user_type, users + +from .utils import log_fileupload + from .payments import create_payment, execute_payment, payment_cancelled, payment_success from django.contrib.auth import views as auth_views # Authentication from .views import RegisterView, CustomLoginView -from django.contrib.auth.views import LoginView, LogoutView +from django.contrib.auth.views import LogoutView urlpatterns = [ path('', index, name='index'), @@ -21,9 +28,7 @@ urlpatterns = [ path('pricay_policy/', privacy_policy, name='privacy_policy'), path('pricing/', pricing, name='pricing'), path('submit_feedback/', submit_feedback, name='submit_feedback'), - path('generate_pdf/', generate_pdf, name='generate_pdf'), path('pricing/', pricing, name='pricing'), - path('generate_pdf/', generate_pdf, name='generate_pdf'), path('instrument_detection/', InstrumentDetectionView.as_view(), name='instrument_detection'), path('model_performance/', ModelPerformanceView.as_view(), name='model_performance'), path('model_selection/', ModelSelectionView.as_view(), name='model_selection'), @@ -46,6 +51,8 @@ urlpatterns = [ path('payment/create/<str:purchase_type>', create_payment, name='create_payment'), path('payment/execute/', execute_payment, name='execute_payment'), path('payment/cancel/', payment_cancelled, name='payment_cancelled'), - path('payment_success/', payment_success, name='success') + path('payment_success/', payment_success, name='success'), + path('generate_statement/', generate_financial_statement, name='generate_financial_statement') + ] diff --git a/myproject/myapp/user_views.py b/myproject/myapp/user_views.py new file mode 100644 index 0000000000000000000000000000000000000000..40d179ec262f9125a8b70e5aaa04394bfdeb8d76 --- /dev/null +++ b/myproject/myapp/user_views.py @@ -0,0 +1,101 @@ +# user_views.py +from django.shortcuts import render, redirect, get_object_or_404 +from django.http import JsonResponse +from django.db import connection +from django.contrib import messages +from .models import Profile, UserTokenCount +import json + +from .decorators import admin_required, ml_engineer_required, accountant_required, login_required, admin_accountant_required, \ + admin_ml_engineer_required + +@login_required +@admin_ml_engineer_required +def admin_table(request): + + query = """SELECT date, log, user_id, feedback FROM myapp_log ORDER BY date DESC""" + with connection.cursor() as cursor: + cursor.execute(query) + rows = cursor.fetchall() + + # Create a list of dictionaries from the query results + data = [] + for row in rows: + # Parse the JSON string into a dictionary + log = json.loads(row[1]) + # Get the user object based on the user_id + user_id = row[2] + # Get the feedback value + feedback = row[3] + # Create a dictionary with the date, user, JSON fields, and feedback + date = row[0].strftime('%Y-%m-%d %H:%M:%S') + entry = {'date': date, 'user': user_id, 'file': log['file'], 'action': log['action'], 'status': log['status'], + 'description': log['description'], 'feedback': feedback} + data.append(entry) + + # Return the data as a JSON response + return JsonResponse({'data': data}, safe=False) + +@login_required +def user_table(request): + user_id = request.user.id + # Only display user logs code below + query = """SELECT date, log, user_id, feedback FROM myapp_log WHERE user_id = {} ORDER BY date DESC""".format(user_id) + with connection.cursor() as cursor: + cursor.execute(query) + rows = cursor.fetchall() + + # Create a list of dictionaries from the query results + data = [] + for row in rows: + # Parse the JSON string into a dictionary + log = json.loads(row[1]) + # Get the user object based on the user_id + user_id = row[2] + # Get the feedback value + feedback = row[3] + # Create a dictionary with the date, user, JSON fields, and feedback + date = row[0].strftime('%Y-%m-%d %H:%M:%S') + entry = {'date': date, 'user': user_id, 'file': log['file'], 'action': log['action'], 'status': log['status'], + 'description': log['description'], 'feedback': feedback} + data.append(entry) + + # Return the data as a JSON response + return JsonResponse({'data': data}, safe=False) + + +@login_required +def users(request): + # Make a request to the admin_table view to get the data + context = {} + data_user = user_table(request) + user_dict = json.loads(data_user.content) + token_count = UserTokenCount.objects.get(user=request.user).token_count + user_profile = request.user.profile + user = request.user + all_user_profiles = Profile.objects.all() # Retrieve all Profile objects + + # Pass the data as a context variable to the template + # !!! ADMIN DATA ONLY DISPLAYED AND GET IF USER IS ADMIN !!! + if request.user.profile.user_type == 1 or request.user.is_superuser or request.user.profile.user_type == 2: + data_admin = admin_table(request) + admin_dict = json.loads(data_admin.content) + context['admin_data'] = admin_dict['data'] + + context['user_data'] = user_dict['data'] + context['token_count'] = token_count + context['user_profile'] = user_profile + context['user'] = user + context['all_user_profiles'] = all_user_profiles # Add all_user_profiles to the context + + return render(request, 'user_page.html', context) + +@login_required +@admin_required +def change_user_type(request, user_id): + if request.method == 'POST': + user_type = request.POST.get('user_type') + user_profile = get_object_or_404(Profile, user__id=user_id) # Get the user profile + user_profile.user_type = user_type + user_profile.save() + return redirect('users') # Redirect to the users page \ No newline at end of file diff --git a/myproject/myapp/utils.py b/myproject/myapp/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2d07dfab17f4acac4ca6e81e3aaed9162e7fc1a2 --- /dev/null +++ b/myproject/myapp/utils.py @@ -0,0 +1,39 @@ +# utils.py +from .models import Log +from django.http import JsonResponse +from django.views.decorators.csrf import csrf_exempt +from .models import Action +import json + +def get_log_data(user, action, status='success', file=None, description=None, feedback=None): + log_data = { + 'username': user.username, + 'action': action.value.format(username=user.username), + 'status': status, + 'file': file, + 'description': description, + 'feedback': feedback, # Add the feedback field + } + return log_data + +def create_log(user, log_data): + Log.objects.create(user=user, log=log_data, feedback=log_data.get('feedback')) + +def user_has_credits(): + has_credits = False + return has_credits + +@csrf_exempt +def log_fileupload(request): + if request.method == 'POST': + data = json.loads(request.body) + status = data.get('status') + file = data.get('file') + + if request.user.is_authenticated: + log_data = get_log_data(request.user, Action.UPLOAD_FILE, status, file) + create_log(request.user, log_data) + + return JsonResponse({'message': 'Log created successfully'}, status=201) + + return JsonResponse({'error': 'Invalid request'}, status=400) diff --git a/myproject/myapp/views.py b/myproject/myapp/views.py index e65ac6c9f5be9c7e24b166b5748322c5aaa0721a..9ab774115d4bb24b70fefbe458ecff029311a546 100644 --- a/myproject/myapp/views.py +++ b/myproject/myapp/views.py @@ -1,22 +1,13 @@ # views.py import os -from django.contrib.auth import authenticate, login, logout -from django.contrib.auth.forms import UserCreationForm -from django.contrib.auth.models import User +from django.contrib.auth import login from django.contrib import messages -from django.http import HttpResponse -from django.utils import timezone -from django.shortcuts import render, redirect, get_object_or_404 -from django.template import RequestContext +from django.shortcuts import render, redirect import logging -from reportlab.pdfgen import canvas import json -from datetime import datetime from .forms import InstrumentDetectionForm -from .models import Log, Action, User, UserTokenCount, Profile, ModelConfig, ModelPerformanceMetrics -from django.http import JsonResponse -from django.db import connection +from .models import Action, UserTokenCount, Profile, ModelConfig, ModelPerformanceMetrics # Django Rest Framework imports from rest_framework.views import APIView @@ -32,80 +23,36 @@ from django.views import View, generic from .models import Profile, ModelConfig from .forms import UserRegisterForm, LoginAuthenticationForm from django.contrib.auth.views import LoginView -from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.mixins import UserPassesTestMixin from django.views.generic import TemplateView -import re - -logger = logging.getLogger(__name__) -def get_log_data(user, action, status='success', file=None, description=None, feedback=None): - log_data = { - 'username': user.username, - 'action': action.value.format(username=user.username), - 'status': status, - 'file': file, - 'description': description, - 'feedback': feedback, # Add the feedback field - } - return log_data - -def create_log(user, log_data): - Log.objects.create(user=user, log=log_data, feedback=log_data.get('feedback')) - -@csrf_exempt -def log_fileupload(request): - if request.method == 'POST': - data = json.loads(request.body) - status = data.get('status') - file = data.get('file') - - if request.user.is_authenticated: - log_data = get_log_data(request.user, Action.UPLOAD_FILE, status, file) - create_log(request.user, log_data) +import re - return JsonResponse({'message': 'Log created successfully'}, status=201) +from .utils import get_log_data, create_log - return JsonResponse({'error': 'Invalid request'}, status=400) +logger = logging.getLogger(__name__) -def submit_feedback(request): - if request.method == 'POST' and request.user.is_authenticated: - prediction = request.POST.get('prediction') - liked = request.POST.get('feedback') == 'true' - file_name = request.POST.get('file_name') # Get the filename from the form data - - # Create log data using the get_log_data function - log_data = get_log_data( - user=request.user, - action=Action.FEEDBACK_SUBMITTED, - status='success', - file=file_name, # Use the filename obtained from the form - description=prediction, - feedback=liked - ) - - # Create the Log entry using the create_log function - create_log(request.user, log_data) - - return redirect('index') - - return redirect('index') +def handler404(request, *args, **kwargs): + response = render(request, '404.html', {}) + response.status_code = 404 + return response -@csrf_exempt -def log_fileupload(request): - if request.method == 'POST': - data = json.loads(request.body) - status = data.get('status') - file = data.get('file') +def handler500(request, *args, **kwargs): + response = render(request, '500.html', {}) + response.status_code = 500 + return response - if request.user.is_authenticated: - log_data = get_log_data(request.user, Action.UPLOAD_FILE, status, file) - create_log(request.user, log_data) +def maintenance(request): + return render(request, 'maintenance.html') +def terms_conditions(request): + return render(request, 'terms_conditions.html') - return JsonResponse({'message': 'Log created successfully'}, status=201) +def privacy_policy(request): + return render(request, 'privacy_policy.html') - return JsonResponse({'error': 'Invalid request'}, status=400) +def pricing(request): + return render(request, 'pricing.html') def submit_feedback(request): if request.method == 'POST' and request.user.is_authenticated: @@ -127,70 +74,10 @@ def submit_feedback(request): create_log(request.user, log_data) return redirect('index') - - return redirect('index') - -def admin_table(request): - if request.user.is_authenticated: - if request.user.profile.user_type != 0 or request.user.is_superuser: - # Execute the query and fetch all rows - query = """SELECT date, log, user_id, feedback FROM myapp_log ORDER BY date DESC""" - with connection.cursor() as cursor: - cursor.execute(query) - rows = cursor.fetchall() - - # Create a list of dictionaries from the query results - data = [] - for row in rows: - # Parse the JSON string into a dictionary - log = json.loads(row[1]) - # Get the user object based on the user_id - user_id = row[2] - # Get the feedback value - feedback = row[3] - # Create a dictionary with the date, user, JSON fields, and feedback - date = row[0].strftime('%Y-%m-%d %H:%M:%S') - entry = {'date': date, 'user': user_id, 'file': log['file'], 'action': log['action'], 'status': log['status'], - 'description': log['description'], 'feedback': feedback} - data.append(entry) - - # Return the data as a JSON response - return JsonResponse({'data': data}, safe=False) - else: - messages.info(request, 'Must be logged in as a non-basic user to access this page.') - return redirect('index') - else: - messages.info(request, 'Must be logged in as a non-basic user to access this page.') - return redirect('login') -def user_table(request): - if request.user.is_authenticated: - user_id = request.user.id - # Only display user logs code below - query = """SELECT date, log, user_id, feedback FROM myapp_log WHERE user_id = {} ORDER BY date DESC""".format(user_id) - with connection.cursor() as cursor: - cursor.execute(query) - rows = cursor.fetchall() - - # Create a list of dictionaries from the query results - data = [] - for row in rows: - # Parse the JSON string into a dictionary - log = json.loads(row[1]) - # Get the user object based on the user_id - user_id = row[2] - # Get the feedback value - feedback = row[3] - # Create a dictionary with the date, user, JSON fields, and feedback - date = row[0].strftime('%Y-%m-%d %H:%M:%S') - entry = {'date': date, 'user': user_id, 'file': log['file'], 'action': log['action'], 'status': log['status'], - 'description': log['description'], 'feedback': feedback} - data.append(entry) - - # Return the data as a JSON response - return JsonResponse({'data': data}, safe=False) else: - messages.info(request, 'Must be logged in as a user to access this page.') - return redirect('login') + messages.error(request, 'Invalid request') + return redirect('index') + def index(request): # Initialize default context @@ -239,52 +126,6 @@ def index(request): - - -def users(request): - if request.user.is_authenticated: - # Make a request to the admin_table view to get the data - context = {} - data_user = user_table(request) - user_dict = json.loads(data_user.content) - token_count = UserTokenCount.objects.get(user=request.user).token_count - user_profile = request.user.profile - user = request.user - all_user_profiles = Profile.objects.all() # Retrieve all Profile objects - - # Pass the data as a context variable to the template - # !!! ADMIN DATA ONLY DISPLAYED AND GET IF USER IS ADMIN !!! - if request.user.profile.user_type != 0 or request.user.is_superuser: - data_admin = admin_table(request) - admin_dict = json.loads(data_admin.content) - context['admin_data'] = admin_dict['data'] - - - context['user_data'] = user_dict['data'] - context['token_count'] = token_count - context['user_profile'] = user_profile - context['user'] = user - context['all_user_profiles'] = all_user_profiles # Add all_user_profiles to the context - - return render(request, 'user_page.html', context) - else: - messages.info(request, 'Must be logged in as a user to access this page.') - return redirect('login') - -def handler404(request, *args, **kwargs): - response = render(request, '404.html', {}) - response.status_code = 404 - return response - -def handler500(request, *args, **kwargs): - response = render(request, '500.html', {}) - response.status_code = 500 - return response - -def maintenance(request): - return render(request, 'maintenance.html') - - # Authentication class RegisterView(generic.CreateView): form_class = UserRegisterForm @@ -337,38 +178,22 @@ class CustomLoginView(LoginView): -def terms_conditions(request): - return render(request, 'terms_conditions.html') - -def privacy_policy(request): - return render(request, 'privacy_policy.html') - -def pricing(request): - return render(request, 'pricing.html') - -#For testing the receipts ONLY. TODO: delete when working -def generate_pdf(request): - response = HttpResponse(content_type='application/pdf') - response['Content-Disposition'] = 'attachment; filename="example.pdf"' - - p = canvas.Canvas(response) - p.drawString(100, 800, "Hello, this is a PDF!") - p.showPage() - p.save() - - return response - -# Running the audio file through the model +# Model Views class InstrumentDetectionView(APIView): def dispatch(self, request, *args, **kwargs): - user_token_count = UserTokenCount.objects.get(user=request.user) if request.user.is_anonymous: messages.info(request, 'Must be logged in as a user to access this page.') return redirect('login') - elif user_token_count.token_count < 1: + else: + user_token_count = UserTokenCount.objects.get(user=request.user) + if user_token_count.token_count < 1: messages.info(request, 'You do not have enough tokens to make a prediction.') return redirect('pricing') + # Add a check for the existence of files in the request.FILES dictionary + elif 'audio_file' not in request.FILES: + messages.info(request, 'No audio file was uploaded.') + return redirect('index') else: return super().dispatch(request, *args, **kwargs) def post(self, request): @@ -535,18 +360,9 @@ class ModelSelectionView(UserPassesTestMixin, View): model_config = ModelConfig.load() model_config.selected_model_version = selected_model_version model_config.save() - return redirect('model_selection') + messages.success(request, f'Selected model version: {selected_model_version}') + return redirect('users') -def change_user_type(request, user_id): - if request.method == 'POST': - user_type = request.POST.get('user_type') - user_profile = get_object_or_404(Profile, user__id=user_id) # Get the user profile - user_profile.user_type = user_type - user_profile.save() - return redirect('users') # Redirect to the users page -def user_has_credits(): - has_credits = False - return has_credits