File size: 32,533 Bytes
05dddec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c12e7
05dddec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.models import User
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt    
from api.models import Profile, Department, Event, Ticket, Notifications
import re
import requests
import random
import json
import uuid
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# sender = "[email protected]"
# password = "Auabs@904"
# server = smtplib.SMTP('smtp.gmail.com', 587)
# server.starttls()
# server.login(sender, password)
# create a function
def emailSender(reciver,template,otp):
    # global server

    # msg = MIMEMultipart('alternative')
    # msg['Subject'] = "Link"
    # msg['From'] = sender
    # msg['To'] = reciver

    # f = open(template, "r", encoding="utf-8")
    # html = f.read()
    # html = html.replace("%%OTP1%%", otp[0])
    # html = html.replace("%%OTP2%%", otp[1])
    # html = html.replace("%%OTP3%%", otp[2])
    # html = html.replace("%%OTP4%%", otp[3])
    # part = MIMEText(html, 'html')
    # msg.attach(part)
    # server.sendmail(sender, reciver, msg.as_string())
    pass

def home(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    departments = Department.objects.all()
    departmentArr = []
    for department in departments:
        departmentArr.append([department.name, department.posterImage])
    events = Event.objects.filter(department=Department.objects.filter(name="Computer Engineering").first()).all().order_by('-name')
    eventArr = []
    impEvent = []
    for event in events:
        if event.name != "X - Motion Game Mania":
            eventArr.append([event.name, (event.price).strip(), event.description, event.tagline,event.posterImage, (event.name).replace(" ", "-").replace("---", ":"),event.isTeamEvent,event.teamPrice])
        else:
            impEvent = [[event.name, (event.price).strip(), event.description, event.tagline,event.posterImage, (event.name).replace(" ", "-").replace("---", ":"),event.isTeamEvent,event.teamPrice]]
    impEvent.extend(eventArr[:10])
    context = {
        "departmentArr": departmentArr[:10],
        "eventArr": impEvent,
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic
    }
    return render(request, "index.html", context)

def events(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    departments = Department.objects.all()
    departmentArr = []
    impEvent = []
    for department in departments:
        events = Event.objects.filter(department=department).order_by('-name').all()
        eventArr = []
        tempDepartment = {
            "departmentName" : department.name
        }
        for event in events:
            tempEvent = {
                "eventName" : event.name,
                "eventPrice" : event.price,
                "eventDescription" : event.description,
                "eventTagline" : event.tagline,
                "eventPosterImage" : event.posterImage,
                "eventLink" : (event.name).replace(" ", "-").replace("---", ":"),
                "isTeamEvent" : event.isTeamEvent,
                "teamPrice" : event.teamPrice,
                "isTeamPriceFull" : event.isTeamPriceFull,
                "winnerPrice1" : event.winnerPrice1 if event.winnerPrice1 != None else 0 ,
                "winnerPrice2" : event.winnerPrice2 if event.winnerPrice2 != None else 0 ,
                "isClosed" : event.isClosed
                
            }
            eventArr.append(tempEvent)
        tempDepartment["events"] = eventArr
        tempDepartment["eventCount"] = len(eventArr)
        departmentArr.append(tempDepartment)
    context = {
        "departmentArr": departmentArr,
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic
    }
    return HttpResponse(json.dumps(context), content_type="application/json")

def aboutus(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    context={
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic
    }
    return render(request, "about-us.html", context)

@csrf_exempt
def signin(request):
    if request.method == "POST":
        email = request.POST['email']
        password = request.POST['password']
        request.session['emailVarification'] = email
        try:
            username = User.objects.filter(email=email).first().username
            user = authenticate(username=username, password=password)
            if user is not None:
                profile = Profile.objects.filter(user=user).first()
                isVerified = True
                isAccountSetup = profile.isAccountSetup
                profile.save()
                if isAccountSetup == True:
                    login(request, user)
                    return redirect("/")
                else:
                    context = {'email' : email}
                    return redirect("/accountSetUp",context)
        except:
            context = {
                "error": True
            }
            
            return render(request, "login.html",context)
        else:
            context = {
                "error": True
            }
            return render(request, "login.html",context)
    return render(request, "login.html")

def check(email):
    regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
    if(re.fullmatch(regex, email)):
        return True
    else:
        return False

@csrf_exempt
def register(request):
    if request.method == "POST": 
        email = request.POST['email']
        pass1 = request.POST['password1']
        pass2 = request.POST['password2']

        if not check(email):
            context = {
                "error" : "Invalid Email."
            }
            return render(request, "register.html",context)
            #return HttpResponse(json.dumps({"error": "Invalid Email."}), content_type="application/json")
        elif pass1 != pass2:
            context = {
                "error" : "Password Does Not Match."
            }
            return render(request, "register.html",context)
            #return HttpResponse(json.dumps({"error": "Password Does Not Match."}), content_type="application/json")
        else:
            users = User.objects.filter(email=email).all().count()
            if users == 0:
                newUser = User.objects.create_user(username=email, email=email, password=pass1)
                newUser.save()
                otp = str(random.randint(1000, 9999))
                profileForNewUser = Profile()
                profileForNewUser.user = User.objects.filter(email=email).first()
                profileForNewUser.otp = otp
                profileForNewUser.events = {"data": []}
                profileForNewUser.notification = {"data": []}
                profileForNewUser.isAccountSetup = False
                profileForNewUser.isVolunteer = False
                profileForNewUser.isOrganiser = False
                profileForNewUser.isVerified = True
                profileForNewUser.save()
                emailSender(email,"./emailTemplates/welcomeEmail.html",str(otp))
                request.session['emailVarification'] = email
                return redirect("/accountSetUp/")
            else:
                context = {
                    "error" : "User Already Exists."
                }
                return render(request, "register.html",context)
    
    return render(request, "register.html")

def event(request, event):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            email = request.user.email
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            email = ""
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        email = ""
        userName = ""
        profilePic = "0001"
    context = {
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic,
        "email" : email
    }
    eventData = Event.objects.filter(name=event.replace("-", " ").replace(":", " - ")).first()
    context["isTeamEvent"] = eventData.isTeamEvent
    context["name"] = eventData.name
    context["department"] = eventData.department.name
    context["teamName"] = eventData.teamName
    context["teamLeader"] = eventData.teamLeader.user.get_full_name() if eventData.teamLeader != None else ""
    context["price"] = eventData.price
    context["winnerPrice1"] = eventData.winnerPrice1
    context["winnerPrice2"] = eventData.winnerPrice2
    context["location"] = eventData.location
    context["date"] = str(eventData.date)
    context["description"] = eventData.description
    context["rules"] = (eventData.rules).split("•")[1:] if eventData.rules != None and eventData.rules != "" else ""
    round1 = (eventData.round1).split("•")[1:] if eventData.round1 != None else []
    round2 = (eventData.round2).split("•")[1:] if eventData.round2 != None else []
    round3 = (eventData.round3).split("•")[1:] if eventData.round3 != None else []
    round4 = (eventData.round4).split("•")[1:] if eventData.round4 != None else []
    round5 = (eventData.round5).split("•")[1:] if eventData.round5 != None else []
    round1Title = eventData.round1Title if eventData.round1Title != None else ""
    round2Title = eventData.round2Title if eventData.round2Title != None else ""
    round3Title = eventData.round3Title if eventData.round3Title != None else ""
    round4Title = eventData.round4Title if eventData.round4Title != None else ""
    round5Title = eventData.round5Title if eventData.round5Title != None else ""
    context["rounds"] = []
    if round1Title != "":
        context["rounds"].append({"title": round1Title,"description": round1})
    if round2Title != "":
        context["rounds"].append({"title": round2Title,"description": round2})
    if round3Title != "":
        context["rounds"].append({"title": round3Title,"description": round3})
    if round4Title != "":
        context["rounds"].append({"title": round4Title,"description": round4})
    if round5Title != "":
        context["rounds"].append({"title": round5Title,"description": round5})
    context["tagline"] = eventData.tagline
    context["posterImage"] = eventData.posterImage
    context["winner1"] =  eventData.winner1.user.get_full_name() if eventData.winner1 != None  else ""
    context["winner2"] =  eventData.winner2.user.get_full_name() if eventData.winner2 != None  else ""
    context["winner3"] =  eventData.winner3.user.get_full_name() if eventData.winner3 != None  else ""
    context["organiser1"] = eventData.organiser1.user.get_full_name() if eventData.organiser1 != None else ""
    context["organiser1Phone"] = Profile.objects.filter(user=eventData.organiser1.user).first().phone if eventData.organiser1 != None else ""
    context["organiser2"] = eventData.organiser2.user.get_full_name() if eventData.organiser2 != None else ""
    context["organiser2Phone"] = Profile.objects.filter(user=eventData.organiser2.user).first().phone if eventData.organiser2 != None else ""
    context["organiser3"] = eventData.organiser3.user.get_full_name() if eventData.organiser3 != None else ""
    context["organiser3Phone"] = Profile.objects.filter(user=eventData.organiser3.user).first().phone if eventData.organiser3 != None else ""
    context["organiser4"] = eventData.organiser4.user.get_full_name() if eventData.organiser4 != None else ""
    context["organiser4Phone"] = Profile.objects.filter(user=eventData.organiser4.user).first().phone if eventData.organiser4 != None else ""
    context["organiser5"] = eventData.organiser5.user.get_full_name() if eventData.organiser5 != None else ""
    context["organiser5Phone"] = Profile.objects.filter(user=eventData.organiser5.user).first().phone if eventData.organiser5 != None else ""
    context["isTeamEvent"] = eventData.isTeamEvent
    context["teamParticapantCount"] = eventData.teamParticapantCount
    context["isClosed"] = eventData.isClosed
    context["status"] = eventData.status
    context["images"] = eventData.images["data"]
    context["isClosed"] = eventData.isClosed
    # request.session['event'] = eventData.name
    return HttpResponse(json.dumps(context), content_type="application/json")

def otpvalidationWeb(request):
    if request.method == "POST":
        email = request.session['emailVarification']
        user = Profile.objects.filter(user=User.objects.filter(email=email).first()).first()
        if userOtp == user.otp:
            profile = Profile.objects.filter(user=User.objects.filter(email=email).first()).first()
            profile.isVerified = True
            profile.save()
            return redirect("/accountSetUp/")
        else:
            context = {'error' : "Invalid OTP"}
            return render(request, "otp-page.html",context)
    #404 page
    return render(request, "404.html")

def pageNotFound(request):
    return render(request,"404.html")

def cart(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    context={
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic
    }
    return render(request,"cart.html",context)

def signOut(request):
    logout(request)
    return redirect('/')

def faqs(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    context = {
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic
    }
    return render(request,"faqs.html",context)

def accountSetUp(request):
    if request.method == "POST":
        try: 
            email = request.session['emailVarification']
            
            name = request.POST['firstname']
            #college = body['college']
            phone = request.POST['mobileNo']
            profilePic = request.POST['profilePic']
            user = User.objects.filter(email=email).first()
            user.first_name = name
            user.save()
            profile = Profile.objects.filter(user=user).first()
            profile.college = "LDRP-ITR"
            profile.phone = phone
            profile.profilePic = profilePic
            profile.isAccountSetup = True
            profile.save()

            request.session['accountSetup'] = True

            return redirect('/login')
        except Exception as error: 
            print(error)
            return render(request, "account-setup.html")
    return render(request, "account-setup.html")

@csrf_exempt
def resendOtpWeb(request):
    try: 
        email =  request.session['emailVarification']
        otp = str(random.randint(1000, 9999))
        profile = Profile.objects.filter(user=User.objects.filter(email=email).first()).first()
        profile.otp = otp
        profile.save()
        emailSender(email,"./emailTemplates/resendOTPEmail.html",str(otp))
        return HttpResponse(json.dumps({"msg": "OTP sent to "+email}), content_type="application/json")
    except Exception as error:
            return HttpResponse(json.dumps({"error": error}), content_type="application/json")

@csrf_exempt
def ticketVerifer(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    if isVolunteer == True:
        if request.method == "POST":
            body = json.loads(request.body)
            id = body['id']
            ticket = Ticket.objects.filter(id=id).first()
            if ticket != None:
                
                ticket.acceptedBy = profile
                ticket.isPaid = True
                
                ticket.save()
                return  HttpResponse(json.dumps({"msg": "Ticket has been Paid."}), content_type="application/json")
            else:
                return HttpResponse(json.dumps({"error": "error"}), content_type="application/json")
        tickets = Ticket.objects.all()
        dataTemp = []
        for ticket in tickets:
            count = 1
            if ticket.owner1 != None:
                count=count+1
            if ticket.owner2 != None:
                count=count+1
            if ticket.owner3 != None:
                count=count+1
            if ticket.owner4 != None:
                count=count+1
            temp = {}
            temp["id"] = ticket.id
            temp["profilePic"] = ticket.owner.profilePic
            temp["username"] = ticket.owner.user.first_name
            temp["email"] = ticket.owner.user.email
            if ticket.event.isTeamEvent != True:
                temp["price"] = ticket.event.price
            else: 
                temp["price"] = ticket.event.teamPrice
            temp["eventName"] = ticket.event.name
            temp["isPaid"] = ticket.isPaid
            temp["isTeamPriceFull"] = ticket.event.isTeamPriceFull
            try:
                temp["userCount"] = count
                if count != 1:
                    temp["total"] = count*int(ticket.event.price)
            except:
                temp["userCount"] = count
                temp["total"] = ticket.event.price
            dataTemp.append(temp)
        data = []
        data2 = []
        for i in dataTemp:
            if i["isPaid"]== False:
                data.append(i)
            else:
                data2.append(i)
        data = data[::-1]
        data.extend(data2)
        context = {
            "data" : data,
            "isUser" : isUser,
            "isVolunteer" : isVolunteer,
            "userName" : userName,
            "profilePic" : profilePic
        }
        return render(request, "ticket.html",context)
    else:
        return render(request, "404.html")

def myTicket(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
            
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    if isUser == True:
        tickets = Ticket.objects.filter(Q(owner=profile)|Q(owner1=profile)|Q(owner2=profile)|Q(owner3=profile)|Q(owner4=profile)).all()
        
        dataTemp = []
        for ticket in tickets:
            count = 1
            if ticket.owner1 != None:
                count=count+1
            if ticket.owner2 != None:
                count=count+1
            if ticket.owner3 != None:
                count=count+1
            if ticket.owner4 != None:
                count=count+1
            temp = {}
            temp["id"] = ticket.id
            temp["profilePic"] = ticket.owner.profilePic
            temp["username"] = ticket.owner.user.first_name
            temp["email"] = ticket.owner.user.email
            if ticket.event.isTeamEvent != True:
                temp["price"] = ticket.event.price
            else: 
                temp["price"] = ticket.event.teamPrice
            temp["eventName"] = ticket.event.name
            temp["isPaid"] = ticket.isPaid
            temp["qrCodeData"] = ticket.qrCodeData
            temp["isTeamPriceFull"] = ticket.event.isTeamPriceFull
            if ticket.userCount >0:
                temp["isScanned"] = False
            else:
                temp["isScanned"] = True
            try:
                temp["userCount"] = count
                if count != 1:
                    temp["total"] = count*int(ticket.event.price)
            except:
                temp["userCount"] = 1
                temp["total"] = 0
            dataTemp.append(temp)
        data = []
        data2 = []
        for i in dataTemp:
            if i["isPaid"]== False:
                data.append(i)
            else:
                data2.append(i)
        data = data[::-1]
        data2 = data2[::-1]
        data.extend(data2)
        context = {
            "data" : data,
            "isUser" : isUser,
            "isVolunteer" : isVolunteer,
            "userName" : userName,
            "profilePic" : profilePic
        }
        return render(request, "myTicket.html",context)
    else:
        return render(request, "404.html")

def eventConfirmation(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    context = {
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic,
        "team" : request.session['team'],
        "event" : request.session['event']
    }
    return render(request, "event-confirmation.html",context)

@csrf_exempt
def addTeamMebers(request):
    if request.user != None:
        try:
            profile = Profile.objects.filter(user=request.user).first()
            userName = request.user.first_name
            isUser = True
            isVolunteer = profile.isCampainVolunteer
            profilePic = profile.profilePic
        except:
            userName = "Anonymous"
            isUser = False
            isVolunteer = False
            profilePic = "0001"
    else:
        isUser = False
        isVolunteer = False
        userName = ""
        profilePic = "0001"
    
    if request.method == "POST":
        isForm = request.POST.get('isForm',False)
        if isForm == False:
            body = json.loads(request.body)
            email = body['email']
            user = User.objects.filter(email=email).first()
            if user is not None:
                return HttpResponse(json.dumps({"msg": email + " does exist in our Database."}), content_type="application/json")
            else:
                return HttpResponse(json.dumps({"error": "Email does not exist in our Database"}), content_type="application/json")
        else:
            users = request.POST.get('user')
            emailArr = users.split(",")
            request.session['team'] = []
            try:
                for i in range(len(emailArr)):
                    user = User.objects.filter(email=emailArr[i]).first()
                    profile = Profile.objects.filter(user=user).first()
                    if user is not None:
                        request.session['team'].append({"name":user.first_name, "email":user.email,"phone":profile.phone})
                return redirect("/eventConfirmation/")
            except:
                context = {
                    'email':request.user,
                    "isUser" : isUser,
                    "isVolunteer" : isVolunteer,
                    "userName" : userName,
                    "profilePic" : profilePic,
                    "event" : request.session['event'],
                    "min":Event.objects.filter(name=request.session['event']).first().teamParticapantCountMin,
                    "max":Event.objects.filter(name=request.session['event']).first().teamParticapantCount,
                    "error" : "Please confirm emails of your team members.",
                }
                return render(request, 'event-registration-form.html',context)
    
    context = {
        'email':request.user,
        "isUser" : isUser,
        "isVolunteer" : isVolunteer,
        "userName" : userName,
        "profilePic" : profilePic,
        "event" : request.session['event'],
        "min":Event.objects.filter(name=request.session['event']).first().teamParticapantCountMin,
        "max":Event.objects.filter(name=request.session['event']).first().teamParticapantCount,
    }
    return render(request, 'event-registration-form.html',context)

@csrf_exempt
def ticketGenrator(request):
    if request.method == "POST":
        try:
            body = json.loads(request.body)
            if 'isTeam' not in body.keys():
                eventName = body['event']
                event = Event.objects.filter(name=eventName).first()
                if event.isClosed == True:
                    return HttpResponse(json.dumps({"error": "Registration for this event is closed."}), content_type="application/json")
                else:
                    email = body['email']
                    user = User.objects.filter(email=email).first()
                    owner = Profile.objects.filter(user=user).first()
                    qrCodeData = uuid.uuid1()
                    userCount = body['userCount']
                    newTicket = Ticket()
                    newTicket.event = event
                    newTicket.owner = owner
                    newTicket.qrCodeData = qrCodeData
                    newTicket.userCount = userCount
                    newTicket.save()
                    return HttpResponse(json.dumps({"msg": "You are successfully registered. Your registration will get confirmed and you will also see the ticket in your account once you make the payment."}), content_type="application/json")
            else:
                eventName = body['event']
                event = Event.objects.filter(name=eventName).first()
                if event.isClosed == True:
                    return HttpResponse(json.dumps({"error": "Registration for this event is closed."}), content_type="application/json")
                else:
                    email = request.session['team'][0]['email']
                    user = User.objects.filter(email=email).first()
                    owner = Profile.objects.filter(user=user).first()
                    qrCodeData = uuid.uuid1()
                    newTicket = Ticket()
                    newTicket.event = event
                    newTicket.owner = owner
                    try:
                        teamMember1= User.objects.filter(email=request.session['team'][1]["email"]).first()
                        teamMember1Profile = Profile.objects.filter(user=teamMember1).first()
                        newTicket.owner1 = teamMember1Profile 
                    except:
                        newTicket.owner1 = None
                    try:
                        teamMember2= User.objects.filter(email=request.session['team'][2]["email"]).first()
                        teamMember2Profile = Profile.objects.filter(user=teamMember2).first()
                        newTicket.owner2 = teamMember2Profile 
                    except:
                        newTicket.owner2 = None
                    try:
                        teamMember3= User.objects.filter(email=request.session['team'][3]["email"]).first()
                        teamMember3Profile = Profile.objects.filter(user=teamMember3).first()
                        newTicket.owner3 = teamMember3Profile 
                    except:
                        newTicket.owner3 = None
                    try:
                        teamMember4= User.objects.filter(email=request.session['team'][4]["email"]).first()
                        teamMember4Profile = Profile.objects.filter(user=teamMember4).first()
                        newTicket.owner4 = teamMember4Profile 
                    except:
                        newTicket.owner4 = None
                    newTicket.qrCodeData = qrCodeData
                    newTicket.userCount = len(request.session['team'])
                    newTicket.save()
                    request.session['team'] = []
                    return HttpResponse(json.dumps({"msg": "You are successfully registered. Your registration will get confirmed and you will also see the ticket in your account once you make the payment."}), content_type="application/json")
        except Exception as error:
            return HttpResponse(json.dumps({"error": str(error)}), content_type="application/json")
    else:
        return render(request, "404.html")

@csrf_exempt
def dataOutper(request):
    for event in Event.objects.all():
        eventName = event.name
        department = event.department.name
        tickets = Ticket.objects.filter(event=event).all()
        paid = 0
        unpaid = 0
        for ticket in tickets:
            if ticket.event.isTeamEvent:
                if ticket.isPaid:
                    paid += ticket.userCount
                else:
                    unpaid += ticket.userCount
            else:
                if ticket.isPaid:
                    paid += 1
                else:
                    unpaid += 1
        print(department,",",eventName,",",paid,",",unpaid)
    return HttpResponse("Done")

@csrf_exempt
def closeEvents(request):
    for event in Event.objects.all():
        event.isClosed = True
        event.save()
    return HttpResponse("Done")