forked from CoderDojoBrianza/CoderDojo-Mobile-Toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
626 lines (557 loc) · 20.5 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
from django.shortcuts import render
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
# from django.template import loader
# from .forms import TutorialUploadForm
from .forms import CheckInOutForm
from .forms import TicketUploadForm
# from django.http import HttpResponseRedirect
from . models import Event
from . models import Ticket
from . models import Libro
from . models import Genere
from . models import Autore
from . models import Participant
from . models import SpriteImages
from . models import Sprite
from . models import SpriteCategory
from . models import Liberatoria
from . models import LearningTopic
from . models import OperatingSystem
from . models import SoftwareTool
import os
import unicodedata
from django.contrib.auth.decorators import permission_required
import csv
import datetime
from io import TextIOWrapper
import random
# https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy
from django.urls import reverse_lazy
toggle = '-'
def base_function(request):
if request.user.id is not None:
user = request.user.get_username()
else:
user = None
context = {"user": user}
return context
def index(request): # Home page
context = base_function(request)
return render(request, "coderdojomobile/index.html", context)
def scratch(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='scratch'
)
context = {
'titolo_liv': "Scratch - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='scratch'
)
context = {
'titolo_liv': "Scratch - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "coderdojomobile/libri.html", context)
def python(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='python'
)
context = {
'titolo_liv': "Python - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='python'
)
context = {
'titolo_liv': "Python - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "libri.html", context)
def html(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='html'
)
context = {
'titolo_liv': "HTML - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='html'
)
context = {
'titolo_liv': "HTML - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "libri.html", context)
def java(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='java'
)
context = {
'titolo_liv': "Java - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='java'
)
context = {
'titolo_liv': "Java - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "libri.html", context)
def php(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='php'
)
context = {
'titolo_liv': "PHP - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='php'
)
context = {
'titolo_liv': "PHP - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "libri.html", context)
def arduino(request, liv):
if liv == 'L*':
elenco = Libro.objects.order_by('titolo').filter(
genere__descrizione='arduino'
)
context = {
'titolo_liv': "Arduino - Tutti livelli",
'lista': elenco
}
else:
elenco = Libro.objects.order_by('titolo').filter(
livello=liv,
genere__descrizione='arduino'
)
context = {
'titolo_liv': "Arduino - Livello " + liv[-1:],
'lista': elenco
}
return render(request, "libri.html", context)
# Per compilare il DB
def genDB(request):
with open(
os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"toolbox/static/toolbox/elenco.txt"
),
"r"
) as f:
titoli = f.readlines()
elenco = dict()
cont = 0
for t in titoli:
if t[0:6] != 'elenco':
elenco[cont] = t[:-5]
unacard = (Libro.objects.order_by('titolo')
.filter(titolo=elenco[cont]))
if len(unacard) == 0: # il titolo non è ancora in DB
# CheGenere = Genere(descrizione='scratch')
# CheAutore = Autore(cognome='Coderdojo', nome='Generico')
print(
Genere.objects.order_by('descrizione')
.filter(descrizione='scratch')[0],
Autore.objects.order_by('cognome')
.filter(cognome='Coderdojo')[0]
)
Card = Libro(
titolo=elenco[cont],
genere=Genere.objects.order_by('descrizione')
.filter(descrizione='scratch')[0],
autore=Autore.objects.order_by('cognome')
.filter(cognome='Coderdojo')[0]
)
Card.save()
# print(Card)
cont += 1
# elenco=dict()
# for libro in Libro.objects.all().order_by('titolo'):
# elenco[libro.titolo] = libro.posizione
context = {'file_dict': elenco}
return render(request, "genDB.html", context)
# Pagina con elenco delle liberatorie
def liberatorie(request, spec):
global toggle
toggle = ('' if toggle == '-' else '-')
if spec == 'cogn':
elenco = Liberatoria.objects.all().order_by(toggle+'cognome')
elif spec == 'nome':
elenco = Liberatoria.objects.all().order_by(toggle+'nome')
elif spec == 'cons':
elenco = Liberatoria.objects.all().order_by(toggle+'consegnata')
else:
elenco = Liberatoria.objects.all().order_by(toggle+'data_di_consegna')
for libera in elenco:
libera.consegnata = (
unicodedata.lookup("HEAVY CHECK MARK") if libera.consegnata
else " "
)
context = {'lista': elenco}
return render(request, "liberatorieLista.html", context)
def nonraggiungibile(request):
return HttpResponse(
"<h2>Sito non raggiungibile. Accesso a internet inesistente"
)
def split_software_by_os(op_sys_list, sw_list):
# TODO hic sunt leones, test / refactor
os_map = {}
for op_sys in op_sys_list:
os_map[op_sys.title] = []
for sw in sw_list:
for op_sys in os_map.keys():
for supported_os in sw.operating_systems.all():
if supported_os.title == op_sys:
os_map[op_sys].append(sw)
break
return os_map
def softwareDojo(request, topic_id):
context = base_function(request)
# TODO filter by operating system
op_sys = OperatingSystem.objects.all().order_by('title')
tools = SoftwareTool.objects.filter(topic_id=topic_id).order_by('title')
sw_map = split_software_by_os(op_sys, tools)
context.update({
'sw_by_os': sw_map})
return render(request, "coderdojomobile/softwareDojo.html", context)
# Usiamo le categorie definite a db
def sprites(request):
context = base_function(request)
sprite_categories = SpriteCategory.objects.order_by('sprite_category_name')
context.update({
'sprite_categories': sprite_categories
})
return render(request, 'coderdojomobile/sprites.html', context)
def spritesAlieni(request):
context = base_function(request)
return render(request, "spritesAlieni.html", context)
def spriteCategory(request, category_id):
context = base_function(request)
sprites = Sprite.objects.order_by('sprite_name').filter(
spritecategory__id=category_id
)
sprite_images = SpriteImages.objects.all().filter(
sprite__in=sprites
).order_by('image_order')
for sprite in sprites:
sprite.imgs = []
for image in sprite_images:
if image.sprite.id == sprite.id:
sprite.imgs.append(image)
context.update({
'sprites': sprites,
'sprite_images': sprite_images
})
return render(request, 'coderdojomobile/spritesInCategory.html', context)
def learningTopicGuides(request):
context = base_function(request)
learning_topics = LearningTopic.objects.order_by('title')
context.update({
'learning_topics': learning_topics
})
return render(
request,
'coderdojomobile/learningTopicsGuides.html',
context
)
def learningTopicSoftwares(request):
context = base_function(request)
learning_topics = LearningTopic.objects.order_by('title')
context.update({
'learning_topics': learning_topics
})
return render(
request,
'coderdojomobile/learningTopicsSoftware.html',
context
)
def events(request):
context = base_function(request)
sorted_events = Event.objects.order_by('event_date')
context.update({
'events': sorted_events,
})
return render(request, 'coderdojomobile/events.html', context)
def add_waiver_status_to_ticket(ticket):
ticket.has_valid_waiver = has_valid_waiver(ticket)
def eventDetails(request, event_id):
context = base_function(request)
event = Event.objects.order_by('event_date').get(id=event_id)
tickets = Ticket.objects.order_by('participant__name').filter(
event__id=event_id
)
total_participants = tickets.count()
missing_participants = 0
for ticket in tickets:
if not ticket.has_checked_in:
missing_participants = missing_participants + 1
total_participants = tickets.count()
# Navigate participants from tickets of this event
queryset_for_form = Participant.objects.filter(ticket__event__id=event_id)
participants = queryset_for_form
for ticket in tickets:
for participant in participants:
if participant.id == ticket.participant.id:
add_waiver_status_to_ticket(ticket)
ticket.badges = []
for part_badge in participant.badges.all():
ticket.badges.append(part_badge)
form = CheckInOutForm(queryset_for_form)
ticket_upload_form = TicketUploadForm()
context.update({
'event': event,
'tickets': tickets,
'form': form,
'total_participants': total_participants,
'missing_participants': missing_participants,
'ticket_upload_form': ticket_upload_form
})
return render(request, 'coderdojomobile/eventDetails.html', context)
def is_valid_waiver_for_event(waiver, event):
return waiver is not None \
and waiver.valid \
and (waiver.expiry_date is None
or waiver.expiry_date > event.event_date)
def has_valid_waiver(ticket):
waiver = None
waiver_valid = False
try:
waiver = ticket.participant.waiver
except ObjectDoesNotExist:
waiver = None
waiver_valid = is_valid_waiver_for_event(waiver, ticket.event)
return waiver_valid
@permission_required(
'coderdojomobile.change_ticket',
login_url=reverse_lazy('coderdojomobile:login',
current_app="coderdojomobile")
)
def eventCheckInOut(request, event_id):
context = base_function(request)
if request.method == 'POST': # fix get
# create a form instance and populate it with data from the request:
# Navigate participants from tickets of this event
queryset = Participant.objects.filter(ticket__event__id=event_id)
form = CheckInOutForm(queryset_for_form=queryset, data=request.POST)
ticket = None
event = None
ticket_found = False
waiver_valid = False
try:
event = Event.objects.get(id=event_id)
except ObjectDoesNotExist:
event = None
if form.is_valid():
# Check which field is populated
try:
if (len(form.cleaned_data['participant_id']) > 0):
ticket = Ticket.objects.get(
event__id=event_id,
participant__uuid=form.cleaned_data['participant_id']
)
elif (len(form.cleaned_data['ticket_id']) > 0):
ticket = Ticket.objects.get(
event__id=event_id,
uuid=form.cleaned_data['ticket_id']
)
elif not (form.cleaned_data['participant'] is None):
ticket = Ticket.objects.get(
event__id=event_id,
participant__id=form.cleaned_data['participant'].id
)
except ObjectDoesNotExist:
ticket = None
if not (ticket is None): # We found the ticket, set status
ticket_found = True
if form.cleaned_data['check_in_out'] == form.CHECK_IN:
ticket.has_checked_in = True
else:
ticket.has_checked_in = False
ticket.save()
# check waiver status
waiver_valid = has_valid_waiver(ticket)
context.update({
'ticket': ticket,
'event': event,
'waiver_is_valid': waiver_valid,
'ticket_found': ticket_found
})
return render(request, 'coderdojomobile/eventCheckInOut.html', context)
def generate_uuid():
now = datetime.datetime.now()
rand = random.randint(1, 999)
micro = now.strftime("%f").zfill(6)[3:6]
uuid = now.strftime("%M%S") + str(micro) + str(rand).zfill(3)
return uuid
class TicketLoadingOutcome():
ok = 0
error = 1
def __init__(self, name, surname, ticket_id, badge_id, outcome):
self.name = name
self.surname = surname
self.ticket_id = ticket_id
self.badge_id = badge_id
self.outcome = outcome
def import_ticket(ticket, event):
'''
if badge id is not null, it is used to identify the participant
otherwise, name and surname are used
if the badge id does not match an existing badge id, a new participant
is created. This is done to allow Ninjas to use the same badge in more
than one Dojo.
No check is performed on name - surname w.r.t badge id.
'''
name = ticket['Name']
surname = ticket['Surname']
ticket_id = ticket['Ticket_id']
badge_id = ticket['Badge_id']
participant = None
outcome = None
if badge_id is not None and len(badge_id) > 0:
# Look for the Participant
try:
participant = Participant.objects.get(uuid=badge_id)
except Participant.DoesNotExist:
pass
elif name is not None and surname is not None \
and len(name) > 0 and len(surname) > 0:
# Look for the Participant
try:
participant = Participant.objects.get(
name__iexact=name,
surname__iexact=surname
)
except Participant.DoesNotExist:
pass
except Participant.MultipleObjectsReturned:
outcome = TicketLoadingOutcome(
name,
surname,
ticket_id,
badge_id,
TicketLoadingOutcome.error)
if participant is None and outcome is None:
# create
badge_id = generate_uuid()
participant = Participant.objects.create(
name=name,
surname=surname,
uuid=badge_id
)
if ticket_id is None or len(ticket_id) == 0 and outcome is None:
ticket_id = generate_uuid()
if outcome is None:
Ticket.objects.create(
participant=participant,
event=event,
has_checked_in=False,
uuid=ticket_id
)
outcome = TicketLoadingOutcome(
name,
surname,
ticket_id,
badge_id,
TicketLoadingOutcome.ok)
return outcome
def import_event_participants(external_ticket_list, event):
processed_tickets = []
for ticket in external_ticket_list:
processed_tickets.append(import_ticket(ticket, event))
return processed_tickets
@permission_required(
'coderdojomobile.change_ticket',
login_url=reverse_lazy('coderdojomobile:login',
current_app="coderdojomobile")
)
def event_ticket_upload(request, event_id):
context = base_function(request)
event = None
processed_tickets = []
if request.method == 'POST': # TODO handle get
form = TicketUploadForm(request.POST, request.FILES)
'''
CSV format support 4 fields:
name, surname, ticket id (optional), badge id (optional)
'''
ticket_list = []
if form.is_valid():
try:
event = Event.objects.get(id=event_id)
except Event.DoesNotExist:
pass
if event is not None:
# Check which field is populated
try:
# https://stackoverflow.com/a/16243182
ticket_file = \
TextIOWrapper(
request.FILES['ticket_file'].file,
encoding='utf-8'
)
reader = csv.DictReader(
ticket_file,
fieldnames=[
'Name',
'Surname',
'Ticket_id',
'Badge_id'
]
)
next(reader) # skip first line
for row in reader:
ticket_list.append(row)
except csv.Error as e:
print('line {}: {}'.format(reader.line_num, e))
processed_tickets = import_event_participants(
ticket_list,
event
)
context.update({
'tickets': processed_tickets,
'event': event
})
return render(
request,
'coderdojomobile/eventTicketUpload.html',
context)
# -----------------------------------------------------------------------------
# Function usate per prova
def libro(request, id):
try:
libro = Libro.objects.get(pk=id)
return HttpResponse(
"'%s' di %s, %s<br>" % (libro.titolo, libro.autore, libro.genere)
)
except Libro.DoesNotExist:
return HttpResponse("Codice %s inesistente" % id)
def lista(request):
elenco = dict()
for libro in Libro.objects.all().order_by('titolo'):
elenco[libro.titolo] = libro.posizione
context = {'file_dict': elenco}
return render(request, "libriLista.html", context)