-
Notifications
You must be signed in to change notification settings - Fork 2
/
main_app_ui.py
2354 lines (1786 loc) · 82.9 KB
/
main_app_ui.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
# Copyright (C) 2023 David Mossakowski
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import json
import os
import io
import glob
import random
import uuid
from datetime import datetime, date, time, timedelta
from src.User import User
import competitionsEngine
import csv
from functools import wraps
import qrcode
from flask import Flask, redirect, url_for, session, request, render_template, send_file, send_from_directory, \
jsonify, Response, \
stream_with_context, copy_current_request_context, make_response
import logging
from flask import Blueprint
import activities_db as activity_engine
from io import BytesIO
from flask import send_file
import skala_api
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
#app_ui = Blueprint('app_ui', __name__)
from authlib.integrations.flask_client import OAuth
from authlib.integrations.flask_client import OAuthError
import activities_db as activities_db
#from flask_openapi3 import Info, Tag, APIBlueprint
#from flask_openapi3 import OpenAPI
languages = {}
DATA_DIRECTORY = os.getenv('DATA_DIRECTORY')
if DATA_DIRECTORY is None:
DATA_DIRECTORY = os.getcwd()
#PLAYLISTS_DB = DATA_DIRECTORY + "/db/playlists.sqlite"
COMPETITIONS_DB = DATA_DIRECTORY + "/db/competitions.sqlite"
# ID, date, name, location
COMPETITIONS_TABLE = "competitions"
# ID, name, club, m/f, list of climbs
CLIMBERS_TABLE = "climbers"
FSGT_APP_ID = os.getenv('FSGT_APP_ID')
FSGT_APP_SECRET = os.getenv('FSGT_APP_SECRET')
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
#tag = Tag(name="UI operations", description='UI operations which return HTML pages - competitionsApp.py')
#app_ui = APIBlueprint('app_ui', __name__, abp_tags=[tag])
app_ui = Blueprint('app_ui', __name__, static_folder='public')
app_ui.debug = True
app_ui.secret_key = 'development'
oauth = OAuth(app_ui)
genres = {"test": "1"}
authenticated = False
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
app_ui.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
UPLOAD_FOLDER = os.path.join(DATA_DIRECTORY,'uploads')
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
#app_ui.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# User session management setup
# https://flask-login.readthedocs.io/en/latest
@app_ui.before_request
def x(*args, **kwargs):
skala_api.x(*args, **kwargs)
@app_ui.route('/language/<language>')
def set_language(language=None):
skala_api.set_language(language)
# Get the origin of the request from the Referer header
origin = request.headers.get('Referer')
# Redirect to the origin if it's not None, otherwise redirect to the home page
if origin:
return redirect(origin)
else:
return redirect("/")
def login_required(fn):
@wraps(fn)
def decorated_function(*args, **kwargs):
if skala_api.is_logged_in():
return fn(*args, **kwargs)
else:
session["wants_url"] = request.url
return redirect(url_for("app_ui.fsgtlogin"))
return decorated_function
def admin_required(fn):
@wraps(fn)
def decorated_function(*args, **kwargs):
if session != None and (session.get('name') == 'David Mossakowski' or
session.get('name') == 'Sebastiao Correia'):
now = int(datetime.now().timestamp())
#expiresAt = session['expires_at']
expiresAtLocaltime = session['expires_at_localtime']
return fn(*args, **kwargs)
else:
session["wants_url"] = request.url
return redirect(url_for("app_ui.fsgtlogin"))
return decorated_function
@app_ui.get("/aa")
def index11():
if session.get('username'):
return '<a class="button" href="/login">logged in </a>'+session.get('username')
if current_user.is_authenticated:
return (
"<p>Hello, {}! You're logged in! Email: {}</p>"
"<div><p>Google Profile Picture:</p>"
'<img src="{}" alt="Google profile pic"></img></div>'
'<a class="button" href="/logout">Logout</a>'.format(
current_user.name, current_user.email, current_user.profile_pic
)
)
else:
return '<a class="button" href="/login">Google Login</a>'
@app_ui.route('/competitionRawAdmin', methods=['GET'])
@login_required
@admin_required
def fsgtadminget():
"""
Load Admin page from competitionRawAdmin.html
"""
edittype = request.args.get('edittype')
id = request.args.get('id')
action = request.args.get('action')
jsondata = request.args.get('jsondata')
jsonobject = None
return render_template('competitionRawAdmin.html',
jsondata=json.dumps(jsonobject),
reference_data=competitionsEngine.reference_data,
id=id)
@app_ui.post('/competitionRawAdmin')
@login_required
@admin_required
def fsgtadmin():
"""
Do admin action
This is an admin action
"""
edittype = request.form.get('edittype')
id = request.form.get('id')
action = request.form.get('action')
jsondata = request.form.get('jsondata')
comp = {}
jsonobject = None
if jsondata is not None and len(jsondata) > 2:
jsonobject = json.loads(jsondata)
if edittype == 'user':
if jsonobject is not None and action == 'update':
competitionsEngine.upsert_user(jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_user_by_email(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_user_emails()
elif edittype == 'competition':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
competitionsEngine._update_competition(jsonobject['id'],jsonobject)
if id is not None and action == 'delete':
#jsonobject = {"success": "competition updated"}
competitionsEngine.delete_competition(id)
if id is not None and action == 'find':
jsonobject = competitionsEngine.getCompetition(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_competition_ids()
elif edittype == 'gym':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
competitionsEngine.update_gym(jsonobject['id'], jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_gym(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_gyms()
elif edittype == 'routes':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
# None is gymid but this is ok as the routes id will be found
competitionsEngine.upsert_routes(id, None, jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_routes(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_routes_ids()
elif edittype == 'activities':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
# None is gymid but this is ok as the routes id will be found
# competitionsEngine.upsert_routes(id, None, jsonobject)
return
if id is not None and action == 'find':
jsonobject = activities_db.get_activities(id)
if id is not None and action == 'findall':
jsonobject = activities_db.get_activities(id)
else :
jsonobject = {"error": "choose edit type" }
return render_template('competitionRawAdmin.html',
jsondata=json.dumps(jsonobject),
reference_data=competitionsEngine.reference_data,
id=id)
@app_ui.route('/adminv2', methods=['GET'])
@login_required
@admin_required
def adminv2():
edittype = request.args.get('edittype')
id = request.args.get('id')
action = request.args.get('action')
jsondata = request.args.get('jsondata')
jsonobject = None
return render_template('adminv2.html',
reference_data=competitionsEngine.reference_data
)
@app_ui.route('/competition_admin/<competition_id>', methods=['GET'])
#, summary='returns competitionAdmin.html',
# responses={"default": {"description": "Render template competitionAdmin.html"}})
@login_required
def competition_admin_get(competition_id):
user = competitionsEngine.get_user_by_email(session['email'])
competition = competitionsEngine.getCompetition(competition_id)
user_list = competitionsEngine.get_all_user_emails()
if user is None or competition is None or not competitionsEngine.can_edit_competition(user,competition):
session["wants_url"] = request.url
return redirect(url_for('app_ui.getCompetition', competitionId=competition['id']))
all_routes = competitionsEngine.get_routes_by_gym_id(competition['gym_id'])
return render_template('competitionAdmin.html',
user=user,
competition=competition,
user_list=user_list,
competitionId=competition_id,
all_routes = all_routes,
reference_data=competitionsEngine.reference_data,
id=id)
@app_ui.route('/competition_admin/<competition_id>', methods=['POST'])
@login_required
def competition_admin_post(competition_id):
remove_climber = request.form.get('remove_climber')
update_status = request.form.get('update_status')
permission_admin_user = request.form.get('permission_admin_user')
permission_scorer_user = request.form.get('permission_scorer_user')
max_participants = request.form.get('max_participants')
# get climber id in competition admin table (not none when a change is saved)
climber_id = request.form.get('update_climber')
competition_update_button = request.form.get('competition_update_button')
delete_competition_button = request.form.get('delete_competition_button')
change_poster_button = request.form.get('change_poster_button')
edittype = request.form.get('edittype')
permissioned_user = request.form.get('permissioned_user')
id = request.form.get('id')
action = request.form.get('action')
competition_status = request.form.get('competition_status')
instructions = request.form.get('instructions')
user_id = request.form.get('userId')
jsondata = request.form.get('jsondata')
comp = {}
jsonobject = None
imgfilename = None
if 'file1' in request.files:
file1 = request.files['file1']
if file1.filename is not None and len(file1.filename) > 0:
imgfilename = competition_id
# this needs a fix for SVG files.. currently they will not be displayed
# the fix is to img field to each competition.. currently we retrieve the image as a file
imgpath = os.path.join(UPLOAD_FOLDER, imgfilename)
file1.save(imgpath)
user = competitionsEngine.get_user_by_email(session['email'])
competition = competitionsEngine.getCompetition(competition_id)
if user is None or competition is None or not competitionsEngine.can_edit_competition(user,competition):
session["wants_url"] = request.url
return redirect(url_for("app_ui.fsgtlogin"))
# add this competition to another user's permissions
# remove this competition from another users permissions
# change the state of a competition
# remove climber from a competition
if permission_admin_user is not None:
user2 = competitionsEngine.get_user(user_id)
competitionsEngine.modify_user_permissions_to_competition(user2, competition_id)
competitionsEngine.add_user_permission_edit_competition(user2)
if permission_scorer_user is not None:
user2 = competitionsEngine.get_user(user_id)
competitionsEngine.modify_user_permissions_to_competition(user2, competition_id)
competitionsEngine.add_user_permission_update_routes(user2)
if update_status is not None:
competition['status'] = int(competition_status)
competitionsEngine.update_competition(competition_id, competition)
if remove_climber is not None:
competition['climbers'].pop(remove_climber)
competitionsEngine.update_competition(competition['id'], competition)
if climber_id is not None:
competition['climbers'][climber_id]['name'] = request.form.get('name_'+ climber_id)
competition['climbers'][climber_id]['sex'] = request.form.get('sex_'+ climber_id)
competition['climbers'][climber_id]['club'] = request.form.get('club_'+ climber_id)
competition['climbers'][climber_id]['email'] = request.form.get('email_'+ climber_id)
try:
# Attempt to retrieve the category from the form data and convert it to an integer
competition['climbers'][climber_id]['category'] = int(request.form.get('category_' + str(climber_id)))
except (ValueError, TypeError):
# Handle the exception if the conversion fails
print("The provided category is not a valid integer for climber " + competition['climbers'][climber_id]['name'])
# Set to a default value or handle the error as appropriate
competition['climbers'][climber_id]['category'] = 0 # Replace default_value with whatever default you wish to use
competitionsEngine.update_competition(competition['id'], competition)
if competition_update_button is not None:
competition_name = request.form.get('competition_name')
competition_date = request.form.get('competition_date')
competition_routes = request.form.get('competition_routes')
max_participants = request.form.get('max_participants')
# update gym name in the competition if Gym Name is changed somewhere else
gym = competitionsEngine.get_gym(competition['gym_id'])
if gym is not None:
if gym['name'] != competition['gym']:
competition['gym']=gym['name']
competition['max_participants']=max_participants
competitionsEngine.update_competition_details(competition, competition_name, competition_date, competition_routes, instructions)
if delete_competition_button is not None:
if competitionsEngine.competition_can_be_deleted(competition):
competitionsEngine.delete_competition(competition['id'])
return redirect(f'/competitionDashboard')
if change_poster_button is not None and imgfilename is not None:
competitionsEngine.update_competition(competition['id'], competition)
user_list = competitionsEngine.get_all_user_emails()
all_routes = competitionsEngine.get_routes_by_gym_id(competition['gym_id'])
return render_template('competitionAdmin.html',
jsondata=json.dumps(jsonobject),
user=user,
competition=competition,
user_list=user_list,
competitionId=competition_id,
all_routes = all_routes,
reference_data=competitionsEngine.reference_data,
id=id)
@app_ui.route('/fsgtadmin/<edittype>')
def fsgtadminedit(edittype):
j = request.args.get('jsondata')
if edittype == 'user' and j['email'] is not None:
competitionsEngine.upsert_user(j)
return render_template('competitionRawAdmin.html',
reference_data=competitionsEngine.reference_data)
# for some reason I added a case here to go to the home page
# no idea why
@app_ui.route('/loginchoice')
def fsgtlogin(error=None):
return render_template('competitionLogin.html',
reference_data=competitionsEngine.reference_data,
error=error
)
@app_ui.route('/activities', methods=['GET'])
@login_required
def activities():
user = competitionsEngine.get_user_by_email(session['email'])
return render_template('activities.html',
user=user,
reference_data=competitionsEngine.reference_data,
today=date.today()
)
#@app_ui.route('/activities/<activity_id>', methods=['GET'], description='returns activity-detail.html')
@app_ui.route('/activities/<activity_id>', methods=['GET'])
#@login_required
def activity_detail(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activity_engine.get_activity(activity_id)
gym = competitionsEngine.get_gym(activity['gym_id'])
#gym = competitionsEngine.get_gym(journey['gym_id'])
if activity.get('routes_id') is None:
routes = competitionsEngine.get_routes("7134a8ef-fa2e-4672-a247-115773183bcd") # should return Nanterre routes
else:
routes = competitionsEngine.get_routes(activity['routes_id'])
return render_template('activity-detail.html',
user=user,
reference_data=competitionsEngine.reference_data,
activity=activity,
routes=routes,
gym=gym,
today=date.today(),
activity_id=activity_id,
)
@app_ui.route('/activities/dialog', methods=['GET'])
#@login_required
def activity_detail_dialog():
user = competitionsEngine.get_user_by_email(session['email'])
activity = activity_engine.get_activity(activity_id)
gym = competitionsEngine.get_gym(activity['gym_id'])
return render_template('activity-detail.html',
user=user,
reference_data=competitionsEngine.reference_data,
activity=activity,
routes=routes,
gym=gym,
today=date.today(),
activity_id=activity_id,
)
@app_ui.route('/journey/add', methods=['POST'])
@login_required
def journey_add():
user = competitionsEngine.get_user_by_email(session['email'])
date = request.form.get('date')
gym_id = request.form.get('gym_id')
comp = {}
gym = competitionsEngine.get_gym(gym_id)
journey = activity_engine.add_journey_session(user,gym_id, gym.get('routesid'), date)
#journey_id = user.get('journey_id')
#if journey_id is None:
# journey = activity_engine.add_journey(user, description)
journeys = activity_engine._get_journey_sessions_by_user_id(user.get('id'))
return render_template('skala-journey.html',
user=user,
journeys=journeys,
journey=journey,
reference_data=competitionsEngine.reference_data
)
@app_ui.route('/journey/<journey_id>', methods=['GET'])
@login_required
def journey_session(journey_id):
user = competitionsEngine.get_user_by_email(session['email'])
journey = activity_engine.get_journey_session(journey_id)
#gym = competitionsEngine.get_gym(journey['gym_id'])
if journey.get('routes_id') is None:
routes = competitionsEngine.get_routes("7134a8ef-fa2e-4672-a247-115773183bcd") # should return Nanterre routes
else:
routes = competitionsEngine.get_routes(journey['routes_id'])
return render_template('skala-journey-session.html',
user=user,
journey=journey,
routes=routes,
reference_data=competitionsEngine.reference_data,
)
@app_ui.route('/journey/<journey_id>/add', methods=['POST'])
@login_required
def journey_session_entry_add(journey_id):
user = competitionsEngine.get_user_by_email(session['email'])
route_finish_status = request.form.get('route_finish_status')
route_id = request.form.get('route')
notes = request.form.get('notes')
comp = {}
journey = activity_engine.get_journey_session(journey_id)
journey = activity_engine.add_journey_session_entry(journey_id,route_id, route_finish_status, notes)
routes = competitionsEngine.get_routes(journey.get('routes_id'))
return render_template('skala-journey-session.html',
user=user,
journey=journey,
routes=routes,
reference_data=competitionsEngine.reference_data,
)
@app_ui.route('/journey/<journey_id>/<route_id>/remove', methods=['GET'])
@login_required
def journey_session_remove(journey_id, route_id):
user = competitionsEngine.get_user_by_email(session['email'])
journey = activity_engine.get_journey_session(journey_id)
activity_engine.remove_journey_session(journey_id, route_id)
routes = competitionsEngine.get_routes(journey.get('routes_id'))
return render_template('skala-journey-session.html',
user=user,
journey=journey,
routes=routes,
reference_data=competitionsEngine.reference_data,
)
@app_ui.route('/privacy')
def privacy():
return render_template('privacy.html',
reference_data=competitionsEngine.reference_data
)
@app_ui.route('/')
def index():
langs = competitionsEngine.reference_data['languages']
language = session.get('language')
if language is None:
logging.debug('language is None. setting to fr_FR')
language = 'fr_FR'
session['language'] = language
user = competitionsEngine.get_user_by_email(session.get('email'))
competitions= competitionsEngine.getCompetitions()
return render_template('skala3ma.html',
competitions=competitions,
competitionName=None,
session=session,
user=user,
reference_data=competitionsEngine.reference_data,
#langpack=language,
**session
)
@app_ui.route('/main')
def main():
return redirect("/")
@app_ui.route('/competitionCalendar')
def getCompetitionCalendar():
#username = session.get('username')
logging.info('competitionCalendar language=' + str(session.get('language')))
can_create_competition = False
user = competitionsEngine.get_user_by_email(session.get('email'))
if user is not None:
can_create_competition = competitionsEngine.can_create_competition(user)
#langs = competitionsEngine.reference_data['languages']
return render_template('competitionCalendar.html',
session=session,
user=user,
reference_data=competitionsEngine.reference_data,
language=session['language'],
#langpack=languages['en_US'],
can_create_competition=can_create_competition
# **session
)
@app_ui.route('/competitionDashboard')
def getCompetitionDashboard():
# select season year depending on current month;
# e.g. if 2023-10-01 then season is 2023-24
# if 2023-05-01 then season is 2022-23
current_year = datetime.now().year
current_month = datetime.now().month
season = current_year if current_month >= 9 else current_year-1
return competitions_by_year(str(season))
@app_ui.route('/competitions/year/<year>')
def competitions_by_year(year):
username = session.get('username')
name = request.args.get('name')
date = request.args.get('date')
gym = request.args.get('gym')
if not year.isdigit():
year = datetime.now().year
can_create_competition = False
user = competitionsEngine.get_user_by_email(session.get('email'))
if user is not None:
can_create_competition = competitionsEngine.can_create_competition(user)
subheader_message = request.accept_languages
langs = competitionsEngine.reference_data['languages']
competitions3 = competitionsEngine.get_competitions_by_year(year)
return render_template('competitionDashboard.html',
subheader_message=subheader_message,
competitions=competitions3,
competitionName=None,
session=session,
user=user,
year=year,
reference_data=competitionsEngine.reference_data,
#langpack=languages['en_US'],
can_create_competition=can_create_competition,
**session
)
@app_ui.route('/newCompetition', methods=['GET'])
@login_required
def new_competition():
username = session.get('username')
#if username:
# return 'logged in '+str(username)
#print(username)
#username = request.args.get('username')
name = request.args.get('name')
date = request.args.get('date')
gym = request.args.get('gym')
comp = {}
competitionId=None
all_gyms = competitionsEngine.get_gyms()
clubs = []
for gymid in all_gyms:
gymname = all_gyms[gymid]['name']
routes = competitionsEngine.get_routes_by_gym_id(gymid)
for routeid in routes:
clubs.append ({'gymname':gymname, 'gymid':gymid, 'routesid':routeid, 'routesname':routes[routeid]['name']})
return render_template('newCompetition.html',
competitionName=None,
session=session,
gyms=gyms,
clubs=clubs,
reference_data=competitionsEngine.reference_data,
**session)
# method to add a new competition
@app_ui.route('/newCompetition', methods=['POST'])
@login_required
def new_competition_post():
username = session.get('username')
#if username:
# return 'logged in '+str(username)
#print(username)
#username = request.args.get('username')
name = request.form.get('name')
date = request.form.get('date')
#gym = request.form.get('gym')
routesid = request.form.get('routes')
competition_type = request.form.get('competition_type')
max_participants = request.form.get('max_participants')
instructions = request.form.get('instructions')
comp = {}
competitionId = None
user = competitionsEngine.get_user_by_email(session.get('email'))
if user is None or not competitionsEngine.can_create_competition(user):
return redirect(url_for('app_ui.fsgtlogin', competitionId=competitionId))
if name is not None and date is not None and routesid is not None and max_participants is not None:
competitionId = competitionsEngine.addCompetition(None, name, date, routesid, max_participants,
competition_type=competition_type, instructions=instructions)
# now if an image was provided, save it under the competition id
# there is only one main image allowed per competition for now
# any new image will overwrite the previous one
if 'file1' in request.files:
file1 = request.files['file1']
if file1.filename is not None and len(file1.filename) > 0:
imgpath = os.path.join(UPLOAD_FOLDER, competitionId)
file1.save(imgpath)
competitionsEngine.modify_user_permissions_to_competition(user, competitionId, "ADD")
comp = getCompetition(competitionId)
return redirect(url_for('app_ui.getCompetition', competitionId=competitionId))
subheader_message='Welcome '
competitions= competitionsEngine.getCompetitions()
return render_template('competitionDashboard.html',
subheader_message=subheader_message,
competitions=competitions,
competitionName=None,
session=session,
reference_data=competitionsEngine.reference_data,
**session)
@app_ui.route('/competitionDashboard/<competitionId>/register')
#@login_required
def addCompetitionClimber(competitionId):
useremail = session.get('email')
firstname = request.args.get('firstname')
lastname = request.args.get('lastname')
email = request.args.get('email')
sex = request.args.get('sex')
club = request.args.get('club')
otherclub = request.args.get('otherclub')
category = request.args.get('category')
dob = request.args.get('dob')
comp = competitionsEngine.getCompetition(competitionId)
user = competitionsEngine.get_user_by_email(useremail)
climber_id = str(uuid.uuid4().hex)
if user is not None:
climber_id = user['id']
form_user = competitionsEngine.get_user_by_email(email)
competition_accepts_registrations = competitionsEngine.competition_accepts_registrations(comp)
error_code = ''
if not competition_accepts_registrations:
error_code = "error5322"
is_registered = competitionsEngine.is_registered(user, comp)
climber = None
# check if user with this email is known and should login themselves to register
if user is None and form_user is not None and (
form_user.get('fname') is not None or form_user.get('gname') is not None):
error_code = "error5316"
# the user found by email on form is already registered
is_form_user_registered = competitionsEngine.is_registered(form_user, comp)
if is_form_user_registered:
error_code = "error5321"
if dob is not None:
category = competitionsEngine.get_category_from_dob(dob)
if category == -1:
error_code = "error5325"
if not error_code and not is_registered and firstname is not None and sex is not None and club is not None and email is not None:
#climber = competitionsEngine.get_climber_by_email(email)
name = firstname + " " + lastname
try:
if club not in competitionsEngine.clubs.values():
club = otherclub
climber = competitionsEngine.addClimber(climber_id, competitionId, email, name, firstname, lastname, club, sex, category)
competitionsEngine.user_registered_for_competition(climber['id'], name, firstname, lastname, email, climber['sex'],
climber['club'], dob)
comp = competitionsEngine.getCompetition(competitionId)
competitionName = comp['name']
#subheader_message = 'You have been registered! Thanks!'
#return redirect(url_for('app_ui.getCompetition', competitionId=competitionId))
return render_template("competitionClimberRegistered.html",
competitionId=competitionId,
competition=comp,
reference_data=competitionsEngine.reference_data,
library=None,
**session)
except ValueError:
# this user is alrady registered
error_code = "error5321"
## comp=None # this is to not show the list of climbers before registration
#competitions = competitionsEngine.getCompetitions()
name = session.get('name')
if name is None:
name = ""
can_unregister = competitionsEngine.can_unregister(user, comp)
enable_registration = False
if competition_accepts_registrations and not is_registered and not error_code:
enable_registration = True
return render_template('competitionClimber.html',
error_code=error_code,
competition=comp,
competitionId=competitionId,
climber=climber,
user = user,
reference_data=competitionsEngine.reference_data,
logged_email=useremail,
logged_name=name,
can_unregister=can_unregister,
is_registered=is_registered,
enable_registration=enable_registration,
**session)
@app_ui.route('/competitionDashboard/<competitionId>/unregister')
@login_required
def unregister(competitionId):
if session.get('email') is not None:
climber = competitionsEngine.get_user_by_email(session.get('email'))
if climber is not None:
competitionsEngine.removeClimber(climber['id'], competitionId)
return redirect(url_for('app_ui.getCompetition', competitionId=competitionId))
return redirect(url_for('app_ui.getCompetition', competitionId=competitionId))
@app_ui.route('/user')
def get_user():
if session.get('email') is None:
return render_template('competitionDashboard.html', sortedA=None,
reference_data=competitionsEngine.reference_data,
subheader_message="No user found",
**session)
climber = competitionsEngine.get_user_by_email(session.get('email'))
#subheader_message = request.args.get('update_details')
email = session.get('email')
name = session.get('name')
if name is None:
name = ""
return render_template('climber.html',
#subheader_message=subheader_message,
competitionId=None,
climber=climber,
reference_data=competitionsEngine.reference_data,
logged_email=email,
logged_name=email,
**session)
@app_ui.route('/updateuser')
def update_user():
if session.get('email') is None:
return render_template('competitionDashboard.html', sortedA=None,
subheader_message="No competition found",
**session)
climber = competitionsEngine.get_user_by_email(session.get('email'))
firstname = request.args.get('firstname')