Esempio n. 1
0
    def __init__(self,
                 color=None,
                 sponsor_id=None,
                 league_id=None,
                 year=date.today().year):
        """ The constructor.

        Raises
            InvalidField
            SponsorDoesNotExist
            LeagueDoesNotExist
        """
        if color is not None and not string_validator(color):
            raise InvalidField(payload={'details': "Team - color"})
        if sponsor_id is not None and Sponsor.query.get(sponsor_id) is None:
            raise SponsorDoesNotExist(payload={'details': sponsor_id})
        if league_id is not None and League.query.get(league_id) is None:
            raise LeagueDoesNotExist(payload={'details': league_id})
        if year is not None and not year_validator(year):
            raise InvalidField(payload={'details': "Team - year"})
        self.color = color
        self.sponsor_id = sponsor_id
        self.league_id = league_id
        self.year = year
        self.kik = None
Esempio n. 2
0
    def update(self, color=None, sponsor_id=None, league_id=None, year=None):
        """Updates an existing team.

        Raises:
            InvalidField
            SponsorDoesNotExist
            LeagueDoesNotExist
        """
        # does nothing with espys given
        if color is not None and string_validator(color):
            self.color = color
        elif color is not None:
            raise InvalidField(payload={'details': "Team - color"})
        if (sponsor_id is not None
                and Sponsor.query.get(sponsor_id) is not None):
            self.sponsor_id = sponsor_id
        elif sponsor_id is not None:
            raise SponsorDoesNotExist(payload={'details': sponsor_id})
        if league_id is not None and League.query.get(league_id) is not None:
            self.league_id = league_id
        elif league_id is not None:
            raise LeagueDoesNotExist(payload={'details': league_id})
        if year is not None and year_validator(year):
            self.year = year
        elif year is not None:
            raise InvalidField(payload={'details': "Team - year"})
Esempio n. 3
0
 def get(self, sponsor_id):
     """
         GET request for Sponsor Object matching given sponsor_id
         Route: Routes['sponsor']/<sponsor_id:int>
         Returns:
             if found
                 status: 200
                 mimetype: application/json
                 data:
                     {sponsor_id:int,
                     sponsor_name :string,
                     link: string,
                     description: string,
                     active: boolean
                     }
             otherwise
                 status: 404
                 mimetype: application/json
                 data: None
     """
     # expose a single Sponsor
     entry = Sponsor.query.get(sponsor_id)
     if entry is None:
         raise SponsorDoesNotExist(payload={'details': sponsor_id})
     response = Response(dumps(entry.json()),
                         status=200,
                         mimetype="application/json")
     return response
    def post(self):
        """
            POST request for submitting a transaction
            Route: Route['bottransaction']
            Parameters:
                player_id: the id of the player submitting the receipt (int)
                amount: the amount spent (int)
                sponsor: the name of the sponsor (str)
                team_id: the id of the team (int)
            Returns:
                status: 200
                mimetype: application/json
                data: True
        """
        args = parser.parse_args()
        player_id = args['player_id']
        team_id = args['team_id']
        amount = args['amount']
        sponsor_name = args['sponsor']

        # ensure the player exists
        player = Player.query.get(player_id)
        if player is None:
            raise PlayerDoesNotExist(payload={'details': player_id})

        # ensure the team exist
        team = Team.query.get(team_id)
        if team is None:
            raise TeamDoesNotExist(payload={'details': team_id})

        # ensure the sponsor exists
        sponsor = Sponsor.query.filter_by(name=sponsor_name).first()
        if sponsor is None:
            raise SponsorDoesNotExist(payload={'details': sponsor_name})

        # player can only submit receipts to their own team
        if not team.is_player_on_team(player):
            raise PlayerNotOnTeam(payload={'details': player_id})

        # should be good to add the espy now
        espy = Espys(team_id=team.id,
                     sponsor_id=sponsor.id,
                     points=amount,
                     description="Bot transaction")
        DB.session.add(espy)
        DB.session.commit()
        handle_table_change(Tables.ESPYS)
        return Response(dumps(espy.id),
                        status=200,
                        mimetype="application/json")
 def put(self, sponsor_id):
     """
         PUT request for Sponsor
         Route: Routes['sponsor']/<sponsor_id:int>
         Parameters:
             sponsor_name: The Sponsor's name (string)
             link: the link to the sponsor (string)
             description: a description of the sponsor (string)
             active: 1 if the sponsor is active otherwise 0 (int)
         Returns:
             if found and successful
                 status: 200
                 mimetype: application/json
                 data: None
             if found but not successful
                 status: 409
                 mimetype: application/json
                 data: None
             otherwise
                 status: 404
                 mimetype: application/json
                 data: None
     """
     # update a single user
     sponsor = Sponsor.query.get(sponsor_id)
     link = None
     description = None
     name = None
     active = True
     if sponsor is None:
         raise SponsorDoesNotExist(payload={'details': sponsor_id})
     args = parser.parse_args()
     if args['sponsor_name']:
         name = args['sponsor_name']
     if args['link']:
         link = args['link']
     if args['description']:
         description = args['description']
     if args['active']:
         active = args['active'] == 1 if True else False
     sponsor.update(name=name,
                    link=link,
                    description=description,
                    active=active)
     DB.session.commit()
     response = Response(dumps(None),
                         status=200,
                         mimetype="application/json")
     handle_table_change(Tables.SPONSOR, item=sponsor.json())
     return response
Esempio n. 6
0
 def post(self):
     """
         POST request for submitting a transaction
         Route: Route['kiktransaction']
         Parameters:
             kik: the kik user name (str)
             amount: the amount spent (str)
             sponsor: the name of the sponsor (str)
         Returns:
             status: 200
             mimetype: application/json
             data: True
     """
     args = parser.parse_args()
     kik = args['kik']
     amount = args['amount']
     sponsor_name = args['sponsor']
     player = Player.query.filter_by(kik=kik).first()
     if player is None:
         # player is found
         raise PlayerNotSubscribed(payload={'details': kik})
     sponsor = Sponsor.query.filter_by(name=sponsor_name).first()
     if sponsor is None:
         # sponsor is not found
         raise SponsorDoesNotExist(payload={'details': sponsor_name})
     teams = find_team_subscribed(kik)
     if len(teams) == 0:
         # kik user is not subscribed to any teams
         raise PlayerNotSubscribed(payload={'details': kik})
     # always give points to team first subscribed to (of current year)
     espy = Espys(team_id=teams[0],
                  sponsor_id=sponsor.id,
                  points=amount,
                  description="Kik transaction")
     DB.session.add(espy)
     DB.session.commit()
     return Response(dumps(espy.id),
                     status=200,
                     mimetype="application/json")
Esempio n. 7
0
    def __init__(self,
                 team_id,
                 sponsor_id=None,
                 description=None,
                 points=0.0,
                 receipt=None,
                 time=None,
                 date=None):
        """The constructor.

            Raises:
                SponsorDoesNotExist
                TeamDoesNotExist
        """
        if not float_validator(points):
            raise InvalidField(payload={"details": "Game - points"})
        self.points = float(points)
        self.date = datetime.now()
        sponsor = None
        if sponsor_id is not None:
            sponsor = Sponsor.query.get(sponsor_id)
        self.receipt = receipt
        if sponsor_id is not None and sponsor is None:
            raise SponsorDoesNotExist(payload={"details": sponsor_id})
        team = Team.query.get(team_id)
        if team is None:
            raise TeamDoesNotExist(payload={"details": team_id})
        self.description = description
        self.team_id = team_id
        self.sponsor_id = sponsor_id
        self.kik = None
        if date is not None and not date_validator(date):
            raise InvalidField(payload={'details': "Game - date"})
        if time is not None and not time_validator(time):
            raise InvalidField(payload={'details': "Game - time"})
        if date is not None and time is None:
            self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M')
        else:
            self.date = datetime.today()
Esempio n. 8
0
 def delete(self, sponsor_id):
     """
         DELETE request for Sponsor
         Route: Routes['sponsor']/<sponsor_id:int>
         Returns:
             if found
                 status: 200
                 mimetype: application/json
                 data: None
             otherwise
                 status: 404
                 mimetype: application/json
                 data: None
     """
     # delete a single user
     sponsor = Sponsor.query.get(sponsor_id)
     if sponsor is None:
         # Sponsor is not in the table
         raise SponsorDoesNotExist(payload={'details': sponsor_id})
     DB.session.delete(sponsor)
     DB.session.commit()
     return Response(dumps(None), status=200, mimetype="application/json")
Esempio n. 9
0
    def update(self,
               team_id=None,
               sponsor_id=None,
               description=None,
               points=None,
               receipt=None,
               date=None,
               time=None):
        """Used to update an existing espy transaction.

            Raises:
                TeamDoesNotExist
                SponsorDoesNotExist
        """
        if points is not None:
            self.points = points
        if description is not None:
            self.description = description
        if team_id is not None:
            if Team.query.get(team_id) is not None:
                self.team_id = team_id
            else:
                raise TeamDoesNotExist(payload={"details": team_id})
        if sponsor_id is not None:
            if Sponsor.query.get(sponsor_id) is not None:
                self.sponsor_id = sponsor_id
            else:
                raise SponsorDoesNotExist(payload={"details": sponsor_id})
        if receipt is not None:
            self.receipt = receipt
        if date is not None and time is None:
            self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M')
        if date is not None and time is not None:
            if date is not None and not date_validator(date):
                raise InvalidField(payload={'details': "Game - date"})
            if time is not None and not time_validator(time):
                raise InvalidField(payload={'details': "Game - time"})
            self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M')
Esempio n. 10
0
 def import_headers(self):
     """Parse the headers of the csv and add team"""
     done = False
     i = 0
     sponsor = None
     color = None
     captain = None
     league = None
     while not done:
         # read the headers
         line = self.lines[i]
         columns = line.split(",")
         if self.clean_cell(columns[0]) == "sponsor":
             sponsor = columns[1].strip()
         elif self.clean_cell(columns[0]) == "color":
             color = columns[1].strip()
         elif self.clean_cell(columns[0]) == "captain":
             captain = columns[1].strip()
         elif self.clean_cell(columns[0]) == "league":
             league = columns[1].strip()
         else:
             # assuming done reading the headers
             done = True
         i += 1
     player_index = i
     if sponsor is None:
         raise InvalidField(payload={"details": "No sponsor was given"})
     if captain is None:
         raise InvalidField(payload={"details": "No captain was given"})
     if color is None:
         raise InvalidField(payload={"details": "No color was given"})
     if league is None:
         raise InvalidField(payload={"details": "No league was given"})
     # check no examples were left and actually real info
     if (league.lower().startswith("ex.")
             or sponsor.lower().startswith("ex.")
             or color.lower().startswith("ex.")
             or captain.lower().startswith("ex.")):
         t = "The header's still had an example"
         raise InvalidField(payload={"details": t})
     sponsor_id = (DB.session.query(Sponsor).filter(
         Sponsor.name == sponsor).first())
     if sponsor_id is None:
         sponsor_id = (DB.session.query(Sponsor).filter(
             Sponsor.nickname == sponsor).first())
     if sponsor_id is None:
         # what kind of sponsor are you giving
         t = "The sponsor does not exist (check case)"
         raise SponsorDoesNotExist(payload={'details': t})
     sponsor_id = sponsor_id.id
     league_id = (DB.session.query(League).filter(
         League.name == league)).first()
     if league_id is None:
         t = "The league does not exist (check case)"
         raise LeagueDoesNotExist(payload={"details": t})
     league_id = league_id.id
     # check to see if team was already created
     teams = (DB.session.query(Team).filter(Team.color == color).filter(
         Team.sponsor_id == sponsor_id).filter(
             Team.year == date.today().year).all())
     team_found = None
     if len(teams) > 0:
         team_found = teams[0]
     # was the team not found then should create it
     if team_found is None:
         self.warnings.append("Team was created")
         team_found = Team(color=color,
                           sponsor_id=sponsor_id,
                           league_id=league_id)
     else:
         team_found.players = []  # remove all the players before
     self.team = team_found  # set the team
     self.captain_name = captain  # remember captains name
     return player_index
Esempio n. 11
0
def extract_background(background):
    """Returns a dictionary of the extracted json objects from the background.
    Parameters:
        background: dictionary of sponsor, color, captain, league
    Returns:
        a dictionary of sponsor model, team model, player model, league model
    """
    for value in BACKGROUND.values():
        if value not in background.keys():
            errorMessage = MISSING_BACKGROUND.format(value)
            raise InvalidField(payload={"details": errorMessage})
    league_name = background['league']
    sponsor_name = background['sponsor']
    team_color = background['color']
    captain_name = background['captain']
    if league_name.lower().startswith("ex."):
        error_message = LEFT_BACKGROUND_EXAMPLE.format(league_name)
        raise InvalidField(payload={"details": error_message})
    elif sponsor_name.lower().startswith("ex."):
        error_message = LEFT_BACKGROUND_EXAMPLE.format(sponsor_name)
        raise InvalidField(payload={"details": error_message})
    elif team_color.lower().startswith("ex."):
        error_message = LEFT_BACKGROUND_EXAMPLE.format(team_color)
        raise InvalidField(payload={"details": error_message})
    elif captain_name.lower().startswith("ex."):
        error_message = LEFT_BACKGROUND_EXAMPLE.format(captain_name)
        raise InvalidField(payload={"details": error_message})

    # nothing to do with the captain at this point
    captain = {"player_name": captain_name}

    # try to find sponsor and league
    sponsor = (Sponsor.query.filter(
        or_(func.lower(Sponsor.name) == func.lower(sponsor_name)),
        func.lower(Sponsor.nickname) == func.lower(sponsor_name))).first()
    league = League.query.filter(
        func.lower(League.name) == func.lower(league_name)).first()
    if sponsor is None:
        error_message = INVALID_SPONSOR.format(sponsor_name)
        raise SponsorDoesNotExist(payload={'details': error_message})
    if league is None:
        error_message = INVALID_LEAGUE.format(league_name)
        raise LeagueDoesNotExist(payload={'details': error_message})

    # check to see if team was already created
    teams = (Team.query.filter(
        func.lower(Team.color) == func.lower(team_color)).filter(
            Team.sponsor_id == sponsor.id).filter(
                Team.year == date.today().year)).all()
    if len(teams) > 0:
        team = teams[0].json()
    else:
        team = {
            'team_id': None,
            "color": team_color,
            "sponsor_id": sponsor.id,
            "league_id": league.id,
            "captain": None,
            "year": date.today().year
        }
    return {
        "captain": captain,
        "team": team,
        "league": league.json(),
        "sponsor": sponsor.json()
    }