-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcompetitionsEngine.py
More file actions
2126 lines (1661 loc) · 84.2 KB
/
Copy pathcompetitionsEngine.py
File metadata and controls
2126 lines (1661 loc) · 84.2 KB
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 base64
import json
import os
import glob
import random
from datetime import datetime, date, timedelta
import time
from collections import Counter
import tracemalloc
import sqlite3 as lite
import uuid
import copy
from threading import RLock
import csv
import requests
from CalculationStrategy import CalculationStrategy
from CalculationStrategyFsgt import CalculationStrategyFsgt0, CalculationStrategyFsgt1
import skala_db
import activities_db
from src.User import User
from src.Route import Route
from src.Gym import Gym
sql_lock = RLock()
from flask import Flask, redirect, url_for, session, request, render_template, send_file, jsonify, Response, \
stream_with_context, copy_current_request_context
from functools import lru_cache, reduce
import logging
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
USERS_TABLE = "climbers"
ROUTES_TABLE = "routes"
ROUTES_CLIMBED_TABLE = "routes_climbed"
GYM_TABLE = "gyms"
#comps = {}
#climbers = {}
colors = { 'Vert':'#2E8B57',
'Vert marbré':'#2E8B57',
'Rouge':'#FF0000',
'Rouge marbré':'#FF0000',
'Gris':'#708090',
'Marron':'#A0522D',
'Rose marbré':'#FF69B4',
'Jaune':'#FFFF00',
'Orange':'#FFA500',
'Rose':'#FF69B4',
'Mauve':'#800080',
'Blanc':'#FFFFFF',
'Bleu':'#0000FF',
'Bleu marbré':'#0000FF',
'Noir':'#000000',
'Noir marbré':'#000000',
'Violet': '#9400D3',
'Saumon':'#FFE4C4'}
# Mapping of club names to gym IDs
CLUB_TO_GYMID = {
'ROC 14': '005d3b0d78b5477db673f6424b0fbeba',
'Entente Sportive de Nanterre': '1',
'ESC XV': '591a28aa8e924d25a3c9c0cc6a0c883f',
'US Ivry': '8b797c6675934ad197b15d6f7950c8e2',
'RSC Champigny': 'ca09c1dab6c04bb7b8e224bd9344d4c9',
'US Fontenay': '1a088f939d1b4a82a359bda05fed0f24',
'USF Escalade': '1a088f939d1b4a82a359bda05fed0f24',
'CPS 10 - Faites le mur': '20605d959edc4bee8a212935973590e4',
'AS Pierrefitte': 'a247c13c9ae54e898d2651cf7369145a',
'Grimpe Heureuse de Pierrefitte': 'a247c13c9ae54e898d2651cf7369145a',
'US Ivry - Orme au Chat' : '8b797c6675934ad197b15d6f7950c8e2'
}
#categories = {0:"Séniors 16-49 ans | Ado 12-13",
# 1:"Titane 50-64 ans | Ado 14-15 ",
# 2: "Diamant 65 ans et + | Ado 16-17"}
#categories_ado = {0:"Ado 12-13",
# 1:"Ado 14-15 ",
# 2: "Ado 16-17"}
#last 44
clubs = {
40:"11C+",
0:"APACHE" , 111:"Argenteuil Grimpe", 2:"AS Noiseraie Champy" ,
4:"ASG Bagnolet" , 5:"Athletic Club Bobigny", 6:"Au Pied du Mur (APDM)" ,
7:"Chelles Grimpe" , 8:"Cimes 19" , 9:"CMA Plein Air",
44: "Cordée 13",
10:"Faites le Mur - CPS10" ,
42:"CSMG Escalade - Gennevilliers",
11:"Dahu 91" ,
43: "EMA - Maisons-Alfort",
41:"EscaladA'sceaux",
39:"Escalade Populaire Montreuilloise",
12:"Entente Sportive Aérospatial Mureaux(ESAM)" ,
14:"ESC 11", 15:"ESC15" ,16:"Espérance Sportive Stains",
17:"Grimpe 13" ,
38:"Grimpe Fertoise Pays de Brie",
3:"Grimpe heureuse de Pierrefitte" ,
18:"Grimpe Tremblay Dégaine", 19:"GrimpO6" ,
20:"Groupe Escalade Saint Thibault" ,
21:"Le Mur 20" ,
1:"Nanterre Grimpe" ,
22:"Neuf-a-pic", 23:"Quatre +" ,24:"ROC14" , 25:"RSCC ESCALADE MONTAGNE RANDONNEE",
26:"RSC Montreuillois" ,27:"SNECMA Sports Corbeil", 28:"SNECMA Sports Genevilliers" ,
29:"Union Sportive Saint Arnoult", 30:"US Fontenay" , 31:"US Ivry - Orme au Chat" , 32:"US Métro" ,
33:"USMA", 34:"Vertical 12", 35:"Vertical Maubuée", 36:"Villejuif Altitude"
}
# created - only visible to admin or someone who has the right to see it
# open - visible and registration is possible
# inprogress - visible, can still register and can enter routes climbed
# scoring - cannot register, can enter routes, calculate and see results
# closed - cannot change routes and no need to recalculate
competition_status_created = 0
competition_status_open = 1
competition_status_inprogress = 2
competition_status_scoring = 3
competition_status_closed = 4
competition_status_archived = 5
competition_status_future = 5
competition_status = {"created":competition_status_created, "open":1, "inprogress":2, "scoring":3, "closed":4, "archived":5}
user_roles = ["none", "judge", "competitor", "admin"]
supported_languages = {"en_US":"English","fr_FR":"Francais","pl_PL":"Polski"}
first_default_language = "fr_FR"
age_category_type2021 = "fsgt2021" # old age categories
age_category_type2026 = "fsgt2026" # new age categories
age_category_types = {"fsgt2021": age_category_type2021, "fsgt2026": age_category_type2026}
competition_type_adult = "adult"
competition_type_ado = "ado"
competition_types = {"adult":competition_type_adult, "ado":competition_type_ado,}
gym_status = {"created":0, "confirmed":1, "active":3, "inactive":4, "deleted":5}
categories = {0:"Category 0",
1:"Category 1",
2: "Category 2"}
reference_data = { "categories":categories,# "categories_ado":categories_ado,
"clubs":clubs, "competition_status": competition_status, "colors_fr":colors,
"supported_languages":supported_languages, "route_finish_status": activities_db.route_finish_status,
"competition_types":competition_types, "gym_status":gym_status}
from src.email_sender import EmailSender
# Initialize EmailSender with necessary configurations
email_sender = EmailSender(
reference_data=reference_data
)
# called from main_app_ui
def addCompetition(compId, added_by, name, date, routesid, max_participants, competition_type, instructions, calc_type=CalculationStrategy.calc_type_fsgt1):
if compId is None:
compId = str(uuid.uuid4().hex)
routes = skala_db.get_routes_by_id(routesid)
gym = skala_db.get_gym_by_routes_id(routesid)
if gym is None:
raise ValueError('Gym not found')
if (routes is None or len(routes)==0):
raise ValueError('Routes not found')
if max_participants is None:
max_participants=80
#sanitized_instruction = re.sub(r'[^\w\s]', '', instruction)
competition = {
"id": compId, "name": name, "date": date, "gym": gym['name'],"gym_id":gym['id'],
"routesid": routesid, "status": "preopen",
"max_participants": max_participants,
"results": copy.deepcopy(CalculationStrategy.emptyResults),
"calc_type": CalculationStrategy.normalize_strategy_key(1), # default to fsgt1
"competition_type":competition_type,
"age_category_type" : age_category_type2026, # fsgt0 for old age categories (16-49, 50+), fsgt1 for new age categories (16-39, 40-49, 50+)
"instructions": instructions,
"added_by": added_by,
"status" : competition_status_created,
"routes": routes.get('routes'),
"climbers": {}}
# write this competition to db
skala_db._add_competition(compId, competition);
return compId
# also used to update max_participants
def update_competition_details(competition, name, date, instructions):
competition['name']=name
competition['date'] = date
competition['instructions'] = instructions
# update age_category_type slugs for climbers because date of competition may have changed
_update_competition(competition['id'], competition)
return competition
# this updates the routeset of a competition
def update_competition_routes(competition, routesid, force=False):
# only update routes if it is different
#if competition.get('routes') is None or competition.get('routesid') != routesid:
if routesid is None:
logging.error('Routesid cannot be None '+str(routesid))
raise ValueError('Cannot update competition routeset. routesid cannot be None')
competition['routesid'] = routesid
routes = skala_db.get_routes_by_id(routesid)
if (routes is None or len(routes)==0):
logging.error('Routes not found '+str(competition.get('id')))
raise ValueError('Routes not found')
if competition.get('status') in [competition_status_closed]:
if not force:
logging.error('Cannot update routes when competition is closed '+str(competition.get('id')))
raise ValueError('Cannot update routes when competition is closed')
competition['routes'] = routes.get('routes')
# after a new routeset is set, we need to update each climber with routes they climbed
try:
setRoutesClimbed2(competition)
except Exception as e:
logging.error('error setting routes climbed2: ' + str(e))
raise ValueError('Cannot update competition routeset. ' + str(e))
skala_db._update_competition(competition['id'], competition)
return competition
# compare the competition's static routeset with the current routeset in the db
# the competition routeset is a snapshot taken when the routeset was assigned
# if the db routeset has been modified since, this returns the differences
def get_routeset_differences(competition):
routesid = competition.get('routesid')
if routesid is None:
return None
comp_routes = competition.get('routes') or []
db_routeset = skala_db.get_routes_by_id(routesid)
if db_routeset is None:
return {'error': 'routeset not found in db', 'routesid': routesid}
db_routes = db_routeset.get('routes') or []
# build lookup by route id
comp_by_id = {str(r.get('id')): r for r in comp_routes}
db_by_id = {str(r.get('id')): r for r in db_routes}
added = [] # routes in db but not in competition
removed = [] # routes in competition but not in db
modified = [] # routes present in both but with different field values
for rid, route in db_by_id.items():
if rid not in comp_by_id:
added.append(route)
elif route != comp_by_id[rid]:
modified.append({'id': rid, 'competition': comp_by_id[rid], 'db': route})
for rid, route in comp_by_id.items():
if rid not in db_by_id:
removed.append(route)
has_differences = len(added) > 0 or len(removed) > 0 or len(modified) > 0
return {
'has_differences': has_differences,
'added': added,
'removed': removed,
'modified': modified
}
# add or register climber to a competition
# no more anonymous climbers so climberid is required
def addClimber(climberId, competitionId, email, name, firstname, lastname, club_name, gymid, sex, category):
logging.info("adding climber to competition "+str(climberId))
if email is None:
raise ValueError('Email cannot be None')
email = email.lower()
if climberId is None:
raise ValueError('Climber ID cannot be None')
try:
category = int(category)
except:
raise ValueError('category must be an integer')
if sex == 'm' or sex == 'M':
sex = 'M'
elif sex == 'f' or sex == 'F':
sex = 'F'
else:
raise ValueError('Only valid values are mfMF')
try:
sql_lock.acquire()
competition = get_competition(competitionId)
climbers = competition['climbers']
#logging.info(climbers)
# Check if this specific climber ID is already registered
if climberId in climbers:
raise ValueError('User with id '+climberId+' already registered')
# Check email duplicates only for non-supervised accounts
# (supervised dependents share the guardian's email)
# not sure if this is needed since we check that climber id is not already registered
for cid in climbers:
existing = climbers.get(cid)
if existing.get('email', '').lower() == email.lower() and cid != climberId:
# Allow same email if one is a supervised dependent (different climberId)
# Only block if both are the same person (same email, not a dependent scenario)
existing_is_supervised = skala_db.get_user(cid)
if existing_is_supervised is None or existing_is_supervised.get('account_type') != 'supervised':
new_is_supervised = skala_db.get_user(climberId)
if new_is_supervised is None or new_is_supervised.get('account_type') != 'supervised':
raise ValueError('User with email '+email+' already registered')
climbers[climberId] = {
"id":climberId, "email":email, "name":name, "firstname":firstname, "lastname":lastname,
"club" :club_name,
"gymid": gymid,
"sex":sex, "category":category,
"age_category_type": age_category_type2026, # default to fsgt1 age categories
"score":0, "rank":0,
"registration_timestamp": datetime.now().isoformat(),
"routesClimbed":[],
"routesClimbed2":[]
}
#logging.info(competition)
_update_competition(competitionId, competition)
except Exception as e:
logging.error(f'Error adding climber to the competition {email}: {str(e)}')
raise
finally:
sql_lock.release()
return climbers[climberId]
def _guess_competition_age_category_type(competition_date, competition_type):
competition_date_dt = datetime.strptime(competition_date, "%Y-%m-%d")
age_category_type = None
if competition_type is competition_type_ado:
age_category_type = age_category_type2026
else:
if competition_date_dt < datetime.strptime('2025-08-31', "%Y-%m-%d"):
age_category_type = age_category_type2021
else:
age_category_type = age_category_type2026
return age_category_type
def get_category_from_dob(dob, competition_date, competition_type, age_category_type=None):
if dob is None:
return -1
dob_dt = datetime.strptime(dob, "%Y-%m-%d")
competition_dt = datetime.strptime(competition_date, "%Y-%m-%d")
# Calculate age as of August 31st of the season start year
# Season runs Sep-Jun, so if competition is Jan-Aug, use previous year's Aug 31
if competition_dt.month < 9: # January to August
reference_year = competition_dt.year - 1
else: # September to December
reference_year = competition_dt.year
august_31st = datetime(reference_year, 8, 31)
age = august_31st.year - dob_dt.year - ((august_31st.month, august_31st.day) < (dob_dt.month, dob_dt.day))
if age < 12:
return -1 # Return -1 for under 12
if age_category_type is None:
age_category_type = _guess_competition_age_category_type(competition_date, competition_type)
if competition_type == competition_type_ado:
if age >= 17:
return -1
else:
if age <= 17:
return -1
if age_category_type == age_category_type2026:
# fsgt1 age categories
if 18 <= age <= 39:
return 0
elif 40 <= age <= 49:
return 1
elif age >= 50:
return 2
elif 12 <= age <= 13:
return 0
elif 14 <= age <= 15:
return 1
elif 16 <= age <= 17:
return 2
else:
return -1 # Return -1 if age does not fit any category
else:
if 18 <= age <= 49:
return 0
elif 50 <= age <= 64:
return 1
elif age >= 65:
return 2
elif 12 <= age <= 13:
return 0
elif 14 <= age <= 15:
return 1
elif 16 <= age <= 17:
return 2
else:
return -1 # Return -1 if age does not fit any category
# remove or unregister climber from a competition
# only possible if competition is not started yet
def removeClimber(climberId, competitionId):
try:
sql_lock.acquire()
competition = get_competition(competitionId)
climbers = competition['climbers']
if climberId not in climbers:
raise ValueError('Cannot remove climber, not registered')
del climbers[climberId]
competition = _update_competition(competitionId, competition)
return competition
finally:
sql_lock.release()
# sort climbers by registration date and puts them on waiting list if needed
# based on max participants
# if registration date is missing, assume the current list order is the registration order
def _recalculate_waiting_list(competition):
climbers = competition['climbers']
# sort climbers by registration date
#sorted_climbers = sorted(climbers.items(), key=lambda x: x[1].get('registration_timestamp'))
for index, (climberId, climberData) in enumerate(climbers.items()):
if index >= int(competition.get('max_participants', 0)):
climbers[climberId]['registration_status'] = 'waiting'
else:
climbers[climberId]['registration_status'] = 'registered'
return competition
def get_climber_json(climberId, email, name, firstname, lastname, club, sex, category=0):
climber_json = {"id": climberId, "email": email, "name": name, "firstname": firstname, "lastname": lastname,
"club": club, "sex": sex, "category": category, "routesClimbed": [], "score": 0, "rank": 0}
def setClimberPresence(competitionId, climberId, present=True ):
try:
sql_lock.acquire()
comp = get_competition(competitionId)
climber = comp['climbers'][climberId]
if climber is None:
return
climber['present'] = present
_update_competition(competitionId, comp)
finally:
sql_lock.release()
return comp
def getCompetitions():
return get_all_competitions()
def getClimber(competitionId, climberId):
comp = get_competition(competitionId)
return comp['climbers'][climberId]
def getFlatCompetition(competitionId):
print("retreiving flat competition " + str(competitionId))
competition = get_competition(competitionId)
for climberid in competition['climbers']:
data = competition['climbers'][climberid]
for i in range(100):
if (i in competition['climbers'][climberid]['routesClimbed']):
data['r' + str(i)] = 1
else:
data['r' + str(i)] = 0
return competition
def getCompetition(competitionId):
return get_competition(competitionId)
def addRouteClimbed(competitionId, climberId, routeNumber):
#print(comps)
#comp = comps[competitionId]
try:
sql_lock.acquire()
comp = get_competition(competitionId)
climber = comp['climbers'][climberId]
if climber is None:
return
routes_climbed = climber['routesClimbed']
#print (routes_climbed)
routes_climbed.append(routeNumber)
_update_competition(competitionId, comp)
finally:
sql_lock.release()
return comp
# update each climber with routes they climbed
# the routes array is made of up the same entries as routes in gym
# routesClimbed2 is calculated from routes object set on competition (not from db based on routesid)
# returns the competition
# no db update
def setRoutesClimbed2(competition):
if competition.get('routes') is None or competition.get('routesid') is None:
raise ValueError('Routes on competition not found')
for climber in competition['climbers']:
climber = competition['climbers'][climber]
climber['routesClimbed2'] = []
if climber is None:
return
climber['routesClimbed2'] = []
for route in climber['routesClimbed']:
if competition.get('routes') is not None:
for route2 in competition['routes']:
if str(route2.get('routenum')) == str(route):
climber['routesClimbed2'].append(route2)
return competition
# update climber with a list of routes they climbed
# the list is a list of route numbers so the lowest number is 1 (not 0)
def setRoutesClimbed(competitionId, climberId, routeList):
try:
sql_lock.acquire()
comp = get_competition(competitionId)
climber = comp['climbers'][climberId]
if climber is None:
return
climber['routesClimbed'] = []
for route in routeList:
routes_climbed = climber['routesClimbed']
#print(routes_climbed)
routes_climbed.append(route)
setRoutesClimbed2(comp)
comp = recalculate(competitionId, comp)
comp = _update_competition(competitionId, comp)
finally:
sql_lock.release()
return comp
def update_competition(competitionId, competition):
_update_competition(competitionId, competition)
# check and remove (this is part of CalculationStrategy)
def get_route_repeats(sex, comp):
# Use resolved strategy
# Prefer slug in `calc_type`; fall back to legacy `calc_type`
key = comp.get('calc_type')
strategy = CalculationStrategy.create_strategy(key)
return strategy._getRouteRepeats(sex, comp)
def recalculate(competitionId, comp=None):
#logging.info('calculating...')
try:
sql_lock.acquire()
if comp is None:
comp = get_competition(competitionId)
if comp is None:
return
# Resolve calculation strategy via registry (supports legacy ints and slugs)
key = comp.get('calc_type')
strategy = CalculationStrategy.create_strategy(key)
# Use the strategy to recalculate the competition
strategy.recalculate(comp)
if comp is None:
comp = _update_competition(competitionId, comp)
finally:
sql_lock.release()
return comp
# returns sorted arrays based on rank
def get_sorted_rankings(competition):
rankings = {}
rankings['F'] = [] # only used for FSGT0
rankings['M'] = [] # only used for FSGT0
rankings['0F'] = []
rankings['1F'] = []
rankings['2F'] = []
rankings['0M'] = []
rankings['1M'] = []
rankings['2M'] = []
rankings['A'] = [] # replaces M and F rankings after men's and women's points were combined in FSGT1
#rankings['club'] = []
# scratch first
for climberid in competition.get('climbers'):
climber = competition.get('climbers').get(climberid)
rank = int(climber['rank'])
#rankings[climber['sex']].insert(rank-1, climber)
# sort by awayPoints, then position; note the lambda uses a tuple
a = competition.get('climbers').values()
#clubs = set(competition.get('climbers')[k]['category'])
clubs = reduce(lambda acc, c: acc.update({ competition['climbers'][c]['club'] :{"M":0, "F":0, "MC":0, "FC":0, "TOTAL":0 }})
or acc if competition['climbers'][c]['club'] not in acc else acc,
competition.get('climbers'), {})
# do not generate rankings for all users together for the fsgt0 calculation
# because in fsgt0 points for each route are divided separately by men and woman
# so it does not make sense to rank them together
# Only build the 'A' ranking when strategy is not fsgt0 (sex-separated)
if CalculationStrategyFsgt0.name != CalculationStrategy.normalize_strategy_key(competition.get('calc_type')):
for itemid in sorted(competition.get('climbers'),
key=lambda k: (competition.get('climbers')[k]['score']),
reverse=True):
climber = competition.get('climbers').get(itemid)
rankings['A'].append(climber)
for itemid in sorted(competition.get('climbers'),
key=lambda k: (competition.get('climbers')[k]['sex'], competition.get('climbers')[k]['score']),
reverse=True):
climber = competition.get('climbers').get(itemid)
rankings[climber['sex']].append(climber)
for itemid in sorted(competition.get('climbers'),
key=lambda k: (competition.get('climbers')[k]['sex'], competition.get('climbers')[k]['category'], competition.get('climbers')[k]['score']),
reverse=True):
climber = competition.get('climbers').get(itemid)
catcode = str(climber['category'])+str(climber['sex'])
rankings[catcode].append(climber)
sex = climber['sex']
classement = len(rankings[catcode])
if climber['score']==0:
continue
# add one point for each climber
points = clubs[climber['club']][sex]
clubs[climber['club']][sex] = points + 1
if classement<6:
points = clubs[climber['club']][sex+"C"]
clubs[climber['club']][sex+"C"] = points + 6 - classement
for clubname in clubs:
total = clubs[clubname]['M']+clubs[clubname]['F']+clubs[clubname]['MC']+clubs[clubname]['FC']
clubs[clubname]['TOTAL'] = total
sortedclubs = []
prevTotal = -1
#prevClub
rank = 0
for club in sorted(clubs, key=lambda x:(clubs[x]['TOTAL'], clubs[x]['F']+clubs[x]['M'], clubs[x]['F']),reverse=True):
if club in ['other','Autre club non répertorié']:
continue
clubs[club]['name'] = club
if prevTotal != clubs[club]['TOTAL']:
rank = rank + 1
prevTotal = clubs[club]['TOTAL']
else:
if clubs[club]['M'] == clubs[prevClub]['M']:
if clubs[club]['F'] < clubs[prevClub]['F']:
rank = rank + 1
else:
rank = rank + 1
clubs[club]['rank'] = rank
sortedclubs.append(clubs[club])
prevClub = club
rankings['club']=sortedclubs
return rankings
def calculate_score(grades):
points_per_grade = {
'1': 1,
'2': 4,
'3': 16,
'4a': 64,
'4b': 256,
'4c': 1024,
'5a': 4096,
'5a+': 8096,
'5b': 16384,
'5b+': 32384,
'5c': 65536,
'5c+': 125384,
'6a': 262144,
'6a+': 524288,
'6b': 1048576,
'6b+': 2097152,
'6c': 4194304,
'6c+': 8388608,
'7a': 16777216,
'7a+': 33554432,
'7b': 67108864,
'7b+': 134217728,
'7c': 268435456,
'7c+': 536870912,
'8a': 1073741824,
'8a+': 2147483648,
'8b': 4294967296,
'8b+': 8589934592,
'8c': 17179869184,
'8c+': 34359738368,
'9a': 68719476736,
'9a+': 137438953472,
'9b': 274877906944,
'9b+': 549755813888,
'9c': 1099511627776
}
score = 0
for i, grade in enumerate(grades):
if grade in points_per_grade:
points = points_per_grade[grade]
if i > 0 and grades[i-1].endswith('+'):
points /= 2
score += points
return score
def test_calcul():
test_data = []
test_data.append(['6a','2'])
test_data.append(['4a','4b','5a','2'])
test_data.append(['4a','4b','5a'])
test_data.append(['4a','4b','6a','5a','2'])
test_data.append(['4a','4b','6a','5b','2'])
test_data.append(['4a','4b','6a','5a','7a'])
def avg(grades):
# create a dictionary to convert grades to numbers
grade_dict2 = {"1": 0, "2": 1, "3": 2, "4a": 3, "4b": 4, "4c": 5, "5a": 6, "5b": 7, "5c": 8, "6a": 9,
"6a+": 10, "6b": 11, "6b+": 12, "6c": 13, "6c+": 14, "7a": 15, "7a+": 16, "7b": 17,
"7b+": 18, "7c": 19, "7c+": 20, "8a": 21, "8a+": 22, "8b": 23, "8b+": 24, "8c": 25,
"8c+": 26, "9a": 27, "9a+": 28, "9b": 29, "9b+": 30, "9c": 31}
grade_dict = {'1': 1, '2': 2, '3': 3, '4a': 4.1, '4b': 4.4, '4c': 4.7,
'5a': 5.2, '5b': 5.5, '5c': 5.8, '6a': 6.1, '6a+': 6.2,
'6b': 6.4, '6b+': 6.5, '6c': 6.7, '6c+': 6.8, '7a': 7.1,
'7a+': 7.2, '7b': 7.4, '7b+': 7.5, '7c': 7.7, '7c+': 7.8,
'8a': 8.1, '8a+': 8.2, '8b': 8.4, '8b+': 8.5, '8c': 8.7, '8c+': 8.8,
'9a': 9.1, '9a+': 9.2, '9b': 9.5, '9b+': 9.6, '9c': 9.9}
# convert grades to numbers
nums = [grade_dict[g] for g in grades]
# calculate the average number
avg_num = sum(nums) / len(nums)
avg_grade = ""
# Convert the grades to numerical values and calculate the mean
grade_sum = sum([grade_dict[grade] for grade in grades])
mean_num = grade_sum / len(grades)
mean_grade=''
# convert the average number back to a grade
for g, n in grade_dict.items():
if n == round(avg_num):
avg_grade= g
if n == round(mean_num):
mean_grade= g
return {'avg':avg_grade,'avg_num':avg_num, 'mean':mean_grade, 'mean_num':mean_num}
def mean_climbing_grade(grades):
# Define a dictionary to map the letter grades to numerical values
grade_values = {'1': 1, '2': 2, '3': 3, '4a': 4.1, '4b': 4.4, '4c': 4.7,
'5a': 5.2, '5b': 5.5, '5c': 5.8, '6a': 6.1, '6a+': 6.2,
'6b': 6.4, '6b+': 6.5, '6c': 6.7, '6c+': 6.8, '7a': 7.1,
'7a+': 7.2, '7b': 7.4, '7b+': 7.5, '7c': 7.7, '7c+': 7.8,
'8a': 8.1, '8a+': 8.2, '8b': 8.4, '8b+': 8.5, '8c': 8.7, '8c+': 8.8,
'9a': 9.1, '9a+': 9.2, '9b': 9.5, '9b+': 9.6, '9c': 9.9}
# Convert the grades to numerical values and calculate the mean
grade_sum = sum([grade_values[grade] for grade in grades])
mean_grade = grade_sum / len(grades)
return mean_grade
def calculate_average_score(routes):
score_dict = {
"1": 1,
"2": 2,
"3": 3,
"4a": 4.1,
"4b": 4.2,
"4c": 4.3,
"5a": 5.1,
"5b": 5.2,
"5c": 5.3,
"6a": 6.1,
"6a+": 6.15,
"6b": 6.2,
"6b+": 6.25,
"6c": 6.3,
"6c+": 6.35,
"7a": 7.1,
"7a+": 7.15,
"7b": 7.2,
"7b+": 7.25,
"7c": 7.3,
"7c+": 7.35,
"8a": 8.1,
"8a+": 8.15,
"8b": 8.2,
"8b+": 8.25,
"8c": 8.3,
"8c+": 8.35,
"9a": 9.1,
"9a+": 9.15,
"9b": 9.2,
"9b+": 9.25,
"9c": 9.3,
}
score_total = 0
count = 0
route_counts = {}
for route in routes:
if route in score_dict:
if route in route_counts:
route_counts[route] += 1
else:
route_counts[route] = 1
count += 1
for route, count in route_counts.items():
score_total += score_dict[route] * count ** 0.5
if count == 0:
return 0
else:
return round(score_total / count * count ** 0.25, 2)
lru_cache.DEBUG = True
def init():
logging.info('initializing competition engine...')
skala_db.init()
#user_authenticated_fb("c1", "Bob Mob", "bob@mob.com",
# "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10224632176365169&height=50&width=50&ext=1648837065&hash=AeTqQus7FdgHfkpseKk")
#user_authenticated_fb("c1", "Bob Mob2", "bob@mob.com",
# "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10224632176365169&height=50&width=50&ext=1648837065&hash=AeTqQus7FdgHfkpseKk")
#user_authenticated_fb("c2", "Mary J", "mary@j.com",
# "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10224632176365169&height=50&width=50&ext=1648837065&hash=AeTqQus7FdgHfkpseKk")
activities_db.init()
for competition in skala_db.get_all_competitions().values():
_migrate_competition(competition)
logging.info('created ' + COMPETITIONS_DB)
logging.info("running user migrations - adding gymid to users...")
emails = get_all_user_emails() # select email from climbers table
for email in emails:
user = get_user_by_email(email)
if user is None:
logging.info('no climber in db for email: '+str(email))
continue
if user.get('gymid') is None:
if user.get('club') is not None:
gym = skala_db.get_gym_by_gym_name(user['club'])
if gym is not None:
user['gymid'] = gym['id']
logging.info('adding gymid: '+str(gym['id'])+' for user '+str(user['email']))
skala_db.upsert_user(user)
elif user.get('club') in CLUB_TO_GYMID:
user['gymid'] = CLUB_TO_GYMID[user.get('club')]
skala_db.upsert_user(user)
else:
logging.info('no gym found for club: '+str(user['club'])+' for user '+str(user['email'])+' confirmed='+str(user.get('is_confirmed')))
#user['gymid'] = ''
skala_db.update_gym_data(reference_data)
skala_db.update_users_data()
skala_db.update_competitions_data()
#internal method.. not locked!!!
def _update_competition(compId, competition):
if compId is None:
raise ValueError("cannot update competition with None key");
competition = _recalculate_waiting_list(competition)
db = lite.connect(COMPETITIONS_DB)
cursor = db.cursor()
cursor.execute("update " + COMPETITIONS_TABLE + " set jsondata=? where id=? ",
[json.dumps(competition), compId])
#logging.info('updated competition: '+str(compId))
db.commit()
db.close()
return competition