Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .flaskenv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FLASK_APP=server
FLASK_ENV=development
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ bin
include
lib
.Python
tests/
.envrc
__pycache__
__pycache__
.venv
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
click==7.1.2
colorama==0.4.6
Flask==1.1.2
iniconfig==2.3.0
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
packaging==25.0
pluggy==1.6.0
Pygments==2.19.2
pytest==8.4.2
python-dotenv==1.1.1
Werkzeug==1.0.1
133 changes: 106 additions & 27 deletions server.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import json
from flask import Flask,render_template,request,redirect,flash,url_for

from datetime import datetime
from flask import session
import logging


def load_json_data(filename: str, key: str):
try:
with open(filename) as f:
data = json.load(f)
if key not in data:
logging.warning(f"Key '{key}' not found in {filename}")
return []
return data[key]
except (FileNotFoundError, json.JSONDecodeError) as e:
logging.warning(f"Unable to load {filename}: {e}")
return []

def loadClubs():
with open('clubs.json') as c:
listOfClubs = json.load(c)['clubs']
return listOfClubs

return load_json_data("clubs.json", "clubs")

def loadCompetitions():
with open('competitions.json') as comps:
listOfCompetitions = json.load(comps)['competitions']
return listOfCompetitions
return load_json_data("competitions.json", "competitions")


app = Flask(__name__)
Expand All @@ -22,32 +32,100 @@ def loadCompetitions():

@app.route('/')
def index():
return render_template('index.html')
return render_template('index.html', clubs=clubs)

@app.route('/showSummary',methods=['POST'])
def showSummary():
club = [club for club in clubs if club['email'] == request.form['email']][0]
return render_template('welcome.html',club=club,competitions=competitions)


@app.route('/book/<competition>/<club>')
def book(competition,club):
foundClub = [c for c in clubs if c['name'] == club][0]
foundCompetition = [c for c in competitions if c['name'] == competition][0]
if foundClub and foundCompetition:
return render_template('booking.html',club=foundClub,competition=foundCompetition)
else:
flash("Something went wrong-please try again")
return render_template('welcome.html', club=club, competitions=competitions)
email = request.form.get('email', '').strip()
club = next((c for c in clubs if c.get('email', '').strip() == email), None)
if not email or not club:
flash("Sorry, that email was not found, please try again.")
return render_template('index.html', clubs=clubs)
session['club_name'] = club['name']
return render_template('welcome.html', club=club, competitions=competitions)

#retrait du paramètre club dans l'URL pour éviter la triche
#club est maintenant récupéré depuis la session
@app.route('/book/<competition>')
def book(competition):
club_name = session.get('club_name')
if not club_name:
flash("You must be logged in to access bookings.")
return render_template('index.html', clubs=clubs)

#harmonisation de la recherche du club et de la compétition, gestion des erreurs
foundClub = next((c for c in clubs if c['name'] == club_name), None)
foundCompetition = next((c for c in competitions if c['name'] == competition), None)

#clarification du message d'erreur
if not foundClub:
flash("Club not found.")
return render_template('welcome.html', club=foundClub, competitions=competitions)
if not foundCompetition:
flash("Competition not found.")
return render_template('welcome.html', club=foundClub, competitions=competitions)

competition_date = datetime.strptime(foundCompetition['date'], "%Y-%m-%d %H:%M:%S")
if competition_date < datetime.now():
flash("This competition has already taken place, booking is not allowed.")
return render_template('welcome.html', club=foundClub, competitions=competitions)
return render_template('booking.html', club=foundClub, competition=foundCompetition)


@app.route('/purchasePlaces',methods=['POST'])
def purchasePlaces():
competition = [c for c in competitions if c['name'] == request.form['competition']][0]
club = [c for c in clubs if c['name'] == request.form['club']][0]
placesRequired = int(request.form['places'])
competition['numberOfPlaces'] = int(competition['numberOfPlaces'])-placesRequired
flash('Great-booking complete!')
MAX_BOOKING = 12

#premier bloc de verif sur le club depuis la session
club_name = session.get('club_name')
if not club_name:
flash("You must be logged in to book places.")
return render_template('index.html', clubs=clubs)

club = next((c for c in clubs if c['name'] == club_name), None)
if not club:
flash("Club not found in session.")
return render_template('index.html', clubs=clubs)

#second bloc de verif sur la compétition depuis le formulaire
competition_name = request.form.get('competition')
foundCompetition = next((c for c in competitions if c['name'] == competition_name), None)
#harmonisation de la recherche du club et de la compétition, gestion des erreurs
if not foundCompetition:
flash("Competition not found.")
return render_template('welcome.html', club=club, competitions=competitions)


places = request.form.get('places')
try:
placesRequired = int(places)
except (TypeError, ValueError):
flash("Invalid number of places.")
return render_template('welcome.html', club=club, competitions=competitions)

if placesRequired <= 0:
flash("Invalid number of places.")
return render_template('welcome.html', club=club, competitions=competitions)

club_points = int(club['points'])
if placesRequired > club_points:
flash("Cannot book more places than club points.")
return render_template('welcome.html', club=club, competitions=competitions)

if placesRequired > int(foundCompetition['numberOfPlaces']):
flash("Cannot book more places than available.")
return render_template('welcome.html', club=club, competitions=competitions)

already_booked = int(foundCompetition.get('booked_by', {}).get(club['name'], 0))
if placesRequired > MAX_BOOKING or already_booked + placesRequired > MAX_BOOKING:
flash(f"Cannot book more than {MAX_BOOKING} places per club for this competition.")
return render_template('welcome.html', club=club, competitions=competitions)

foundCompetition.setdefault('booked_by', {})[club['name']] = already_booked + placesRequired
foundCompetition['numberOfPlaces'] = int(foundCompetition['numberOfPlaces']) - placesRequired
club['points'] = club_points - placesRequired

flash('Great - booking complete!')
return render_template('welcome.html', club=club, competitions=competitions)


Expand All @@ -56,4 +134,5 @@ def purchasePlaces():

@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
1 change: 0 additions & 1 deletion templates/booking.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
<h2>{{competition['name']}}</h2>
Places available: {{competition['numberOfPlaces']}}
<form action="/purchasePlaces" method="post">
<input type="hidden" name="club" value="{{club['name']}}">
<input type="hidden" name="competition" value="{{competition['name']}}">
<label for="places">How many places?</label><input type="number" name="places" id=""/>
<button type="submit">Book</button>
Expand Down
26 changes: 26 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,36 @@
<body>
<h1>Welcome to the GUDLFT Registration Portal!</h1>
Please enter your secretary email to continue:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes" style="color: red;">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form action="showSummary" method="post">
<label for="email">Email:</label>
<input type="email" name="email" id=""/>
<button type="submit">Enter</button>
</form>
<h2>Clubs Points Summary</h2>
<table style="border-collapse: collapse; width: 30%; background-color: #f5f5f5; color: #333;">
<thead>
<tr style="background-color: #e0e0e0;">
<th style="border: 1px solid #ccc; padding: 6px;">Club</th>
<th style="border: 1px solid #ccc; padding: 6px;">Points</th>
</tr>
</thead>
<tbody>
{% for club in clubs %}
<tr style="text-align: center;">
<td style="border: 1px solid #ccc; padding: 6px;">{{ club['name'] }}</td>
<td style="border: 1px solid #ccc; padding: 6px;">{{ club['points'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
20 changes: 20 additions & 0 deletions tests/functional/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import os
import sys
import pytest


"""Pytest configuration file for functional tests.
This file adds the project root directory to sys.path to ensure that
"""

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)

from server import app

@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
54 changes: 54 additions & 0 deletions tests/functional/test_user_booking_workflow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import server

"""
Functional test to check the user workflow from login to logout

1. User logs in
2. User accesses booking page
3. User books places
4. User verifies their points decreased and competition places decreased
5. User logs out
"""


def test_full_booking_workflow(client):
server.clubs = [{"name": "Simply Lift", "email": "john@simplylift.co", "points": "20"}]
server.competitions = [{"name": "Fall Classic", "date": "2026-10-22 13:30:00", "numberOfPlaces": "10"}]

# Step 1: User logs in
response = client.post('/showSummary', data={'email': 'john@simplylift.co'})
assert response.status_code == 200
assert b"Welcome" in response.data

with client.session_transaction() as session:
assert session['club_name'] == "Simply Lift"

# Step 2: User accesses booking page
response = client.get('/book/Fall Classic')
assert response.status_code == 200
assert b"How many places?" in response.data
assert b"Fall Classic" in response.data

# Step 3: User books places
response = client.post('/purchasePlaces', data={
'competition': 'Fall Classic',
'places': '5'
})
assert response.status_code == 200
assert b"Great - booking complete!" in response.data

# Step 4: Verify data was updated : user's points should decrease from 20 to 15
# Competition places should decrease from 10 to 5
# Booking tracking should be recorded
assert int(server.clubs[0]['points']) == 15
assert int(server.competitions[0]['numberOfPlaces']) == 5
assert server.competitions[0]['booked_by']['Simply Lift'] == 5

# Step 5: User logs out
response = client.get('/logout', follow_redirects=True)
assert response.status_code == 200
assert b"Welcome to the GUDLFT Registration Portal!" in response.data

with client.session_transaction() as session:
assert session.get('club_name') is None

22 changes: 22 additions & 0 deletions tests/unit/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import os
import sys
import pytest


"""Pytest configuration file to set up the testing environment.
This file adds the project root directory to sys.path to ensure that
"""

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)

from server import app

@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
with client.session_transaction() as session:
session['club_name'] = "Club A"
yield client
23 changes: 23 additions & 0 deletions tests/unit/test_board_with_clubs_and_their_points.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import server

"""
Unit test file to check if the index page displays the clubs and their points correctly
Test 1: The page loads successfully (status code 200)
Test 2: Each club name and its points appear in the HTML
"""

def test_index_page_loads(client):
response = client.get('/')
assert response.status_code == 200
assert b"Clubs Points Summary" in response.data


def test_index_page_displays_clubs_points(client):
server.clubs = [
{"name": "Simply Lift", "email": "john@simplylift.co", "points": "13"}
]
response = client.get('/')
data = response.data.decode()

assert "Simply Lift" in data
assert "13" in data
Loading