-
Notifications
You must be signed in to change notification settings - Fork 2
/
views.py
1547 lines (1337 loc) · 61.1 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
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Roster views
from django.http import HttpResponse
from django.utils.html import escape, linebreaks
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db.models import Q, Count, Sum
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from django.contrib.formtools.wizard.views import SessionWizardView
from settings import MEDIA_ROOT
from roster.models import *
from roster.forms import *
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, BaseDocTemplate, SimpleDocTemplate, Table, TableStyle, PageBreak, ActionFlowable, Frame, PageTemplate
from reportlab.platypus.flowables import Flowable
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.utils import ImageReader
from reportlab.graphics.barcode import code39
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Calibri', 'calibri.ttf'))
pdfmetrics.registerFont(TTFont('Calibri-Bold', 'calibrib.ttf'))
pdfmetrics.registerFont(TTFont('Calibri-Italic', 'calibrii.ttf'))
import os
import csv
import math
team_color1 = (55.0/255.0, 88.0/255.0, 150.0/255.0)
team_color2 = (236.0/255.0, 108.0/255.0, 29.0/255.0)
@login_required(login_url='/roster/login/')
def front(request):
return render_to_response("roster/front.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def email_list(request):
"""Team email list."""
if request.method == 'GET' and request.GET:
form = EmailListForm(request.GET)
if form.is_valid():
who = set(form.data.getlist('who'))
include_parents = 'Parent' in who
who.discard('Parent')
people = PersonTeam.objects.filter(role__in=who,
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
results = PersonEmail.objects.filter(primary=True, person__in=people)
# Follow relationship to parents from students if enabled.
if include_parents:
parent_relationships = RelationshipType.objects.filter(parent=True).values('id')
students = PersonTeam.objects.filter(role='Student',
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
parents = Relationship.objects.filter(person_from__in=students,
relationship__in=parent_relationships).values('person_to')
results |= PersonEmail.objects.filter(primary=True, person__in=parents)
# CC on emails if enabled. Only does one level.
if results and 'cc_on_email' in form.data:
cc = Relationship.objects.filter(person_from__in=people,
cc_on_email=True).values('person_to')
results |= PersonEmail.objects.filter(primary=True, person__in=cc)
# Uniquify and get related info to avoid additional queries
results = results.select_related('person', 'email.email').distinct()
include_name = 'include_name' in form.data
separator = form.data['separator']
else:
form = EmailListForm()
return render_to_response("roster/email_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def contact_list(request):
"""Team contact list (phone and email)."""
if request.method == 'GET' and request.GET:
form = ContactListForm(request.GET)
if form.is_valid():
who = set(form.data.getlist('who'))
include_parents = 'Parent' in who
who.discard('Parent')
status = form.data.getlist('status')
teams = sorted(form.data.getlist('team'))
team_index = dict((int(x[1]), x[0]) for x in enumerate(teams))
print team_index
people = PersonTeam.objects.filter(role__in=who,
status__in=status, team__in=teams).values('person')
results = Person.objects.batch_select('phones')\
.filter(id__in=people)
# Follow relationship to parents from students if enabled.
if include_parents:
parent_relationships = RelationshipType.objects.filter(parent=True).values('id')
students = PersonTeam.objects.filter(role='Student',
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
parents = Relationship.objects.filter(person_from__in=students,
relationship__in=parent_relationships)
parents_map = dict(parents.values_list('person_to', 'person_from'))
results |= Person.objects.batch_select('phones')\
.filter(id__in=parents_map.keys())
# Uniquify and get related info to avoid additional queries
results = results.distinct()
cc_on_email = 'cc_on_email' in form.data
final_results = []
for result in results:
name = result.render_normal()
roles = [""]*len(teams)
if include_parents and result.id in parents_map:
for x in PersonTeam.objects.filter(person__id=parents_map[result.id],
status__in=status, team__in=teams):
roles[team_index[x.team.id]] = "%sParent" % \
(x.status == 'Prospective' and "Prospective " or "",)
for x in PersonTeam.objects.filter(person=result,
status__in=status, team__in=teams):
roles[team_index[x.team.id]] = "%s%s" % \
(x.status == 'Prospective' and "Prospective " or "",
x.role)
cell = ""
home = ""
for phone in result.phones_all:
if phone.location == 'Mobile':
cell = phone.render_normal()
elif phone.location == 'Home':
home = phone.render_normal()
emails = [pe.email for pe in
PersonEmail.objects.filter(primary=True, person=result)]
cc_emails = []
if cc_on_email:
cc = Relationship.objects.filter(person_from=result,
cc_on_email=True).values('person_to')
cc_emails = sorted(set(pe.email for pe in
PersonEmail.objects.filter(primary=True, person__in=cc)))
final_results.append(dict(name=name, roles=roles, cell=cell,
home=home, emails=emails,
cc_emails=cc_emails))
teams = Team.objects.filter(id__in=teams).order_by('id')
else:
form = ContactListForm()
return render_to_response("roster/contact_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def phone_list(request):
"""Team phone list."""
if request.method == 'GET' and request.GET:
form = PhoneListForm(request.GET)
if form.is_valid():
who = set(form.data.getlist('who'))
include_parents = 'Parent' in who
who.discard('Parent')
status = form.data.getlist('status')
teams = sorted(form.data.getlist('team'))
team_index = dict((int(x[1]), x[0]) for x in enumerate(teams))
print team_index
people = PersonTeam.objects.filter(role__in=who,
status__in=status, team__in=teams).values('person')
results = Person.objects.batch_select('phones').filter(id__in=people)
# Follow relationship to parents from students if enabled.
if include_parents:
parent_relationships = RelationshipType.objects.filter(parent=True).values('id')
students = PersonTeam.objects.filter(role='Student',
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
parents = Relationship.objects.filter(person_from__in=students,
relationship__in=parent_relationships)
parents_map = dict(parents.values_list('person_to', 'person_from'))
results |= Person.objects.batch_select('phones').filter(
id__in=parents_map.keys())
# Uniquify and get related info to avoid additional queries
results = results.distinct()
final_results = []
for result in results:
name = result.render_normal()
roles = [""]*len(teams)
if include_parents and result.id in parents_map:
for x in PersonTeam.objects.filter(person__id=parents_map[result.id],
status__in=status, team__in=teams):
roles[team_index[x.team.id]] = "%sParent" % \
(x.status == 'Prospective' and "Prospective " or "",)
for x in PersonTeam.objects.filter(person=result,
status__in=status, team__in=teams):
roles[team_index[x.team.id]] = "%s%s" % \
(x.status == 'Prospective' and "Prospective " or "",
x.role)
cell = ""
home = ""
for phone in result.phones_all:
if phone.location == 'Mobile':
cell = phone.render_normal()
elif phone.location == 'Home':
home = phone.render_normal()
final_results.append(dict(name=name, roles=roles, cell=cell,
home=home))
teams = Team.objects.filter(id__in=teams).order_by('id')
else:
form = PhoneListForm()
return render_to_response("roster/phone_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def tshirt_list(request):
"""Team T-shirt list."""
if request.method == 'GET' and request.GET:
form = TshirtListForm(request.GET)
if form.is_valid():
who = set(form.data.getlist('who'))
include_parents = 'Parent' in who
who.discard('Parent')
people = PersonTeam.objects.filter(role__in=who,
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
results = Person.objects.filter(id__in=people)
# Follow relationship to parents from students if enabled.
if include_parents:
parent_relationships = RelationshipType.objects.filter(parent=True).values('id')
students = PersonTeam.objects.filter(role='Student',
status__in=form.data.getlist('status'),
team__in=form.data.getlist('team')).values('person')
parents = Relationship.objects.filter(person_from__in=students,
relationship__in=parent_relationships).values('person_to')
results |= Person.objects.filter(id__in=parents)
totals_dict = {}
for tot in results.values('shirt_size').annotate(Count('shirt_size')).order_by():
totals_dict[tot["shirt_size"]] = tot["shirt_size__count"]
totals = []
if "" in totals_dict:
totals.append(dict(shirt_size="",
shirt_size__count=totals_dict[""]))
for size_short, size_long in Person.SHIRT_SIZE_CHOICES:
if size_short not in totals_dict:
continue
totals.append(dict(shirt_size=size_long,
shirt_size__count=totals_dict[size_short]))
else:
form = TshirtListForm()
return render_to_response("roster/tshirt_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def hours_list(request):
"""Team hours list."""
if request.method == 'GET' and request.GET:
form = HoursListForm(request.GET)
if form.is_valid():
who = set(form.data.getlist('who'))
people = PersonTeam.objects.filter(role__in=who,
status='Active',
team__in=form.data.getlist('team')).values('person')
results = Person.objects.filter(id__in=people)
from_date = form.cleaned_data.get('from_date', None)
to_date = form.cleaned_data.get('to_date', None)
if from_date and to_date:
results = results.filter(timerecord__clock_in__range=(from_date, to_date))
elif from_date:
results = results.filter(timerecord__clock_in__gt=from_date)
elif to_date:
results = results.filter(timerecord__clock_in__lt=to_date)
results = results.annotate(total_hours=Sum('timerecord__hours')).order_by('-total_hours')
total = sum((x.total_hours or 0.0) for x in results)
show_hours = 'include_hours' in form.data
else:
form = HoursListForm()
return render_to_response("roster/hours_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def event_email_list(request):
"""Event email list."""
if request.method == 'GET' and request.GET:
form = EventEmailListForm(request.GET)
if form.is_valid():
people = EventPerson.objects.filter(
event=form.cleaned_data['event'],
role__in=form.cleaned_data['who']).values('person')
results = PersonEmail.objects.filter(primary=True, person__in=people)
# CC parents on emails if enabled. Only does one level
# (so if a parent has a CC on email, it won't get followed).
if people and 'cc_on_email' in form.data:
cc = Relationship.objects.filter(person_from__in=people,
cc_on_email=True).values('person_to')
results |= PersonEmail.objects.filter(primary=True, person__in=cc)
# Uniquify and get related info to avoid additional queries
results = results.select_related('person', 'email.email').distinct()
include_name = 'include_name' in form.data
separator = form.data['separator']
else:
form = EventEmailListForm()
return render_to_response("roster/email_list.html", locals(),
context_instance=RequestContext(request))
@login_required(login_url='/roster/login/')
def class_team_list(request):
"""List of people showing their team membership."""
if request.method == 'GET' and request.GET:
form = ClassTeamListForm(request.GET)
if form.is_valid():
results = Person.objects.filter(
grad_year__gte=form.data["class_begin"],
grad_year__lte=form.data["class_end"])
exclude_people = PersonTeam.objects\
.filter(person__in=results.values('id'))\
.exclude(status__in=('Active', 'Prospective'))\
.values('person')
results = results.exclude(id__in=exclude_people)
if 'no_team' in form.data:
exclude_people = PersonTeam.objects\
.filter(person__in=results.values('id'))\
.values('person')
results = results.exclude(id__in=exclude_people)
else:
form = ClassTeamListForm()
return render_to_response("roster/class_team_list.html", locals(),
context_instance=RequestContext(request))
class Checkbox(Flowable):
"""A checkbox flowable."""
def __init__(self, checked, size=0.25*inch, color=colors.black):
self.checked = checked
self.size = size
def wrap(self, *args):
return (0, self.size)
def draw(self):
canvas = self.canv
canvas.setLineWidth(1)
canvas.setStrokeColor(self.color)
canvas.rect(0, 0, self.size, self.size)
if self.checked:
canvas.line(0, 0, self.size, self.size)
canvas.line(0, self.size, self.size, 0)
class StartPerson(ActionFlowable):
def __init__(self, id, firstname, lastname, suffix, adult, team):
ActionFlowable.__init__(self, ('startPerson', id, firstname,
lastname, suffix, adult, team))
class RegVerifyDocTemplate(BaseDocTemplate):
_invalidInitArgs = ('pageTemplates')
def afterInit(self):
self.name = None
self.id = None
self.team = None
self.adult = False
frame = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal')
self.addPageTemplates([PageTemplate(id='First',frames=frame,onPageEnd=self.afterFirstPage,pagesize=self.pagesize),
PageTemplate(id='Later',frames=frame,onPageEnd=self.afterNextPage,pagesize=self.pagesize)])
def afterFirstPage(self, canv, self2):
#self.pageTemplate = self.pageTemplates[1]
# Name in upper left corner
canv.setFont("Calibri-Bold", 14)
canv.setFillColor(colors.black)
canv.drawString(0.5*inch, self.pagesize[1]-0.5*inch, self.name)
# Box with first letter of last name in upper right corner
# Color it based on adult
wh = 0.375*inch
c = (self.pagesize[0]-0.75*inch, self.pagesize[1]-0.5*inch)
canv.setFillColor(self.adult and team_color2 or team_color1)
canv.rect(c[0]-wh/2, c[1]-wh/2,
wh, wh, fill=1, stroke=0)
lsize = 30
canv.setFillColor(colors.black)
canv.setFont("Calibri-Bold", lsize)
canv.drawCentredString(c[0], c[1]-lsize/2/1.4, self.name[0].upper())
# Admin fields
canv.setStrokeColor(colors.black)
canv.setFillColor(colors.black)
canv.setLineWidth(1)
title = "Administration Only"
title_width = canv.stringWidth(title, "Calibri-Italic", 8)
canv.line(0.5*inch, 0.7*inch,
self.pagesize[0]/2-title_width/2, 0.7*inch)
canv.line(self.pagesize[0]/2+title_width/2, 0.7*inch,
self.pagesize[0]-0.5*inch, 0.7*inch)
#canv.line(0.5*inch, 0.7*inch, self.pagesize[0]-0.5*inch, 0.7*inch)
canv.setFont("Calibri-Italic", 8)
canv.drawCentredString(self.pagesize[0]/2, 0.675*inch, title)
canv.setFont("Calibri", 8)
canv.setLineWidth(0.5)
for r, c, sw, vw, s, v in \
[(0, 0, 0.75, 0.5, "Id:", "%d" % self.id),
(1, 0, 0.75, 0.5, "Printed On:",
self.today.strftime("%b %-d, %Y")),
(0, 1, 0.75, 0.5, "Cash/Check #", None),
(1, 1, 0.75, 0.5, "Amount:", None),
(0, 2, 0.75, 0.5, "Team:", self.team),
(1, 2, 0.75, 0.5, "Paid Date:", None),
(0, 3, 1, 0.25, "Release Form:", None),
(1, 3, 1, 0.25, "Student Contract:", None)]:
x = 0.5*inch + c*2*inch
y = 0.5*inch - r*0.125*inch
canv.drawString(x, y, s)
if v is None:
canv.line(x+sw*inch, y, x+(sw+vw)*inch, y)
else:
canv.drawString(x+sw*inch, y, v)
def afterNextPage(self, canv, self2):
pass
def handle_startPerson(self, id, firstname, lastname, suffix, adult,
team):
#self.pageTemplate = self.pageTemplates[0]
self.name = "%s, %s %s" % (lastname, firstname, suffix)
self.id = id
self.adult = adult
self.team = team
def person_to_pdf(elements, person, title, adult=False, parent=None,
contact=None):
base_style = [
# default font and text color for table
('FONT', (0,0), (-1,-1), 'Calibri', 8),
('TEXTCOLOR', (0,0), (-1,-1), colors.black),
# default to top alignment for table
('VALIGN', (0,0), (-1,-1), 'TOP'),
# reduce padding for table
('TOPPADDING', (0,0), (-1,-1), 2),
('BOTTOMPADDING', (0,0), (-1,-1), 2),
# bold first column
('FONT', (0,0), (0,-1), 'Calibri-Bold', 8),
# set up header row
('BACKGROUND', (0,0), (-1,0), team_color1),
('TEXTCOLOR', (0,0), (-1,0), colors.white),
('SPAN', (0,0), (-1,0)),
# lines around the table, between each row, and between cols 2 and 3
('BOX', (0,0), (-1,-1), 1, colors.black),
('LINEBELOW', (0,0), (-1,-1), 1, colors.black),
('LINEAFTER', (1,1), (1,-1), 1, colors.black),
]
if person:
empty_person = False
def highlight(style, data):
style.add('BACKGROUND', (2,len(data)), (2,len(data)), colors.yellow)
else:
empty_person = True
def highlight(style, data):
pass
person = Person()
data = []
style = TableStyle(base_style)
# Basic information
data.append((title, "", ""))
data.append(((parent or contact) and "Name" or "Legal Name",
"First and Last",
"%s %s %s" % (person.firstname, person.lastname, person.suffix)))
if isinstance(contact, Relationship):
style.add('SPAN', (0,len(data)-1), (0,len(data)))
data.append(("", "Relationship", contact.relationship))
elif contact or (parent and not isinstance(parent, Relationship)):
style.add('SPAN', (0,len(data)-1), (0,len(data)))
data.append(("", "Relationship", ""))
if not parent and not contact:
data.append(("Nickname", "", person.nickname))
if not person.gender or person.gender == 'U':
highlight(style, data)
data.append(("Gender", "", person.get_gender_display()))
if not person.birth_month or not person.birth_day or person.birth_year is not None and (person.birth_year > 2050 or person.birth_year < 1900):
highlight(style, data)
data.append(("Date of Birth", "m/d/yyyy", not empty_person and
"%s / %s / %s" % (person.birth_month, person.birth_day, person.birth_year) or ""))
# - School
if not adult:
if not person.school:
highlight(style, data)
data.append(("School", "", person.school))
if not person.grad_year:
highlight(style, data)
data.append(("HS Graduation Year", "", person.grad_year))
if not contact:
# - Company
if adult and not person.company:
highlight(style, data)
data.append(("Company", "", person.company))
# - Shirt Size
if not parent:
if not person.shirt_size:
highlight(style, data)
data.append(("Shirt Size", "", person.shirt_size))
# Parent specific info
#if isinstance(parent, Relationship):
# data.append(("Emergency Contact", "",
# parent.emergency_contact and "Yes" or "No"))
#elif parent:
# data.append(("Emergency Contact", "", "Yes / No"))
# Emails
emails = PersonEmail.objects.filter(person=person)
start = len(data)
first = "Email"
for email in emails:
data.append((first, email.email.location, "%s%s" %
(email.email.email, email.primary and " (primary)" or "")))
first = ""
if not emails:
data.append((first, "Address", ""))
first = ""
# - Parent specific info
if isinstance(parent, Relationship):
data.append((first, "CC on Student Emails",
parent.cc_on_email and "Yes" or "No"))
first = ""
elif parent:
data.append((first, "CC on Student Emails", "Yes / No"))
first = ""
if len(data)-1 > start:
style.add('SPAN', (0,start), (0,len(data)-1))
# Phones
phones = PersonPhone.objects.filter(person=person)
wanted_phone_locations = set([u'Cell', u'Home', u'Work'])
start = len(data)
first = "Phone"
for phone in phones:
location = phone.phone.get_location_display()
wanted_phone_locations.discard(location)
data.append((first, location, "%s%s" %
(phone.phone.render_normal(),
phone.primary and " (primary)" or "")))
first = ""
for location in sorted(wanted_phone_locations):
#highlight(style, data)
data.append((first, location, ""))
first = ""
if len(data)-1 > start:
style.add('SPAN', (0,start), (0,len(data)-1))
if not contact:
# Addresses
addresses = not empty_person and person.addresses.all() or []
for address in addresses:
style.add('SPAN', (0,len(data)), (0,len(data)+2))
data.append(("Address", "Line 1", address.line1))
data.append(("", "Line 2", address.line2))
data.append(("", "City, State, Zip", "%s, %s %s" %
(address.city, address.state, address.zipcode)))
if not addresses:
style.add('SPAN', (0,len(data)), (0,len(data)+2))
highlight(style, data)
data.append(("Address", "Line 1", ""))
highlight(style, data)
data.append(("", "Line 2", ""))
highlight(style, data)
data.append(("", "City, State, Zip", ""))
# Medical
if not parent:
style.add('SPAN', (0,len(data)), (0,len(data)+1))
#if not person.medical:
# highlight(style, data)
data.append(("Medical", "Conditions/Allergies", person.medical))
#if not person.medications:
# highlight(style, data)
data.append(("", "Medications", person.medications))
elements.append(Table(data, colWidths=(0.75*inch, 1.25*inch, 5*inch),
style=style))
def make_reg_verify_pdf(response, people):
from datetime import date
today = date.today()
doc = RegVerifyDocTemplate(response,
pagesize=letter,
allowSplitting=0,
leftMargin=0.5*inch,
rightMargin=0.5*inch,
topMargin=0.75*inch,
bottomMargin=0.75*inch,
title="Team Registration Verification",
author="Beach Cities Robotics")
doc.today = today
# container for the 'Flowable' objects
elements = []
styles = getSampleStyleSheet()
normal_para_style = styles['Normal']
parent_relationships = RelationshipType.objects.filter(parent=True).values_list('id', flat=True)
for person in people:
adult = person.company or \
(person.birth_year and person.birth_year > 1900 and
(today.year - person.birth_year) > 20)
team = None
pts = PersonTeam.objects.filter(person=person, status='Active')
if pts:
team = "%s" % pts[0].team
elements.append(StartPerson(person.id, person.firstname,
person.lastname, person.suffix, adult,
team))
person_to_pdf(elements, person,
"%s Information" % (adult and "Mentor" or "Student"),
adult=adult)
elements.append(Paragraph("", normal_para_style))
parents = []
if not adult:
# Parents
parents = Relationship.objects.filter(
person_from=person,
legal_guardian=True) \
.select_related('person_to')
extra_parents = [1, 2]
for parent in parents:
person_to_pdf(elements, parent.person_to,
"%s's Information" % parent.relationship,
adult=True,
parent=parent)
elements.append(Paragraph("", normal_para_style))
for parent in extra_parents[len(parents):]:
person_to_pdf(elements, None,
"Legal Guardian %d Information" % parent,
adult=True,
parent=True)
elements.append(Paragraph("", normal_para_style))
parents = parents.values('id')
# Emergency Contacts
if adult:
contacts = Relationship.objects.filter(
person_from=person, emergency_contact=True) \
.exclude(id__in=parents) \
.select_related('person_to')
for contact in contacts:
person_to_pdf(elements, contact.person_to,
"Emergency Contact Information",
adult=True,
contact=contact)
elements.append(Paragraph("", normal_para_style))
if not contacts:
person_to_pdf(elements, None,
"Emergency Contact Information",
adult=True,
contact=True)
elements.append(PageBreak())
# Generate the document
doc.build(elements)
@login_required(login_url='/roster/login/')
def team_reg_verify(request):
"""Team registration verification."""
if request.method != 'GET' or not request.GET:
form = TeamRegVerifyForm()
return render_to_response("roster/team_reg_verify.html", locals(),
context_instance=RequestContext(request))
form = TeamRegVerifyForm(request.GET)
if not form.is_valid():
return render_to_response("roster/team_reg_verify.html", locals(),
context_instance=RequestContext(request))
# configure PDF output
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=TeamRegVerify.pdf'
people = PersonTeam.objects.filter(
role__in=form.data.getlist('who'),
status='Active',
team__in=form.data.getlist('team')).values('person')
people = Person.objects.filter(id__in=people)
make_reg_verify_pdf(response, people)
return response
@login_required(login_url='/roster/login/')
def signin_person_list(request):
"""Basic easy to parse list of people for signin application."""
parent_relationships = RelationshipType.objects.filter(parent=True).values_list('id', flat=True)
people = PersonTeam.objects.filter(status='Active').values('person')
results = Person.objects.all()#filter(id__in=people)
#results = results.distinct()
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=signin_person_list.csv'
writer = csv.writer(response)
writer.writerow(['id', 'name', 'student', 'photo', 'photo size', 'badge'])
for person in results:
name = person.render_normal()
student = person.is_student(parent_relationships)
# Default to adult if we can't figure out if this is a student or not.
if student is None:
student = False
photourl = ''
photosize = 0
if person.photo:
photourl = person.photo.url
photosize = person.photo.file.size
writer.writerow([person.id, name, student, photourl, photosize, person.get_badge()])
return response
@login_required(login_url='/roster/login/')
@csrf_exempt
@transaction.commit_on_success
def time_record_bulk_add(request):
"""Bulk time record entry for signin application."""
from datetime import datetime
def fromiso(t):
try:
return datetime.strptime(t, "%Y-%m-%d %H:%M:%S.%f")
except:
return datetime.strptime(t, "%Y-%m-%d %H:%M:%S")
errs = []
ok = []
for count, row in enumerate(csv.DictReader(request)):
try:
person = Person.objects.get(id=int(row["person"]))
event = row.get("event", None)
if event:
event = Event.objects.get(id=int(event))
else:
event = None
record = TimeRecord(
person=person,
event=event,
clock_in=fromiso(row["clock_in"]),
clock_out=fromiso(row["clock_out"]),
hours=float(row["hours"]),
recorded=fromiso(row["recorded"]),
)
record.save()
ok.append(count)
except Exception as e:
errs.append("%d (%s): %s" % (count, row.get("person", ""), str(e)))
return HttpResponse(str(ok)+"\n"+"\n".join(errs), content_type="text/plain")
class Badge(Flowable):
"""A badge flowable."""
# badge dimensions
width = 2.25*inch
height = 3.5*inch
# border thickness
border_size = 0.125*inch
# logo location and size
logo = 0
logo_width = 0.5*inch
logo_height = 0.75*inch
logo_x = width - logo_width - 0.125*inch
logo_y = height - logo_height - 0.125*inch
# team name location and size
team_font = 'Calibri-Bold'
team_fontsize = 18
team_x = width / 2.0
team_y = (1/16.0)*inch
team_name = "Beach Cities Robotics"
# photo location and size
photo_width = 1.25*inch
photo_height = 1.5*inch
photo_x = (1/16.0)*inch
photo_y = height - photo_height - (3/16.0)*inch
photo_corner = 0.125*inch # rounded corner radius
# name location and size
fullname_font = 'Calibri'
fullname_fontsize = 10
fullname_x = 0.125*inch
fullname_y = photo_y - 0.125*inch
firstname_font = 'Calibri-Bold'
firstname_fontsize = 24
firstname_x = 0.125*inch
firstname_y = fullname_y - 0.3*inch
# position location and size
position_font = 'Calibri'
position_fontsize = 14
position_x = 0.125*inch
position_y = 1*inch
position_width = width - position_x - 0.125*inch
position_height = 0.5*inch
# id font
id_font = 'Calibri'
id_fontsize = 8
# barcode location and size
barcode_x = 0
barcode_y = 0.375*inch
def __init__(self, person, student):
self.styles = getSampleStyleSheet()
self.person = person
self.student = student
def wrap(self, *args):
return (0, self.height)
def draw(self):
canvas = self.canv
canvas.saveState()
canvas.setLineWidth(1)
canvas.setStrokeColor(colors.black)
canvas.setFillColor(colors.black)
# clip to badge boundary
p = canvas.beginPath()
p.rect(0, 0, self.width, self.height)
canvas.clipPath(p)
# Badge outline / background
canvas.saveState()
if self.student:
color1 = team_color2
color2 = team_color1
else:
color1 = team_color1
color2 = team_color2
canvas.radialGradient(0, 0,
math.sqrt(self.width*self.width+self.height*self.height),
[colors.white, color1], [0.10, 1])
canvas.setFillColor(color2)
canvas.rect(0, 0, self.width, 0.3*inch, stroke=0, fill=1)
canvas.drawPath(p)
canvas.restoreState()
# Team logo
if self.logo:
canvas.drawImage(os.path.join(MEDIA_ROOT, "logo.jpeg"),
self.logo_x, self.logo_y, self.logo_width, self.logo_height,
preserveAspectRatio=True)
# Team name
canvas.saveState()
canvas.setFillColor(colors.black)
canvas.setFont(self.team_font, self.team_fontsize)
canvas.drawCentredString(self.team_x, self.team_y, self.team_name)
canvas.restoreState()
# Photo
if self.person.photo:
# round corners by using a clip path
canvas.saveState()
p = canvas.beginPath()
p.roundRect(self.photo_x, self.photo_y, self.photo_width,
self.photo_height, self.photo_corner)
canvas.clipPath(p, stroke=0)
# load image
photopath = os.path.join(MEDIA_ROOT, self.person.photo.name)
img = ImageReader(photopath)
# scale/center image so it fills entire area
imgw, imgh = img.getSize()
newimgw, newimgh = imgw, imgh
rw = int(imgh * self.photo_width / self.photo_height)
if rw <= imgw:
newimgw = rw
else:
newimgh = int(imgw * self.photo_height / self.photo_width)
width = self.photo_width*((1.0*imgw)/newimgw)
height = self.photo_height*((1.0*imgh)/newimgh)
x = self.photo_x - (width-self.photo_width)/2.0
y = self.photo_y - (height-self.photo_height)/2.0
# draw image
canvas.drawImage(img, x, y, width, height)
# restore state (clip path)
canvas.restoreState()
else:
canvas.saveState()
canvas.setFillColor(colors.white)
canvas.roundRect(self.photo_x, self.photo_y, self.photo_width,
self.photo_height, self.photo_corner, stroke=1, fill=1)
canvas.restoreState()
# Name
canvas.saveState()
fullname = "%s, %s %s" % (self.person.lastname, self.person.firstname, self.person.suffix)
canvas.setFont(self.fullname_font, self.fullname_fontsize)
canvas.drawString(self.fullname_x, self.fullname_y, fullname)
canvas.restoreState()
canvas.saveState()
canvas.setFont(self.firstname_font, self.firstname_fontsize)
canvas.drawString(self.firstname_x, self.firstname_y, self.person.get_firstname())
canvas.restoreState()
# Position
position = str(self.person.position)
if not position:
if self.student:
position = "Student"
else:
position = "Mentor"
t = '<font name="%s" size="%d">%s</font>' % \
(self.position_font, self.position_fontsize, escape(position))
p = Paragraph(t, style=self.styles['Normal'])
p.wrapOn(canvas, self.position_width, self.position_height)
p.drawOn(canvas, self.position_x, self.position_y)
# Barcode
idstr = "B%05d" % self.person.get_badge()
canvas.saveState()
barcode = code39.Standard39(idstr, humanReadable=0, checksum=1)
canvas.setFillColor(colors.black)
barcode.drawOn(canvas, self.barcode_x, self.barcode_y)
canvas.restoreState()
# ID
idstr = "%d" % self.person.get_badge()
canvas.saveState()
canvas.setFont(self.id_font, self.id_fontsize)