source: music/views.py@ 04f1bb3

Last change on this file since 04f1bb3 was 04f1bb3, checked in by ManuelTrajcev <manueltrajcev7@…>, 8 days ago

search field for tracks

  • Property mode set to 100644
File size: 12.9 KB
Line 
1import json
2
3from django.shortcuts import render
4import os
5import django
6from django.db import connection
7from django.shortcuts import redirect
8
9os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MuiscOrganizationSystem.settings')
10django.setup()
11
12from music.models import *
13
14
15# Create your views here.
16
17def home_page(request):
18 return render(request, 'home.html')
19
20
21def redirect_to_home(request, exception):
22 return redirect('home_page')
23
24
25## LIST OF ALL ##
26def album_list(request):
27 heading = request.GET.get('model', 'All Albums')
28 data = Album.objects.values_list('title', flat=True)
29 return render(request, 'list.html', {'data': data, 'heading': heading})
30
31
32def track_list(request):
33 heading = request.GET.get('model', 'All Tracks')
34 data = Track.objects.values_list('name', flat=True)
35 return render(request, 'list.html', {'data': data, 'heading': heading})
36
37
38def artist_list(request):
39 heading = request.GET.get('model', 'All Artists')
40 data = Artist.objects.values_list('name', flat=True)
41
42 return render(request, 'list.html', {'data': data, 'heading': heading})
43
44
45## VIEWS ##
46def tracks_count_per_genre(request):
47 with connection.cursor() as cursor:
48 cursor.execute("SELECT * FROM track_count_per_genre;")
49 rows = cursor.fetchall()
50
51 data = [{'genre': row[0], 'count': row[1]} for row in rows]
52
53 return render(request, 'track_count_per_genre.html', {'data': data})
54
55
56def avg_track_duration(request):
57 with connection.cursor() as cursor:
58 cursor.execute("SELECT * FROM avg_track_duration_per_artist;")
59 rows = cursor.fetchall()
60
61 data = [{'artist': row[0], 'avg': row[1]} for row in rows]
62
63 return render(request, 'avg_track_duration.html', {'data': data})
64
65
66def rank_list_most_active_customers(request):
67 with connection.cursor() as cursor:
68 cursor.execute("SELECT * FROM rank_list_most_active_customers_view;")
69 rows = cursor.fetchall()
70
71 data = [{'name': row[0], 'total_orders': row[1], 'total_money_spent': row[2]} for row in rows]
72
73 return render(request, 'rank_list_most_active_customers.html', {'data': data})
74
75
76def avg_price_per_artist(request):
77 with connection.cursor() as cursor:
78 cursor.execute("SELECT * FROM avg_price_per_artist;")
79 rows = cursor.fetchall()
80
81 data = [{'name': row[0], 'avg_price_per_track': row[1]} for row in rows]
82
83 return render(request, 'avg_price_per_artist.html', {'data': data})
84
85
86def rank_list_artists(request):
87 with connection.cursor() as cursor:
88 cursor.execute("SELECT * FROM rank_list_artists;")
89 rows = cursor.fetchall()
90
91 data = [{'name': row[0], 'num_invoices': row[1], 'money_earned': row[2]} for row in rows]
92
93 return render(request, 'rank_list_artists.html', {'data': data})
94
95
96def media_type_percentage(request):
97 with connection.cursor() as cursor:
98 cursor.execute("SELECT * FROM media_type_percentage;")
99 rows = cursor.fetchall()
100
101 data = [{'name': row[0], 'num_of_tracks': row[1], 'percentage': row[2]} for row in rows]
102
103 return render(request, 'media_type_percentage.html', {'data': data})
104
105
106def most_listened_genre_per_customer(request):
107 with connection.cursor() as cursor:
108 cursor.execute("SELECT * FROM most_listened_genre_per_customer;")
109 rows = cursor.fetchall()
110
111 data = [{'first_name': row[0], 'last_name': row[1], 'most_listened_genre': row[2]} for row in rows]
112
113 return render(request, 'most_listened_genre_per_customer.html', {'data': data})
114
115
116## QUERRIES ##
117
118def genres_per_customer(request):
119 customers = Customer.objects.all()
120 selected_customer_id = request.GET.get('customer_id')
121 data = []
122 customer = None
123
124 if selected_customer_id:
125 customer = Customer.objects.filter(customer_id=selected_customer_id).first()
126 query = """
127 SELECT c.first_name as first_name, c.last_name as last_name, g.name as genre, COUNT(tr.track_id) as track_count
128 FROM customer c
129 LEFT JOIN invoice i ON c.customer_id = i.customer_id
130 LEFT JOIN invoice_line il ON i.invoice_id = il.invoice_id
131 LEFT JOIN track tr ON il.track_id = tr.track_id
132 LEFT JOIN genre g ON tr.genre_id = g.genre_id
133 WHERE c.customer_id = %s
134 GROUP BY c.customer_id, c.first_name, c.last_name, g.genre_id, g.name
135 ORDER BY c.first_name
136 """
137
138 with connection.cursor() as cursor:
139 cursor.execute(query, [selected_customer_id])
140 rows = cursor.fetchall()
141 data = [{'first_name': row[0], 'last_name': row[1], 'genre': row[2], 'track_count': row[3]} for row in rows]
142
143 return render(request, 'genres_per_customer.html', {
144 'customers': customers,
145 'data': data,
146 'customer': customer,
147 'selected_customer_id': selected_customer_id,
148 })
149
150
151def most_popular_artist_per_customer_per_genre(request):
152 customers = Customer.objects.all()
153 selected_customer_id = request.GET.get('customer_id')
154 data = []
155 customer = []
156 if selected_customer_id:
157 query = """WITH PlayCounts AS (
158 SELECT
159 g.genre_id,
160 g.name AS genre_name,
161 ar.name AS artist_name,
162 COUNT(*) AS play_count
163 FROM customer c
164 JOIN invoice i ON c.customer_id = i.customer_id
165 JOIN invoice_line il ON i.invoice_id = il.invoice_id
166 JOIN track tr ON il.track_id = tr.track_id
167 JOIN genre g ON tr.genre_id = g.genre_id
168 JOIN album a ON tr.album_id = a.album_id
169 JOIN artist ar ON a.artist_id = ar.artist_id
170 WHERE c.customer_id = %s
171 GROUP BY g.genre_id, g.name, ar.name
172 ),
173 MaxPlayCounts AS (
174 SELECT genre_id, MAX(play_count) AS max_count
175 FROM PlayCounts
176 GROUP BY genre_id
177 )
178 SELECT pc.genre_name, pc.artist_name, pc.play_count
179 FROM PlayCounts pc
180 JOIN MaxPlayCounts mpc ON pc.genre_id = mpc.genre_id AND pc.play_count = mpc.max_count;
181 """
182 customer = Customer.objects.filter(customer_id=selected_customer_id).first()
183
184 with connection.cursor() as cursor:
185 cursor.execute(query, [selected_customer_id])
186 rows = cursor.fetchall()
187 data = [{'genre': row[0], 'arist': row[1]} for row in rows]
188
189 return render(request, 'most_popular_artist_per_customer_per_genre.html', {
190 'customers': customers,
191 'customer': customer,
192 'data': data,
193 'selected_customer_id': selected_customer_id,
194 })
195
196
197def invoice_per_customer_after_date(request):
198 customers = Customer.objects.all()
199 selected_customer_id = request.GET.get('customer_id')
200 selected_date = request.GET.get('invoice_date', '2000-01-01')
201 data = []
202 sum = 0
203 customer = None
204
205 if selected_customer_id:
206 customer = Customer.objects.filter(customer_id=selected_customer_id).first()
207 if selected_date:
208 query = """
209 SELECT c.first_name, c.last_name, i.invoice_date::date, i.total
210 FROM customer c
211 JOIN invoice i ON c.customer_id = i.customer_id
212 WHERE c.customer_id = %s AND i.invoice_date > %s
213 ORDER BY i.invoice_date
214 """
215 with connection.cursor() as cursor:
216 cursor.execute(query, [selected_customer_id, selected_date])
217 rows = cursor.fetchall()
218 for r in rows:
219 sum += r[3]
220
221 data = [{'first_name': row[0], 'last_name': row[1], 'invoice_date': row[2], 'total': row[3]} for row in
222 rows]
223 else:
224 query = """
225 SELECT c.first_name, c.last_name, i.invoice_date::date, i.total
226 FROM customer c
227 JOIN invoice i ON c.customer_id = i.customer_id
228 WHERE c.customer_id = %s
229 ORDER BY i.invoice_date
230 """
231 with connection.cursor() as cursor:
232 cursor.execute(query, [selected_customer_id])
233 rows = cursor.fetchall()
234 for r in rows:
235 sum += r[3]
236
237 data = [{'first_name': row[0], 'last_name': row[1], 'invoice_date': row[2], 'total': row[3]}
238 for row in
239 rows]
240
241 return render(request, 'invoices_per_customer_after_date.html', {
242 'customers': customers,
243 'total_sum': sum,
244 'data': data,
245 'customer': customer,
246 'selected_customer_id': selected_customer_id,
247 })
248
249
250from django.shortcuts import render, redirect
251from music.models import Employee
252from django.contrib import messages
253
254
255def batch_update_reports_to(request):
256 selected_manager_id = request.POST.get('manager_id') or request.GET.get('manager_id')
257 employees = Employee.objects.exclude(
258 employee_id=selected_manager_id) if selected_manager_id else Employee.objects.all()
259
260 if request.method == 'POST':
261 selected_employee_ids = request.POST.getlist('employee_ids')
262
263 if selected_manager_id and selected_employee_ids:
264 json_data = json.dumps([
265 {"employee_id": int(emp_id), "reports_to_id": int(selected_manager_id)}
266 for emp_id in selected_employee_ids
267 ])
268 try:
269 with connection.cursor() as cursor:
270 cursor.execute("SELECT batch_update_reports_to(%s::json);", [json_data])
271 messages.success(request, "Batch update successful.")
272 return redirect('batch_update_reports_to')
273
274 except Exception as e:
275 messages.error(request, f"Error during update: {e}")
276
277 all_employees = Employee.objects.all()
278 return render(request, 'batch_update_reports_to.html', {
279 'employees': employees,
280 'all_employees': all_employees,
281 'selected_manager_id': selected_manager_id
282 })
283
284
285def add_tracks_to_playlist(request):
286 search_track = request.GET.get('search_track', '').strip()
287
288 invoices = Invoice.objects.all()
289
290 if search_track:
291 tracks = Track.objects.filter(name__icontains=search_track)
292 else:
293 tracks = Track.objects.all()
294
295 playlists = Playlist.objects.all()
296 selected_playlist_id = request.POST.get('playlist_id') or request.GET.get('playlist_id')
297
298 if request.method == 'POST':
299 selected_track_ids = request.POST.getlist('track_ids')
300
301 if selected_playlist_id and selected_track_ids:
302 json_data = json.dumps([
303 {"track_id": int(track_id)}
304 for track_id in selected_track_ids
305 ])
306 try:
307 with connection.cursor() as cursor:
308 cursor.execute("SELECT add_tracks_to_playlist(%s, %s::json);", [selected_playlist_id, json_data])
309 messages.success(request, "Tracks successfully added to playlist.")
310 return redirect('add_tracks_to_playlist')
311
312 except Exception as e:
313 messages.error(request, f"Error adding tracks: {e}")
314
315 return render(request, 'add_tracks_to_playlist.html', {
316 'playlists': playlists,
317 'tracks': tracks,
318 'selected_playlist_id': selected_playlist_id,
319 'search_track': search_track,
320 })
321
322
323def add_invoice_lines_to_invoice(request):
324 search_track = request.GET.get('search_track', '').strip()
325
326 invoices = Invoice.objects.all()
327
328 if search_track:
329 tracks = Track.objects.filter(name__icontains=search_track)
330 else:
331 tracks = Track.objects.all()
332
333 selected_invoice_id = request.POST.get('invoice_id') or request.GET.get('invoice_id')
334
335 if request.method == 'POST':
336 selected_track_ids = request.POST.getlist('track_ids')
337 quantities = request.POST.getlist('quantities')
338
339 if selected_invoice_id and selected_track_ids and quantities:
340 try:
341 invoice_lines = []
342 for i in range(len(selected_track_ids)):
343 track_id = int(selected_track_ids[i])
344 quantity = int(quantities[i])
345 invoice_lines.append({'track_id': track_id, 'quantity': quantity})
346
347 json_data = json.dumps(invoice_lines)
348
349 with connection.cursor() as cursor:
350 cursor.execute("SELECT add_invoice_lines_to_existing_invoice(%s, %s::json);",
351 [selected_invoice_id, json_data])
352
353 messages.success(request, "Invoice lines added successfully.")
354 return redirect('add_invoice_lines_to_invoice')
355
356 except Exception as e:
357 messages.error(request, f"Error adding invoice lines: {e}")
358
359 return render(request, 'add_invoice_lines_to_invoice.html', {
360 'invoices': invoices,
361 'tracks': tracks,
362 'selected_invoice_id': selected_invoice_id,
363 'search_track': search_track,
364 })
Note: See TracBrowser for help on using the repository browser.