def __init__(self, request): super().__init__(request) self.validation_table = { 'base_table_invalid': {'_state', 'event_rotation_detail'}, 'base_form_invalid': { '_state', 'id', 'event_school_ids', 'event_team_number', 'event_create_time' }, } self.assoc_class_activity = EventActivity self.assoc_class_team = Team self.assoc_class_school = School self.assoc_class_team_link = EventTeam self.assoc_class_tag = EventTag self.assoc_class_summary = Summary self.assoc_class_season = Season self.event_race_tag = [ EventTag.DEFAULT_EVENT_TAGS + ' {}'.format(MiscFunctions.getAlphabet(i)) for i in range(2) ] self.event_team_name_suffix = [ Team.TEAM_NAME_SUFFIX + ' {}'.format(MiscFunctions.getAlphabet(i)) for i in range(2) ] self.event_activity_type = EventActivity.ACTIVITY_TYPE_RACE
def getTableRowContent(self, content): field_data = MiscFunctions.filterDict(self.useAPI(self.base_class).getSelf(id=content.id).__dict__.items(), self.validation_table['base_table_invalid']) field_data = self.updateChoiceAsValue(field_data, self.getChoiceData()) field_data = self.updateDBMapAsValue(field_data, self.getDBMap(field_data)) field_data = MiscFunctions.grabValueAsList(field_data) return field_data
def getFieldData(self, **kwargs): action = kwargs.pop('action') element_id = kwargs.pop('element_id') field_data = dict(event_type=EventType.FLEET_RACE) if self.populate_data_dispatcher.get(action): raw_data = EventAPI(self.request).editSelf(id=element_id).__dict__ field_data = MiscFunctions.filterDict(raw_data.items(), self.validation_set) field_data['event_team'] = raw_data['event_school_ids'] field_data = MiscFunctions.serializeJSONListData( ['event_school_ids', 'event_rotation_detail'], field_data) return field_data return field_data
def getFieldData(self, **kwargs): action = kwargs.pop('action') element_id = kwargs.pop('element_id') field_data_dispatcher = self.populateDispatcher() if field_data_dispatcher.get(action): base_data = MiscFunctions.filterDict( self.useAPI( self.base_class).getSelf(id=element_id).__dict__.items(), self.validation_table['base_form_invalid']) account_data = MiscFunctions.filterDict( self.useAPI(self.assoc_class_account).getSelf( account_linked_id=element_id).__dict__.items(), self.validation_table['account_invalid']) field_data = {**base_data, **account_data} return field_data return None
def processDispatch(self, request, dispatch_path, param=''): page = self.setProcessDispatcher().get(dispatch_path)(request, param) return self.__authenticateModule( request=request, callback=lambda: page.process(), failure=lambda: MiscFunctions.lraise(Exception("Insufficient Permission to Access Module Process")) )
def getTableRowContent(self, content): field_data = MiscFunctions.filterDict( self.useAPI( self.base_class).getSelf(id=content.id).__dict__.items(), self.validation_table['base_table_invalid']) start_date = field_data['event_start_date'] end_date = field_data['event_end_date'] date = str(start_date) + ' to ' + str(end_date) del field_data['event_start_date'] del field_data['event_end_date'] field_data['date'] = date field_data = self.updateChoiceAsValue(field_data, self.getChoiceData()) field_data = self.serializeJSONListData( ['event_school_ids', 'event_rotation_detail'], field_data) field_data = MiscFunctions.grabValueAsList(field_data) return field_data
def getRowContent(self, model_object): field_data = MiscFunctions.filterDict( EventAPI( self.request).getSelf(id=model_object.id).__dict__.items(), self.validation_set) date = '{} to {}'.format(str(field_data['event_start_date']), str(field_data['event_end_date'])) del field_data['event_start_date'] del field_data['event_end_date'] field_data['date'] = date field_data = MiscUtils(self.request).updateChoiceAsValue( field_data, FleetRaceForm(self.request, self.app_name, self.base_class, self.mutable, self.guard).getChoiceData()) field_data = MiscFunctions.serializeJSONListData( ['event_school_ids', 'event_rotation_detail'], field_data) field_data = MiscFunctions.grabValueAsList(field_data) return field_data
def updateRotationArray(action, array): if action == 'add': if len(array) % 2 == 0: array.append(MiscFunctions.modAdd(array[-1]-1, 2, team_num)) else: array.append(array[len(array)-1]) return array elif action == 'delete': array.pop() return array
def render(self, **kwargs): route = kwargs.pop('route') query_term_parser = QueryTermUtils(self.request) table_header = self.getHeader() table_content = self.getBody( query_term_parser.getRangeTerms(), **MiscFunctions.updateDict(query_term_parser.getFilterTerms(), self.injectTableFilter())) return Table(current_class=self.base_class, title=route).buildTable(table_header, table_content)
def eqtParser(equation_string): replace_dict = dict(RACE=event.event_race_number, TEAM=event.event_team_number) arithmetic_exp = MiscFunctions.simpleEqtFormatter( equation_string, replace_dict) try: result = int(EquationParser().eval(arithmetic_exp)) except: result = replace_dict['RACE'] + 1 return result
def actionEditDelete(choice): choiceDict = {"edit": "_edit_form", "delete": "_delete_form"} if element_id is None: return HttpResponse('{"Response": "Error: No Element ID Provided"}') else: self.request.session[self.session_name] = MiscFunctions.getViewJSON(action, element_id) element = currentClass.objects.get(pk=int(element_id)) action_type = dict(form=True) content = Form(choiceDict[choice], form_path, action, self.destination, self.view_dispatcher.get(self.form_path)["form"](instance=element)) return dict(page_title=page_title, type=action_type, context=content)
def getFieldData(self, **kwargs): action = kwargs.pop('action') element_id = kwargs.pop('element_id') field_data_dispatcher = self.populateDispatcher() if field_data_dispatcher.get(action): field_data = MiscFunctions.filterDict( self.useAPI( self.base_class).editSelf(id=element_id).__dict__.items(), self.validation_table['base_form_invalid']) return field_data return None
def updateIndividualRotation(individual_rotation): if action == AuthenticationActionType.ADD: if not len(individual_rotation) % 2: individual_rotation.append( MiscFunctions.modAdd(individual_rotation[-1] - 1, 2, self.event.event_team_number)) else: individual_rotation.append(individual_rotation[-1]) return individual_rotation elif action == AuthenticationActionType.DELETE: return individual_rotation[:-1]
def getTableRowContent(self, content): base_data = MiscFunctions.filterDict( self.useAPI( self.base_class).getSelf(id=content.id).__dict__.items(), self.validation_table['base_table_invalid']) base_data = self.updateChoiceAsValue(base_data, self.getChoiceData()) base_data = MiscFunctions.grabValueAsList(base_data) invalid_table = self.validation_table['account_invalid'] invalid_table.add('account_password') try: account_data = MiscFunctions.grabValueAsList( MiscFunctions.filterDict( self.useAPI(self.assoc_class_account).getSelf( account_linked_id=content.id).__dict__.items(), invalid_table)) except Exception: account_data = MiscFunctions.grabValueAsList({'account_email': ''}) field_data = base_data + account_data return field_data
def loadView(actionClass): return (lambda x: render( self.request, self.page_path, MiscFunctions.updateDict( x( currentClass(self.request).grabData( action, form_path, element_id)), dict(auth=self.permission_obj().getIdentifier(), template_base=self.template_base))) if x else HttpResponse( '{"Response": "Error: Insufficient Parameters"}') )(actionClass)
def __init__(self, request): self.event_type = 'fleet race' super().__init__(request) self.assoc_class_activity = EventActivity self.assoc_class_team = Team self.assoc_class_school = School self.assoc_class_team_link = EventTeam self.assoc_class_tag = EventTag self.assoc_class_type = EventType self.assoc_class_summary = Summary self.assoc_class_season = Season self.event_race_tag = [ EventTag.DEFAULT_EVENT_TAGS + ' {}'.format(MiscFunctions.getAlphabet(i)) for i in range(2) ] self.event_team_name_suffix = [ Team.TEAM_NAME_SUFFIX + ' {}'.format(MiscFunctions.getAlphabet(i)) for i in range(2) ] self.event_activity_type = EventActivity.ACTIVITY_TYPE_RACE
def generalViewDisplay(): def actionView(): action_type = dict(table=True) table = Table(currentClass, self.form_path).makeTable() content = [table] return dict(page_title=page_title, type=action_type, context=content) def actionAdd(): self.request.session[self.session_name] = MiscFunctions.getViewJSON(action, None) action_type = dict(form=True) content = Form('_add_form', form_path, action, self.destination, self.view_dispatcher.get(self.form_path)["form"]()) return dict(page_title=page_title, type=action_type, context=content) def actionEditDelete(choice): choiceDict = {"edit": "_edit_form", "delete": "_delete_form"} if element_id is None: return HttpResponse('{"Response": "Error: No Element ID Provided"}') else: self.request.session[self.session_name] = MiscFunctions.getViewJSON(action, element_id) element = currentClass.objects.get(pk=int(element_id)) action_type = dict(form=True) content = Form(choiceDict[choice], form_path, action, self.destination, self.view_dispatcher.get(self.form_path)["form"](instance=element)) return dict(page_title=page_title, type=action_type, context=content) def setFunctionDispatcher(): dispatcher = Dispatcher() dispatcher.add('view', actionView()) dispatcher.add('add', actionAdd()) dispatcher.add('edit', actionEditDelete('edit')) dispatcher.add('delete', actionEditDelete('delete')) return dispatcher action = (lambda x: x if x else 'view')(self.request.GET.get("action")) element_id = self.request.GET.get("element_id") page_title = (self.form_path + " " + action).title() currentData = (lambda x: x if x else None)(self.view_dispatcher.get(self.form_path)) currentClass = currentData["class"] functionDispatch = setFunctionDispatcher() return ( lambda x: render( self.request, self.page_path, MiscFunctions.updateDict( x, dict(auth=self.permission_obj().getIdentifier(), template_base=self.template_base) ) ) if x else HttpResponse( '{"Response": "Error: Insufficient Parameters"}') )(functionDispatch.get(action))
def actionAdd(data): self.request.session[ self.session_name] = MiscFunctions.getViewJSON( action, None) page_type = dict(form=True) content = Form( '_add_form', form_path, action, self.destination, self.view_dispatcher.get( self.form_path)["form"](data=data['data'])) specialContent = data['special_field'] return dict(page_title=page_title, type=page_type, context=content, special_context=specialContent)
def getFieldData(self, **kwargs): action = kwargs.pop('action') element_id = kwargs.pop('element_id') field_data_dispatcher = self.populateDispatcher() if field_data_dispatcher.get(action): raw_data = self.useAPI( self.base_class).editSelf(id=element_id).__dict__ field_data = MiscFunctions.filterDict( raw_data.items(), self.validation_table['base_form_invalid']) field_data['event_team'] = raw_data['event_school_ids'] field_data = self.serializeJSONListData( ['event_school_ids', 'event_rotation_detail'], field_data) return field_data return {'event_type': self.form_path}
def actionMutate(self, page_object, context, verify): route = self.param.get('route') action = self.request.GET.get("action", ActionType.VIEW) element_id = self.request.GET.get("element_id") if verify and element_id is None: raise Exception( "Element ID not defined for action {} at {}".format( action, route)) # Hydrating PageObject with additional data page_type = dict(form=True) page_object.context = MiscFunctions.updateDict(page_object.context, dict(type=page_type)) page_object.element = context
def __rotationGenerator(self, tag_dict, team_dict, event_race_number, event_team_number): rand_array = random.sample(range(1, event_team_number + 1), event_team_number) result_dict = dict() for shift, tag in enumerate(tag_dict): team_sequence = dict() for team_num, team_id in enumerate(team_dict[tag]): team_sequence[team_id] = [ MiscFunctions.modAdd(rand_array[team_num] + shift, (race - race % 2), event_team_number) for race in range(event_race_number) ] result_dict[tag_dict[tag]] = team_sequence return result_dict
def updateSchools(self, school_ids): schools = SchoolAPI(self.request).filterSelf(id__in=school_ids) # Return error if one or more of the school ids could not be found if not len(schools) == len(school_ids): raise Exception( "At least one of the school ids is invalid in updateSchools") old_school_ids = list( map(lambda x: int(x), self.event.event_school_ids)) # Finding all the elements in school_ids that are not already in old_school_ids, and its converse additionList = [e for e in school_ids if e not in old_school_ids] removalList = [e for e in old_school_ids if e not in school_ids] self.event.event_school_ids = school_ids self.event.event_team_number = len(school_ids) # Remove some boat identifiers if less schools, or add more non duplicate numbers if more schools boat_ids = self.event.event_boat_rotation_name.split(',') next_boat_id = (lambda m: m if m is not None else 0)( MiscFunctions.findMaxInStrArr(boat_ids)) + 1 new_boat_ids = boat_ids[:min(self.event.event_team_number, len(boat_ids))] + \ [str(next_boat_id + i) for i in range( max(0, self.event.event_team_number - len(boat_ids)) )] self.event.event_boat_rotation_name = ','.join(new_boat_ids) self.event.save() # Handling Addition first before deletion self.updateSummaryBySchool(additionList, AuthenticationActionType.ADD) self.updateEventTeams(additionList, AuthenticationActionType.ADD) self.updateEventActivities(additionList, AuthenticationActionType.ADD) self.updateEventTeamLinks(additionList, AuthenticationActionType.ADD) # Handling Deletion self.updateSummaryBySchool(removalList, AuthenticationActionType.DELETE) self.updateEventActivities(removalList, AuthenticationActionType.DELETE) self.updateEventTeamLinks(removalList, AuthenticationActionType.DELETE) self.updateEventTeams(removalList, AuthenticationActionType.DELETE) # Update rotation, previous doesn't have information about new teams self.event.event_rotation_detail = self.regenerateRotation() self.event.save() # Update Summary and League Scores self.recalculateScores()
def edit(key): event_activity = self.useAPI(self.base_class).editSelf(id=key) event_activity.event_activity_event_parent = int( [RequestFunctions.getSingleRequestObj(post_dict, self.search_name[0] + "_result")][0]) event_activity.event_activity_event_tag = int( [RequestFunctions.getSingleRequestObj(post_dict, self.search_name[1] + "_result")][0]) event_activity.event_activity_name = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_name') event_activity.event_activity_order = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_order') event_activity.event_activity_result = MiscFunctions.jsonLoadCatch( RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_result')) event_activity.event_activity_type = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_type') event_activity.event_activity_note = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_note') event_activity.event_activity_status = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_status') event_activity.save() LogFunctions.generateLog( self.request, 'admin', LogFunctions.makeLogQuery( self.base_class, action.title(), id=event_activity.id))
def genSchoolTable(region): schools = SchoolAPI(self.request).filterSelf( school_region=region).order_by('school_name') school_dict = list( map( lambda school: dict( school_name=school.school_name, school_team_name=school.school_default_team_name, school_status=school.school_status, school_season_score=MiscFunctions.truncateDisplayScore( LeagueScoringAPI(self.request). tryCompileThenCalculateScore(school)), school_link=reverse('client.view_dispatch_param', args= ["school_specific", school.id])), list(schools))) return school_dict
def add(): event_api = self.useAPI(self.assoc_class_event) event_activity = self.base_class() event_activity.event_activity_event_parent = int( [RequestFunctions.getSingleRequestObj(post_dict, self.search_name[0] + "_result")][0]) event_activity.event_activity_event_tag = int( [RequestFunctions.getSingleRequestObj(post_dict, self.search_name[1] + "_result")][0]) event_activity.event_activity_name = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_name') event_activity.event_activity_order = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_order') event_activity.event_activity_result = MiscFunctions.jsonLoadCatch( RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_result')) event_activity.event_activity_type = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_type') event_activity.event_activity_note = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_note') event_activity.event_activity_status = RequestFunctions.getSingleRequestObj(post_dict, 'event_activity_status') event_activity.save() LogFunctions.generateLog( self.request, 'admin', LogFunctions.makeLogQuery( self.base_class, action.title(), id=event_activity.id)) teams = event_api.getEventCascadeTeams(event_activity.event_activity_event_parent) matching_teams = list(filter(lambda x: x.team_tag_id == event_activity.event_activity_event_tag, teams)) for team in matching_teams: event_team = self.assoc_class_team_link() event_team.event_team_event_activity_id = event_activity.id event_team.event_team_id = team.id event_team.save() LogFunctions.generateLog( self.request, 'admin', LogFunctions.makeLogQuery( self.assoc_class_team_link, action.title(), id=event_team.id)) event = event_api.getSelf(id=event_activity.event_activity_event_parent) event_type = int(event.event_type) event_team_num = int(event.event_team_number) event_rotation = event.event_rotation_detail event_tag = event_activity.event_activity_event_tag new_rotation = {} if event_type == 1: new_rotation = self.__fleetRotationUpdater(event_tag, event_team_num, 'add', event_rotation) elif event_type == 2: new_rotation = self.__teamRotationUpdater() event.event_rotation_detail = new_rotation event.save() LogFunctions.generateLog( self.request, 'admin', LogFunctions.makeLogQuery( self.assoc_class_event, action.title(), id=event.id))
def actionEdit(data): if element_id is None: return HttpResponse( '{"Response": "Error: No Element ID Provided"}') else: self.request.session[ self.session_name] = MiscFunctions.getViewJSON( action, element_id) page_type = dict(form=True) content = Form( '_edit_form', form_path, action, self.destination, self.view_dispatcher.get( self.form_path)["form"](data=data['data'])) specialContent = data['special_field'] return dict(page_title=page_title, type=page_type, context=content, special_context=specialContent)
def regenerateRotation(self): rotation = dict() permutation = random.sample(range(1, self.event.event_team_number + 1), self.event.event_team_number) event_tags = EventTagAPI(self.request).verifySelf( legacy=False, event_tag_event_id=self.event.id) for boat_shift, tag in enumerate(event_tags): teams = TeamAPI(self.request).filterSelf(team_tag_id=tag.id) team_sequence = { team.id: [ MiscFunctions.modAdd(permutation[idx] + boat_shift, (race - race % 2), self.event.event_team_number) for race in range(self.event.event_race_number) ] for idx, team in enumerate(teams) } rotation[tag.id] = team_sequence return rotation
def updateEventTeams(self, school_ids, action): event_tags = EventTagAPI( self.request).filterSelf(event_tag_event_id=self.event.id) if action == AuthenticationActionType.ADD: schools = SchoolAPI(self.request).filterSelf(id__in=school_ids) for school in schools: for idx, tag in enumerate(event_tags): team_name = '{} {} {}'.format( school.school_default_team_name, Team.TEAM_NAME_SUFFIX, MiscFunctions.getAlphabet(idx)) TeamAPI(self.request).createSelf(team_name=team_name, team_school=school.id, team_status="active", team_tag_id=tag.id) elif action == AuthenticationActionType.DELETE: TeamAPI(self.request).deleteSelf( legacy=False, team_tag_id__in=[e.id for e in event_tags], team_school__in=school_ids).delete()
def genContent(self): content = list() # TODO: Remove these current season stuff as it will be handled by ModelAPI current_season = ConfigAPI( self.request).getConfig().config_current_season school_id = self.param.get("school_id") school = SchoolAPI(self.request).getSelf(id=school_id) participated_events = SchoolAPI(self.request).getParticipatedEvents( school_id, Event.EVENT_STATUS_DONE, current_season) rankingMap = SummaryAPI( self.request).getAllSummaryRankingBySchool(school_id) league_scoring_api = LeagueScoringAPI(self.request) average_events = list( filter( lambda event: event.event_name not in Event. EVENT_NAME_FINAL_RACE, participated_events)) final_events = list( filter( lambda event: event.event_name in Event.EVENT_NAME_FINAL_RACE, participated_events)) average_factor = league_scoring_api.getAverageFactor( school.school_region, len(average_events)) sorted_score_list = league_scoring_api.getReverseSortedEventScoresList( school, average_events) for event in participated_events: score = league_scoring_api.getScoreForEventBySchool( event, school, False) content.append( dict( event_id=event.id, event_name=event.event_name, event_url=self.__eventUrlTransformer(event.id), event_date=event.event_start_date, school_summary_ranking=rankingMap.get(event.id), school_summary_score=MiscFunctions.truncateDisplayScore( score), used_score_in_calculation=self.__checkIsScoreUsed( event, sorted_score_list, final_events, average_factor), )) content_list = sorted(content, key=lambda x: x.get('event_date')) return content_list
def updateEventActivities(self, school_ids, action): event_tags = EventTagAPI( self.request).filterSelf(event_tag_event_id=self.event.id) teams = TeamAPI(self.request).filterSelf( team_tag_id__in=[e.id for e in event_tags], team_school__in=school_ids) event_activities = EventActivityAPI(self.request).verifySelf( legacy=False, event_activity_event_parent=self.event.id) for activity in event_activities: ranking = activity.event_activity_result # Don't do anything if ranking is empty, because event is in the future if not ranking: continue # Add/delete the teams specified by school_ids, and commit to db for team in teams: if action == AuthenticationActionType.ADD: if activity.event_activity_event_tag == team.team_tag_id: ranking.update({team.id: ScoreMapping.DEFAULT_MAPPING}) elif action == AuthenticationActionType.DELETE: if activity.event_activity_event_tag == team.team_tag_id: ranking.pop(str(team.id)) # We need to adjust the ranking after deleting some teams if action == AuthenticationActionType.DELETE: # Ranking sorted by its integer, if it is string like 'DNF', set as 0 s_ranking = sorted( map( lambda x: (x[0], int(x[1])) if MiscFunctions.canConvertTo(int, x[1]) else (x[0], -1), ranking.items()), key=lambda k: k[1], ) count = 1 for team_id, rank in s_ranking: if not rank == -1: ranking.update({team_id: str(count)}) count += 1 activity.event_activity_result = ranking activity.save()