source: music/views.py@ aee9548

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

more search fields

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