예제 #1
0
def update_waiver_order():
    try:
        priorities = [
            int(prio) for prio in request.form.get('priorities', '').split(',')
        ]
    except ValueError:
        priorities = []

    wgw = waiver_gameweek()

    if datetime.now() >= wgw['waiver']:
        flash(
            "The deadline for waivers this week has passed. You can no longer edit your claims."
        )

    else:
        current_claims = sorted(db.get(
            'claims', dict(user=current_user.get_id(), week=wgw['week'])),
                                key=lambda claim: claim['priority'])
        deleted_claims = []

        for (n, claim) in enumerate(current_claims):
            try:
                claim['priority'] = priorities.index(n + 1)
            except ValueError:
                deleted_claims.append(claim)

        db.save_all(
            [claim for claim in current_claims if claim not in deleted_claims])
        for claim in deleted_claims:
            db.delete(claim)

    return redirect(url_for('waiver_claims'))
예제 #2
0
def add_player():
    add_id = request.form.get('add', 0)
    drop_id = request.form.get('drop', 0)

    if (add_id > 0 and drop_id > 0):
        add = db.get_by_id(add_id)
        drop = db.get_by_id(drop_id)

        cgw = current_gameweek()
        wgw = waiver_gameweek()

        waiver = waiver_status(add, cgw['week'], cgw['deadline'],
                               cgw['waiver'],
                               next_gameweek()['waiver'])

        if waiver['addable']:

            if waiver['type'] == 'free':
                add['team'] = current_user.get_name()
                drop['team'] = ''
                drop['startingxi'] = 0

                db.save_all((add, drop))
                add_waiver_claim(current_user.get_id(),
                                 current_user.get_name(), cgw['week'], add,
                                 drop, 'success')

            elif waiver['type'] == 'waiver':
                add_waiver_claim(current_user.get_id(),
                                 current_user.get_name(), wgw['week'], add,
                                 drop)

    return redirect(request.args.get('next', url_for('lineup')))
예제 #3
0
def add_player():
	add_id = request.form.get('add', 0)
	drop_id = request.form.get('drop', 0)

	if (add_id > 0 and drop_id > 0):
		add = db.get_by_id(add_id)
		drop = db.get_by_id(drop_id)

		cgw = current_gameweek()
		wgw = waiver_gameweek()

		waiver = waiver_status(add, cgw['week'], cgw['deadline'], cgw['waiver'], next_gameweek()['waiver'])

		if waiver['addable']:

			if waiver['type'] == 'free':
				add['team'] = current_user.get_name()
				drop['team'] = ''
				drop['startingxi'] = 0

				db.save_all((add, drop))
				add_waiver_claim(current_user.get_id(), current_user.get_name(), cgw['week'], add, drop, 'success')

			elif waiver['type'] == 'waiver':
				add_waiver_claim(current_user.get_id(), current_user.get_name(), wgw['week'], add, drop)

	return redirect(request.args.get('next', url_for('lineup')))
예제 #4
0
def lineup_submit():
    if not current_user:
        abort(401)
    else:
        deadline = current_gameweek()['deadline']

        if deadline < datetime.now():
            flash(
                "This week's lineup deadline has passed. Your lineup changes have not been saved."
            )
        else:
            players = get_lineup(current_user.get_name())
            for player in players:
                if request.form.get('startercheck%s' % player['_id'],
                                    '') == 'on':
                    player['startingxi'] = '1'
                else:
                    player['startingxi'] = '0'

            if valid_formation(player for player in players
                               if player['startingxi'] == '1'):
                db.save_all(players, 'players')
                flash('Lineup saved')
            else:
                flash(
                    'Lineup reverted as was not a valid formation (please use 1 G, 3-5 D, 3-5 M, 1-3 F)'
                )

        return redirect(url_for('lineup'))
예제 #5
0
def update_waiver_order():
	try:
		priorities = [int(prio) for prio in request.form.get('priorities', '').split(',')]
	except ValueError:
		priorities = []

	wgw = waiver_gameweek()

	if datetime.now() >= wgw['waiver']:
		flash("The deadline for waivers this week has passed. You can no longer edit your claims.")

	else:
		current_claims = sorted(db.get('claims', dict(user=current_user.get_id(), week=wgw['week'])),
								key=lambda claim: claim['priority'])
		deleted_claims = []

		for (n, claim) in enumerate(current_claims):
			try:
				claim['priority'] = priorities.index(n + 1)
			except ValueError:
				deleted_claims.append(claim)

		db.save_all([claim for claim in current_claims if claim not in deleted_claims])
		for claim in deleted_claims:
			db.delete(claim)

	return redirect(url_for('waiver_claims'))
예제 #6
0
def trade(team1, team2):
	team1, team2 = db.get_by_id(team1), db.get_by_id(team2)

	if (not team1) or (not team2):
		abort(404)

	if request.method == 'POST':
		cgw = current_gameweek()
		players = dict([(unicode(player['_id']), player) for player in db.get('players')])

		firstplayer = [players.get(player) for player in request.form.getlist('firstplayer')]
		secondplayer = [players.get(player) for player in request.form.getlist('secondplayer')]

		for player in firstplayer:
			player['team'] = team2['name']
		for player in secondplayer:
			player['team'] = team1['name']

		trade = dict(
			week=cgw['week'],
			firstplayer=firstplayer,
			secondplayer=secondplayer,
			first=team1,
			second=team2)

		db.save_all(firstplayer + secondplayer)
		db.save(trade, 'trades')

		return redirect(url_for('scoring'))
	else:
		return render_template('trade.html', activepage="scoring", team1=team1, team2=team2)
예제 #7
0
def update_next_fixtures():
	clubs = dict([(c['_id'], c) for c in db.get('clubs')])
	fixtures = current_gameweek()['fixtures']

	for fixture in fixtures:
		clubs[fixture['home']['_id']]['nextopponent'] = '%s (H)' % fixture['away']['name']
		clubs[fixture['away']['_id']]['nextopponent'] = '%s (A)' % fixture['home']['name']

	db.save_all(clubs.values())
예제 #8
0
def complete_gameweeks():
    changedweeks = []
    for gw in db.get('gameweeks'):
        conclusion = datetime.strptime(gw['conclusion'], '%Y-%m-%dT%H:%M:%S')
        if (not gw.get('completed', False)) and conclusion < datetime.now():
            gw['completed'] = True
            changedweeks.append(gw)
    if changedweeks:
        db.save_all(changedweeks)
        update_next_fixtures()
예제 #9
0
def trade(team1, team2):
    team1, team2 = db.get_by_id(team1), db.get_by_id(team2)

    if (not team1) or (not team2):
        abort(404)

    if request.method == 'POST':
        cgw = current_gameweek()
        players = dict([(unicode(player['_id']), player)
                        for player in db.get('players')])

        firstplayer = [
            players.get(player)
            for player in request.form.getlist('firstplayer')
        ]
        secondplayer = [
            players.get(player)
            for player in request.form.getlist('secondplayer')
        ]

        for player in firstplayer:
            player['team'] = team2['name']
        for player in secondplayer:
            player['team'] = team1['name']

        trade = dict(week=cgw['week'],
                     firstplayer=firstplayer,
                     secondplayer=secondplayer,
                     first=team1,
                     second=team2)

        db.save_all(firstplayer + secondplayer)
        db.save(trade, 'trades')

        return redirect(url_for('scoring'))
    else:
        return render_template('trade.html',
                               activepage="scoring",
                               team1=team1,
                               team2=team2)
예제 #10
0
def update_player_scores():
	players = dict([(p['_id'], p) for p in db.get('players')])

	gameweeks = db.get('gameweeks', dict(scored=True))
	recent = sorted(gw['week'] for gw in gameweeks)[-4:]

	for player in players.values():
		player.pop('totalscore', None)
		player['form'] = [0] * len(recent)

	for gw in gameweeks:
		for result in gw.get('fixtures', []):
			for player in (result.get('homelineup', []) + result.get('awaylineup', [])):
				dbplayer = players.get(player.get('_id', ''))
				if dbplayer:
					dbplayer.update(totalscore=(dbplayer.get('totalscore', 0) + player.get('score', 0)))
					try:
						dbplayer['form'][recent.index(gw['week'])] = player.get('score', 0)
					except ValueError:
						pass

	db.save_all(players.values())
예제 #11
0
def lineup_submit():
	if not current_user:
		abort(401)
	else:
		deadline = current_gameweek()['deadline']

		if deadline < datetime.now():
			flash("This week's lineup deadline has passed. Your lineup changes have not been saved.")
		else:
			players = get_lineup(current_user.get_name())
			for player in players:
				if request.form.get('startercheck%s' % player['_id'], '') == 'on':
					player['startingxi'] = '1'
				else:
					player['startingxi'] = '0'

			if valid_formation(player for player in players if player['startingxi'] == '1'):
				db.save_all(players, 'players')
				flash('Lineup saved')
			else:
				flash('Lineup reverted as was not a valid formation (please use 1 G, 3-5 D, 3-5 M, 1-3 F)')

		return redirect(url_for('lineup'))
예제 #12
0
def update_league_table():
	teams = db.get('users')

	results = []
	for gw in db.get('gameweeks', dict(scored=True)):
		for result in gw.get('schedule', []):
			homeresult = dict(team=result.get('home', ''), score=int(result.get('homescore', 0)))
			awayresult = dict(team=result.get('away', ''), score=int(result.get('awayscore', 0)))

			homeresult['win'] = awayresult['loss'] = 1 * (homeresult.get('score', 0) > awayresult.get('score', 0))
			awayresult['win'] = homeresult['loss'] = 1 * (awayresult.get('score', 0) > homeresult.get('score', 0))
			homeresult['draw'] = awayresult['draw'] = 1 * (homeresult.get('score', 0) == awayresult.get('score', 0))

			results.append(homeresult)
			results.append(awayresult)

	for team in teams:
		team['wins'] = sum([result.get('win', 0) for result in results if result.get('team', '') == team.get('name', '')])
		team['losses'] = sum([result.get('loss', 0) for result in results if result.get('team', '') == team.get('name', '')])
		team['draws'] = sum([result.get('draw', 0) for result in results if result.get('team', '') == team.get('name', '')])
		team['points'] = (team['wins'] * 2) + team['draws']
		team['score'] = sum([result.get('score', 0) for result in results if result.get('team', '') == team.get('name', '')])

	db.save_all(teams)
예제 #13
0
def process_waivers_now(cgw=None):
	if not cgw:
		cgw = current_gameweek()

	teams = get_teams(reverse=True)
	players = db.get('players')
	claims = db.get('claims', dict(week=cgw['week']))

	# mark all players currently on teams
	for player in players:
		if player['team'] != '':
			player['onteam'] = cgw['week']

	# convert player list to dictionary so we can look up by id
	players = dict([(player['_id'], player) for player in players])

	def next_claim(team):
		try:
			return sorted([claim for claim in claims if claim['user'] == team['userid'] and claim['status'] == ''],
						  key=lambda claim: claim['priority'])[0]

		except IndexError:
			return False

	# process waiver claims
	done = 0
	seq = 0
	while not done:
		done = 1 # until we find out otherwise!

		for team in teams:
			while True:
				claim = next_claim(team)
				if claim:
					done = 0

					# update status of target player from master player list:
					claim['add'] = players[claim['add']['_id']]
					claim['drop'] = players[claim['drop']['_id']]

					# update sequence of claim for correct ordering in after-event views
					claim['order'] = seq
					seq += 1

					# process claim
					if claim['add']['team'] != '':
						claim['status'] = 'failure'
						claim['whynot'] = 'player added by %s' % claim['add']['team']
					elif claim['drop']['team'] != team['name']:
						claim['status'] = 'failure'
						claim['whynot'] = 'no longer have player to drop'
					else:
						claim['status'] = 'success'
						claim['add']['team'] = team['name']
						claim['add']['onteam'] = cgw['week']
						claim['drop']['team'] = ''
						claim['drop']['startingxi'] = 0

						# success, exit loop
						break

				else:
					# no more claims for this user, exit loop
					break

	# save changes
	cgw = db.get_by_id(cgw['_id'])
	cgw['waivers_done'] = True

	db.save_all(players.values() + teams + claims + [cgw])