-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.py
executable file
·2336 lines (2223 loc) · 84 KB
/
admin.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
#!/usr/bin/env python
import os
import re
import quopri
import cgi
import logging
import webapp2
import datetime
import hashlib
import json
from google.appengine.ext import ndb
from google.appengine.api import users, memcache, images, mail
from django.template.loaders.filesystem import Loader
from django.template.loader import render_to_string
import tournament
import payments
import capabilities
import sponsorship
import auctionitem
import detailpage
import uploadedfile
import tz
import auditing
from sponsor import Sponsor, Team, Golfer, Substitute, DinnerGuest, TributeAd, get_handicap_index
server_software = os.environ.get('SERVER_SOFTWARE')
dev_server = True if server_software and server_software.startswith("Development") else False
# Logout
def show_login_page(out, redirect_url):
email = None
user = users.get_current_user()
if user:
email = user.email()
logging.info("User %s (%s) does not have required capability" % (email, user.nickname()))
template_values = {
'email': email,
'login_url': users.create_login_url(redirect_url),
'logout_url': users.create_logout_url(redirect_url)
}
out.write(render_to_string('login.html', template_values))
class Logout(webapp2.RequestHandler):
def get(self):
self.redirect(users.create_logout_url('/'))
# Users who can update parts of the site.
def make_bitmask(*caps):
bitmask = 0
for cap in caps:
bitmask = bitmask << 1
if cap:
bitmask = bitmask | 1
return bitmask
class ManageUsers(webapp2.RequestHandler):
# Show the form.
def get(self):
if not users.is_current_user_admin():
show_login_page(self.response.out, self.request.uri)
return
caps = capabilities.get_current_user_caps()
q = capabilities.all_caps()
q = q.order(capabilities.Capabilities.email)
allcaps = q.fetch(30)
for u in allcaps:
u.capbits = make_bitmask(u.can_update_sponsorships,
u.can_view_registrations,
u.can_add_registrations,
u.can_update_auction,
u.can_edit_content,
u.can_edit_tournament_properties,
u.can_edit_payment_processor)
template_values = {
'capabilities': caps,
'allcaps': allcaps
}
self.response.out.write(render_to_string('users.html', template_values))
# Process the submitted info.
def post(self):
if not users.is_current_user_admin():
show_login_page(self.response.out, '/admin/users')
return
count = int(self.request.get('count'))
updated_records = [ ]
for i in range(1, count + 1):
email = self.request.get('email%d' % i)
us = True if self.request.get('us%d' % i) == 'u' else False
vr = True if self.request.get('vr%d' % i) == 'v' else False
ar = True if self.request.get('ar%d' % i) == 'a' else False
ua = True if self.request.get('ua%d' % i) == 'u' else False
ec = True if self.request.get('ec%d' % i) == 'e' else False
et = True if self.request.get('et%d' % i) == 't' else False
pp = True if self.request.get('pp%d' % i) == 'p' else False
orig_capbits = int(self.request.get('capbits%d' % i))
new_capbits = make_bitmask(us, vr, ar, ua, ec, et, pp)
if orig_capbits != new_capbits:
u = capabilities.get_caps(email)
logging.info("updating user %s: orig caps %02x new caps %02x" % (email, orig_capbits, new_capbits))
if u.email is None:
logging.error("user %d not found" % email)
else:
u.can_update_sponsorships = us
u.can_view_registrations = vr
u.can_add_registrations = ar
u.can_update_auction = ua
u.can_edit_content = ec
u.can_edit_tournament_properties = et
u.can_edit_payment_processor = pp
updated_records.append(u)
u.audit()
if updated_records:
ndb.put_multi(updated_records)
email = self.request.get('email')
if email:
us = True if self.request.get('us') == 'u' else False
vr = True if self.request.get('vr') == 'v' else False
ar = True if self.request.get('ar') == 'a' else False
ua = True if self.request.get('ua') == 'u' else False
ec = True if self.request.get('ec') == 'e' else False
et = True if self.request.get('et') == 't' else False
pp = True if self.request.get('pp') == 'p' else False
new_capbits = make_bitmask(us, vr, ar, ua, ec, et, pp)
logging.info("adding user %s: caps %02x" % (email, new_capbits))
capabilities.add_user(email = email,
can_update_sponsorships = us,
can_view_registrations = vr,
can_add_registrations = ar,
can_update_auction = ua,
can_edit_content = ec,
can_edit_tournament_properties = et,
can_edit_payment_processor = pp)
memcache.flush_all()
self.redirect('/admin/users')
def reinitialize_counters(t):
counters = tournament.get_counters(t)
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
q = q.order(Sponsor.timestamp)
num_golfers = 0
num_dinners = 0
for s in q:
num_golfers += s.num_golfers + s.num_golfers_no_dinner
num_dinners += s.num_golfers + s.num_dinners
counters.golfer_count = num_golfers
counters.dinner_count = num_dinners
counters.put()
logging.info("updated golfer_count = %d, dinner_count = %d" % (num_golfers, num_dinners))
# Tournament properties
class ManageTournament(webapp2.RequestHandler):
# Show the form.
def get(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_edit_tournament_properties:
show_login_page(self.response.out, self.request.uri)
return
t = tournament.get_tournament(self.request.get("t"))
if t.dinner_early_bird_deadline is None:
t.dinner_early_bird_deadline = t.early_bird_deadline
counters = tournament.get_counters(t)
template_values = {
'capabilities': caps,
'tournament': t,
'counters': counters
}
self.response.out.write(render_to_string('tournament.html', template_values))
# Process the submitted info.
def post(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_edit_tournament_properties:
show_login_page(self.response.out, '/admin/tournament')
return
t = tournament.get_tournament(self.request.get("original_name"))
if self.request.get("num_golfers") == "" or self.request.get("num_dinners") == "":
reinitialize_counters(t)
t.name = self.request.get("new_name")
t.published = (self.request.get("published") == "y")
t.accepting_registrations = (self.request.get("accepting") == "y")
golf_month = int(self.request.get("golf_month"))
golf_day = int(self.request.get("golf_day"))
golf_year = int(self.request.get("golf_year"))
t.golf_date = datetime.date(golf_year, golf_month, golf_day)
dinner_month = int(self.request.get("dinner_month"))
dinner_day = int(self.request.get("dinner_day"))
dinner_year = int(self.request.get("dinner_year"))
t.dinner_date = datetime.date(dinner_year, dinner_month, dinner_day)
early_bird_month = int(self.request.get("early_bird_month"))
early_bird_day = int(self.request.get("early_bird_day"))
early_bird_year = int(self.request.get("early_bird_year"))
t.early_bird_deadline = datetime.date(early_bird_year, early_bird_month, early_bird_day)
dinner_early_bird_month = int(self.request.get("dinner_early_bird_month"))
dinner_early_bird_day = int(self.request.get("dinner_early_bird_day"))
dinner_early_bird_year = int(self.request.get("dinner_early_bird_year"))
t.dinner_early_bird_deadline = datetime.date(dinner_early_bird_year, dinner_early_bird_month, dinner_early_bird_day)
deadline_month = int(self.request.get("deadline_month"))
deadline_day = int(self.request.get("deadline_day"))
deadline_year = int(self.request.get("deadline_year"))
t.deadline = datetime.date(deadline_year, deadline_month, deadline_day)
tribute_deadline_month = int(self.request.get("tribute_deadline_month"))
tribute_deadline_day = int(self.request.get("tribute_deadline_day"))
tribute_deadline_year = int(self.request.get("tribute_deadline_year"))
t.tribute_deadline = datetime.date(tribute_deadline_year, tribute_deadline_month, tribute_deadline_day)
t.golf_price_early = int(self.request.get("golf_price_early"))
t.golf_price_late = int(self.request.get("golf_price_late"))
t.golf_only_price_early = int(self.request.get("golf_only_price_early"))
t.golf_only_price_late = int(self.request.get("golf_only_price_late"))
t.dinner_price_early = int(self.request.get("dinner_price_early"))
t.dinner_price_late = int(self.request.get("dinner_price_late"))
t.limit_golfers = int(self.request.get("limit_golfers"))
t.limit_dinners = int(self.request.get("limit_dinners"))
t.golf_sold_out = (self.request.get("golf_sold_out") == "y")
t.dinner_sold_out = (self.request.get("dinner_sold_out") == "y")
t.wait_list_email = self.request.get("wait_list_email")
t.dinner_choices = self.request.get("dinner_choices")
t.go_discount_codes = self.request.get("go_discount_codes")
t.red_course_rating = float(self.request.get("red_course_rating"))
t.red_course_slope = float(self.request.get("red_course_slope"))
t.white_course_rating = float(self.request.get("white_course_rating"))
t.white_course_slope = float(self.request.get("white_course_slope"))
t.blue_course_rating = float(self.request.get("blue_course_rating"))
t.blue_course_slope = float(self.request.get("blue_course_slope"))
t.put()
tournament.set_tournament_cache(t)
auditing.audit(t, "Updated tournament properties", request = self.request)
self.redirect('/admin/tournament')
# Payment Gateway
class PaymentGateway(webapp2.RequestHandler):
# Show the form.
def get(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_edit_payment_processor:
show_login_page(self.response.out, self.request.uri)
return
t = tournament.get_tournament()
payments_info = payments.get_payments_info(t)
template_values = {
'capabilities': caps,
'payments': payments_info
}
self.response.out.write(render_to_string('payments.html', template_values))
# Process the submitted info.
def post(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_edit_payment_processor:
show_login_page(self.response.out, self.request.uri)
return
t = tournament.get_tournament()
payment_gateway = payments.Payments.query(ancestor = t.key).get()
if payment_gateway is None:
payment_gateway = payments.Payments(parent = t.key)
payment_gateway.gateway_url = self.request.get("gateway_url")
payment_gateway.relay_url = self.request.get("relay_url")
payment_gateway.receipt_url = self.request.get("receipt_url")
payment_gateway.api_login_id = self.request.get("api_login_id")
payment_gateway.transaction_key = self.request.get("transaction_key")
payment_gateway.test_mode = self.request.get("test_mode") == "true"
payment_gateway.put()
auditing.audit(t, "Updated payment gateway", request = self.request)
self.redirect('/admin/payments')
# Sponsorship information.
class Sponsorships(webapp2.RequestHandler):
# Show the form.
def get(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_update_sponsorships:
show_login_page(self.response.out, self.request.uri)
return
t = tournament.get_tournament()
sponsorships = sponsorship.Sponsorship.query(ancestor = t.key).order(sponsorship.Sponsorship.sequence).fetch(30)
next_seq = 1
last_level = "Double Eagle"
for s in sponsorships:
next_seq = s.sequence + 1
last_level = s.level
template_values = {
'capabilities': caps,
'next_seq': next_seq,
'last_level': last_level,
'sponsorships': sponsorships
}
self.response.out.write(render_to_string('sponsorships.html', template_values))
# Process the submitted info.
def post(self):
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_update_sponsorships:
show_login_page(self.response.out, '/admin/sponsorships')
return
t = tournament.get_tournament()
sponsorship.clear_sponsorships_cache()
count = int(self.request.get('count'))
for i in range(1, count + 1):
name = self.request.get('name%d' % i)
q = sponsorship.Sponsorship.query(ancestor = t.key)
q = q.filter(sponsorship.Sponsorship.name == name)
s = q.get()
if self.request.get('delete%d' % i) == 'd':
auditing.audit(t, "Deleted Sponsorship", data = s.level + "/" + s.name, request = self.request)
s.key.delete()
else:
try:
price = int(self.request.get('price%s' % i))
except:
price = s.price
try:
golfers_included = int(self.request.get('golfers_included%d' % i))
except:
golfers_included = s.golfers_included
unique = True if self.request.get('unique%d' % i) == 'u' else False
sold = True if self.request.get('sold%d' % i) == 's' else False
if price != s.price or golfers_included != s.golfers_included or unique != s.unique or sold != s.sold:
s.price = price
s.golfers_included = golfers_included
s.unique = unique
s.sold = sold
s.put()
auditing.audit(t, "Updated Sponsorship", data = s.level + "/" + name, request = self.request)
name = self.request.get('name')
level = self.request.get('level')
sequence = self.request.get('seq')
price = self.request.get('price')
golfers_included = self.request.get('golfers_included')
if golfers_included is None:
golfers_included = 1
unique = True if self.request.get('unique') == 'u' else False
sold = True if self.request.get('sold') == 's' else False
if name and sequence and price:
s = sponsorship.Sponsorship(parent = t.key,
name = name,
level = level,
sequence = int(sequence),
price = int(price),
golfers_included = int(golfers_included),
unique = unique,
sold = sold)
s.put()
auditing.audit(t, "Added Sponsorship", data = level + "/" + name, request = self.request)
self.redirect('/admin/sponsorships')
def get_tees(flight, gender):
if gender == "F":
return 1 # Red
if flight == 2:
return 3 # Blue
return 2 # White
def calc_course_handicap(tournament, handicap_index, tees):
slope = [tournament.red_course_slope, tournament.white_course_slope, tournament.blue_course_slope][tees - 1]
return min(36, int(round(handicap_index * slope / 113.0)))
class ViewGolfer(object):
def __init__(self, t, s, g, count):
self.golfer_key = g.key.urlsafe()
if s:
self.sponsor_id = s.sponsor_id
self.sponsor_name = s.first_name + " " + s.last_name
if g.substitute:
g1 = g.substitute.get()
self.has_substitute = True
else:
g1 = g
self.has_substitute = False
self.golfer = g1
self.sequence = g.sequence
team = None
if g.team:
team = g.team.get()
if g1.first_name or g1.last_name:
self.golfer_name = g1.first_name + " " + g1.last_name
if self.has_substitute:
self.golfer_name = "*" + self.golfer_name
elif s:
self.golfer_name = "(%s #%d)" % (s.last_name, g.sequence)
else:
self.golfer_name = "(TBD)"
self.count = count
if s:
self.pairing = s.pairing if g.sequence == s.num_golfers + s.num_golfers_no_dinner else '' # TODO: remove this
self.team_name = team.name if team else '-'
self.starting_hole = team.starting_hole if team else ''
self.cart = g.cart
if g1.tees:
self.tees = g1.tees
else:
flight = 1
if team:
flight = team.flight
self.tees = get_tees(flight, g1.gender)
handicap_index = get_handicap_index(g1)
if g1.has_index:
self.handicap_index_str = "%.1f" % handicap_index
self.computed_index = ''
self.course_handicap = calc_course_handicap(t, handicap_index, self.tees)
elif handicap_index is not None:
self.handicap_index_str = ''
self.computed_index = "%.1f" % handicap_index
self.course_handicap = calc_course_handicap(t, handicap_index, self.tees)
else:
self.handicap_index_str = ''
self.computed_index = ''
self.course_handicap = 'n/a'
class ViewDinner(object):
def __init__(self, s, first_name, last_name, choice, sequence, table_num, count):
self.sponsor_id = s.sponsor_id
self.sponsor_name = s.first_name + " " + s.last_name
if first_name or last_name:
self.guest_name = first_name + " " + last_name
else:
self.guest_name = "(%s #%d)" % (s.last_name, sequence)
self.dinner_choice = choice
self.sequence = sequence
self.count = count
self.table_num = str(table_num) if table_num > 0 else ""
self.seating = s.dinner_seating if sequence == s.num_golfers + s.num_dinners else ''
class ViewRegistrations(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
if self.request.get('sort') == 'date':
q = q.order(Sponsor.timestamp)
else:
q = q.order(Sponsor.sort_name)
sponsors = q.fetch(limit = None)
golfer_count = 0
dinner_count = 0
for s in sponsors:
no_dinners = 0
total_golfers = s.num_golfers + s.num_golfers_no_dinner
if total_golfers:
golfers = ndb.get_multi(s.golfer_keys[:total_golfers])
for g in golfers:
if g.dinner_choice == 'none':
no_dinners += 1
s.total_golfers = total_golfers
s.adjusted_dinners = total_golfers - no_dinners + s.num_dinners
s.flag_dinners = True if no_dinners != s.num_golfers_no_dinner else False
s.net_due = s.payment_due - s.payment_made
if s.discount:
s.net_due -= s.discount
s.net_due = max(0, s.net_due)
golfer_count += total_golfers
dinner_count += total_golfers - no_dinners + s.num_dinners
template_values = {
'sponsors': sponsors,
'sponsor_count': len(sponsors),
'golfer_count': golfer_count,
'dinner_count': dinner_count,
'incomplete': '',
'capabilities': caps
}
self.response.out.write(render_to_string('viewsponsors.html', template_values))
class ViewIncomplete(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
q = q.order(Sponsor.sort_name)
sponsors = []
for s in q:
golfers_complete = 0
ndinners = 0
no_dinners = 0
total_golfers = s.num_golfers + s.num_golfers_no_dinner
if total_golfers:
golfers = ndb.get_multi(s.golfer_keys[:total_golfers])
for g in golfers:
if g.first_name and g.last_name and g.gender and (g.ghin_number or g.has_index or g.average_score):
golfers_complete += 1
if g.dinner_choice:
ndinners += 1
if g.dinner_choice == 'none':
no_dinners += 1
if s.num_dinners:
guests = ndb.get_multi(s.dinner_keys[:s.num_dinners])
for g in guests:
if g.first_name and g.last_name and g.dinner_choice:
ndinners += 1
s.total_golfers = total_golfers
s.adjusted_dinners = total_golfers - no_dinners + s.num_dinners
s.flag_dinners = True if no_dinners != s.num_golfers_no_dinner else False
s.net_due = s.payment_due - s.payment_made
if s.discount:
s.net_due -= s.discount
s.net_due = max(0, s.net_due)
if (s.net_due == 0 and
(golfers_complete < s.num_golfers or ndinners < s.num_golfers + s.num_dinners)):
sponsors.append(s)
nav = []
template_values = {
'sponsors': sponsors,
'incomplete': 'incomplete',
'nav': nav,
'capabilities': caps
}
self.response.out.write(render_to_string('viewsponsors.html', template_values))
class ViewUnpaid(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
q = q.order(Sponsor.sort_name)
sponsors = []
for s in q:
no_dinners = 0
total_golfers = s.num_golfers + s.num_golfers_no_dinner
if total_golfers:
golfers = ndb.get_multi(s.golfer_keys[:total_golfers])
for g in golfers:
if g.dinner_choice == 'none':
no_dinners += 1
s.total_golfers = total_golfers
s.adjusted_dinners = total_golfers - no_dinners + s.num_dinners
s.flag_dinners = True if no_dinners != s.num_golfers_no_dinner else False
s.net_due = s.payment_due - s.payment_made
if s.discount:
s.net_due -= s.discount
s.net_due = max(0, s.net_due)
if s.net_due > 0:
sponsors.append(s)
nav = []
template_values = {
'sponsors': sponsors,
'incomplete': 'unpaid',
'nav': nav,
'capabilities': caps
}
self.response.out.write(render_to_string('viewsponsors.html', template_values))
class ViewDinnerSurvey(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
q = q.order(Sponsor.sort_name)
sponsors = []
for s in q:
if s.num_golfers > 0 and s.email:
sponsors.append(s)
nav = []
template_values = {
'sponsors': sponsors,
'nav': nav,
'capabilities': caps
}
self.response.out.write(render_to_string('dinnersurvey.html', template_values))
class ViewUnconfirmed(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == False)
q = q.order(Sponsor.timestamp)
sponsors = q.fetch(100)
for s in sponsors:
s.total_golfers = s.num_golfers + s.num_golfers_no_dinner
s.adjusted_dinners = s.num_golfers + s.num_dinners
s.flag_dinners = True if no_dinners != s.num_golfers_no_dinner else False
s.net_due = s.payment_due - s.payment_made
if s.discount:
s.net_due -= s.discount
s.net_due = max(0, s.net_due)
nav = []
template_values = {
'sponsors': sponsors,
'incomplete': 'unconfirmed',
'nav': nav,
'capabilities': caps
}
self.response.out.write(render_to_string('viewsponsors.html', template_values))
class ViewGolfers(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
# html = memcache.get('%s/admin/view/golfers' % t.name)
# if html:
# self.response.out.write(html)
# return
all_golfers = []
counter = 1
q = Sponsor.query(ancestor = t.key)
q = q.filter(Sponsor.confirmed == True)
q = q.order(Sponsor.sort_name)
for s in q:
total_golfers = s.num_golfers + s.num_golfers_no_dinner
if total_golfers == 0:
continue
golfers = ndb.get_multi(s.golfer_keys[:total_golfers])
for g in golfers:
all_golfers.append(ViewGolfer(t, s, g, counter))
counter += 1
for i in range(len(golfers) + 1, total_golfers + 1):
g = Golfer(tournament = t.key, sponsor = s.key, sequence = i,
sort_name = '', first_name = '', last_name = '', gender = '',
company = '', address = '', city = '', phone = '', email = '',
handicap_index = 0.0, average_score = '', ghin_number = '',
shirt_size = '', dinner_choice = '')
all_golfers.append(ViewGolfer(t, s, g, counter))
counter += 1
shirt_sizes = { }
for g in all_golfers:
key = g.golfer.shirt_size if g.golfer.shirt_size else 'unspecified'
if not key in shirt_sizes:
shirt_sizes[key] = 0
shirt_sizes[key] += 1
template_values = {
'golfers': all_golfers,
'shirt_sizes': shirt_sizes,
'capabilities': caps
}
html = render_to_string('viewgolfers.html', template_values)
self.response.out.write(html)
class ViewGolfersByName(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
all_golfers = []
q = Golfer.query()
q = q.filter(Golfer.tournament == t.key)
q = q.filter(Golfer.active == True)
q = q.order(Golfer.sort_name)
counter = 1
for g in q:
s = g.sponsor.get()
all_golfers.append(ViewGolfer(t, s, g, counter))
counter += 1
template_values = {
'golfers': all_golfers,
'capabilities': caps
}
html = render_to_string('viewgolfersbyname.html', template_values)
self.response.out.write(html)
class UpdateHandicap(webapp2.RequestHandler):
def get(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, self.request.uri)
return
start = 1
if self.request.get('start'):
start = int(self.request.get('start'))
all_golfers = []
q = Golfer.query()
q = q.filter(Golfer.tournament == t.key)
q = q.filter(Golfer.active == True)
q = q.order(Golfer.sort_name)
golfer_keys = q.fetch(offset = start - 1, limit = 21, keys_only = True)
prev_page_offset = 0 if start == 1 else max(1, start - 20)
next_page_offset = 0
if len(golfer_keys) == 21:
next_page_offset = start + 20
golfer_keys = golfer_keys[:20]
counter = start
golfers = ndb.get_multi(golfer_keys)
for g in golfers:
s = g.sponsor.get()
vg = ViewGolfer(t, s, g, counter)
h = hashlib.md5()
h.update(g.ghin_number or '-')
h.update(vg.handicap_index_str or '-')
h.update(g.average_score or '-')
h.update('t' if g.index_info_modified else 'f')
vg.index_hash = h.hexdigest()
all_golfers.append(vg)
counter += 1
template_values = {
'golfers': all_golfers,
'prev_page_offset': prev_page_offset,
'this_page_offset': start,
'next_page_offset': next_page_offset,
'count': len(golfers),
'capabilities': caps
}
html = render_to_string('viewgolfers-index.html', template_values)
self.response.out.write(html)
def post(self):
t = tournament.get_tournament()
caps = capabilities.get_current_user_caps()
if caps is None or not caps.can_view_registrations:
show_login_page(self.response.out, '/admin/view/golfers/handicap')
return
prev_page_offset = int(self.request.get('prev_page_offset'))
this_page_offset = int(self.request.get('this_page_offset'))
next_page_offset = int(self.request.get('next_page_offset'))
count = int(self.request.get('count'))
golfers_to_update = []
for i in range(this_page_offset, this_page_offset + count):
key = ndb.Key(urlsafe = self.request.get('key_%d' % i))
index_hash = self.request.get('hash_%d' % i)
ghin_number = self.request.get('ghin_%d' % i)
handicap_index = self.request.get('index_%d' % i)
average_score = self.request.get('avg_score_%d' % i)
modified_checkbox = self.request.get('modified_%d' % i)
h = hashlib.md5()
h.update(ghin_number or '-')
h.update(handicap_index or '-')
h.update(average_score or '-')
h.update('t' if modified_checkbox else 'f')
if h.hexdigest() == index_hash:
continue
try:
g = key.get()
except:
logging.error("Invalid key for golfer #%d" % i)
continue
logging.info("Updating handicap info for golfer #%d" % i)
g.ghin_number = ghin_number
if handicap_index:
try:
val = float(handicap_index)
if not g.has_index or val != g.handicap_index:
g.handicap_index = val
g.has_index = True
except ValueError:
logging.error("Invalid handicap index '%s'" % handicap_index)
else:
g.handicap_index = 0.0
g.has_index = False
g.average_score = average_score
g.index_info_modified = False
golfers_to_update.append(g)
if golfers_to_update:
ndb.put_multi(golfers_to_update)
if self.request.get('prevpage'):
self.redirect('/admin/view/golfers/handicap?start=%d' % prev_page_offset)
elif self.request.get('nextpage'):
self.redirect('/admin/view/golfers/handicap?start=%d' % next_page_offset)
else:
self.redirect('/admin/view/golfers/handicap?start=%d' % this_page_offset)
class JsonBuilder:
def __init__(self, t):
self.t = t
self.build_teams()
self.build_golfers_and_groups()
self.check_consistency()
def build_teams(self):
"""
Build the list of teams, along with side data structures mapping golfers
to teams and teams to golfers.
golfers_by_team is an array indexed by (team_num - 1), where each element
is an array of golfer IDs.
teams_by_golfer_id_fwd is a table that maps each golfer id to a team,
based on the forward links from the Team entity to Golfer entities.
"""
self.teams = []
self.teams_by_id = {}
self.golfers_by_team = []
self.golfer_nums_by_id = {}
self.teams_by_golfer_id_fwd = {}
q = Team.query(ancestor = self.t.key).order(Team.name)
for t in q:
t_id = t.key.id()
team_num = len(self.teams) + 1
team = {
'team_num': team_num,
'key': t_id,
'name': t.name,
'golfer_nums': [],
'pairing_prefs': t.pairing or ''
}
self.teams.append(team)
self.teams_by_id[t_id] = team_num
golfer_ids = []
if t.golfers:
for g_key in t.golfers:
g_id = g_key.id()
golfer_ids.append(g_id)
if g_id in self.teams_by_golfer_id_fwd:
other_team_num = self.teams_by_golfer_id_fwd[g_id]
other_team = teams[other_team_num - 1]
logging.warning("Golfer %d is contained by teams \"%s\" and \"%s\"" % (g_id, other_team['name'], t.name))
else:
self.teams_by_golfer_id_fwd[g_id] = team_num
self.golfers_by_team.append(golfer_ids)
def build_golfers_and_groups(self):
"""
Build the list of golfers and the list of groups, along with a side data
structure mapping golfers to teams.
teams_by_golfer_id_rev is a table that maps each golfer id to a team,
based on the reverse links from each Golfer entities to a Team entity.
When there is disagreement, we use this mapping as the "truth".
"""
self.golfers = []
self.substitutes = []
self.groups = []
self.teams_by_golfer_id_rev = {}
q = Sponsor.query(ancestor = self.t.key).filter(Sponsor.confirmed == True).order(Sponsor.sort_name)
for s in q:
total_golfers = s.num_golfers + s.num_golfers_no_dinner
if total_golfers == 0:
continue
group_golfer_nums = []
for g in ndb.get_multi(s.golfer_keys[:total_golfers]):
g_id = g.key.id()
golfer_num = len(self.golfers) + 1
team = None
team_num = 0
if g.team:
try:
team = g.team.get()
except:
logging.warning("Dangling reference from golfer %d (sponsor id %d) to deleted team" % (g_id, s.sponsor_id))
g.team = None
g.put()
if team:
t_id = team.key.id()
team_num = self.teams_by_id[t_id]
if not g_id in self.teams_by_golfer_id_fwd:
logging.warning("Golfer %d (sponsor id %d) refers to team \"%s\", but no team contains golfer" % (g_id, s.sponsor_id, t.name))
elif self.teams_by_golfer_id_fwd[g_id] != team_num:
other_team_num = self.teams_by_golfer_id_fwd[g_id]
other_team = self.teams[other_team_num - 1]
logging.warning("Golfer %d (sponsor id %d) refers to team \"%s\", but is contained by team \"%s\"" % (g_id, s.sponsor_id, t.name, other_team['name']))
else:
t_id = -1
self.teams_by_golfer_id_rev[g_id] = team_num
if g_id in self.teams_by_golfer_id_fwd:
team_num = self.teams_by_golfer_id_fwd[g_id]
else:
team_num = 0
if g.substitute:
g_sub = g.substitute.get()
hdcp_index = get_handicap_index(g_sub)
if hdcp_index is not None:
hdcp_index = "%.1f" % hdcp_index
else:
hdcp_index = "-"
substitute = {
'key': g.substitute.id(),
'first_name': g_sub.first_name,
'last_name': g_sub.last_name,
'gender': g_sub.gender,
'ghin': g_sub.ghin_number,
'avg': g_sub.average_score,
'index': hdcp_index
}
self.substitutes.append(substitute)
substitute_index = len(self.substitutes)
else:
substitute_index = 0
hdcp_index = get_handicap_index(g)
if hdcp_index is not None:
hdcp_index = "%.1f" % hdcp_index
else:
hdcp_index = "-"
h = hashlib.md5()
h.update(','.join(str(x) for x in [t_id, g.cart]))
golfer = {
'golfer_num': golfer_num,
'group_num': len(self.groups) + 1,
'team_num': team_num,
'key': g_id,
'first_name': g.first_name,
'last_name': g.last_name,
'gender': g.gender,
'index': hdcp_index,
'cart': g.cart,
'substitute': substitute_index,
'md5': h.hexdigest()
}
if team_num:
team = self.teams[team_num - 1]
team['golfer_nums'].append(golfer_num)
else:
group_golfer_nums.append(golfer_num)
self.golfers.append(golfer)
group = {
'group_num': len(self.groups) + 1,
'key': s.key.id(),
'id': str(s.sponsor_id),
'first_name': s.first_name,
'last_name': s.last_name,
'golfer_nums': group_golfer_nums,
'pairing_prefs': s.pairing
}
self.groups.append(group)
def check_consistency(self):
for t in range(1, len(self.teams) + 1):
team = self.teams[t - 1]
for g_id in self.golfers_by_team[t - 1]:
if not g_id in self.teams_by_golfer_id_rev:
logging.warning("Team %d \"%s\" (%d) contains golfer %d, but golfer does not exist" % (t, team['name'], team['key'], g_id))
elif self.teams_by_golfer_id_rev[g_id] != t:
logging.warning("Team %d \"%s\" (%d) contains golfer %d, but golfer does not refer to team" % (t, team['name'], team['key'], g_id))
if not team['golfer_nums']:
logging.warning("Empty team \"%s\" (%d)" % (team['name'], team['key']))
def groups_json(self):
return json.dumps(self.groups)
def teams_json(self):
return json.dumps(self.teams)
def golfers_json(self):
return json.dumps(self.golfers)
def substitutes_json(self):
return json.dumps(self.substitutes)
class TeamsUpdater:
def __init__(self, t, golfers_json, substitutes_json, groups_json, teams_json):
self.t = t
self.golfers = json.loads(golfers_json)
self.substitutes = json.loads(substitutes_json)
self.groups = json.loads(groups_json)
self.teams = json.loads(teams_json)
def update_teams_pass1(self):
self.team_entities = []
self.golfers_by_id = {}
for t in self.teams:
team_id = t['key']
if team_id:
team = Team.get_by_id(int(team_id), parent = self.t.key)
if not team:
logging.error("no team with id %s" % team_id)
continue
else:
team = Team(parent = self.t.key)
team.name = t['name']
team.pairing = t['pairing_prefs']
self.team_entities.append((t['team_num'], team))
for golfer_num in t['golfer_nums']:
g_id = self.golfers[golfer_num - 1]['key']
self.golfers_by_id[g_id] = (None, False)
# logging.debug("Update teams pass 1: team %d golfer %d" % (t['team_num'], g_id))
def update_golfers_pass1(self):
for g in self.golfers:
g_id = g['key']
team_num = g['team_num']
if team_num:
t_id = self.teams[team_num - 1]['key']
if not t_id:
t_id = 0
else:
t_id = -1
h = hashlib.md5()
h.update(','.join(str(x) for x in [t_id, g['cart']]))
modified = h.hexdigest() != g['md5']
# logging.debug("Update golfers pass 1: team %d golfer %d (%s)" % (g['team_num'], g_id, "modified" if modified else "not modified"))
if modified or g_id in self.golfers_by_id:
group_num = g['group_num']
group = self.groups[group_num - 1]
s_id = group['key']
s = Sponsor.get_by_id(s_id, parent = self.t.key)
if not s: