ajout d'un toggle pour permission d'upload des documents dans admin pannel
CI - Security, Lint & Tests / validate (push) Failing after 1m3s

ajout de compteur d'heure disponible
ajout du calendrier de dispo dans les profils publics
This commit is contained in:
cedrick2711
2026-08-26 22:33:24 -04:00
parent 820cccb25e
commit bfb25f4d16
16 changed files with 1966 additions and 74 deletions
+6 -5
View File
@@ -18,11 +18,12 @@ class AppSettings(db.Model):
# ------------------------------------------------------------------
# Well-known keys (documented here for discoverability)
# ------------------------------------------------------------------
# tryouts_open – "true" / "false" (default: "true")
# season_active – "true" / "false" (default: "false")
# season_name – e.g. "Fall 2026"
# season_start – ISO date string
# season_end – ISO date string
# tryouts_open – "true" / "false" (default: "true")
# document_uploads_enabled – "true" / "false" (default: "true")
# season_active – "true" / "false" (default: "false")
# season_name – e.g. "Fall 2026"
# season_start – ISO date string
# season_end – ISO date string
@staticmethod
def get(key, default=None):
+19
View File
@@ -73,6 +73,7 @@ def dashboard():
settings = {
'tryouts_open': AppSettings.get_bool('tryouts_open', default=True),
'document_uploads_enabled': AppSettings.get_bool('document_uploads_enabled', default=True),
'season_active': AppSettings.get_bool('season_active', default=False),
'season_name': AppSettings.get('season_name') or 'Not set',
'season_start': AppSettings.get('season_start') or 'Not set',
@@ -326,6 +327,24 @@ def end_season():
_log('season_ended', f'Season: {name}, End: {end_date}')
flash(f'Season "{name}" has ended.', 'success')
return redirect(url_for('admin.dashboard'))
@admin_bp.route('/toggle-document-uploads', methods=['POST'])
@login_required
def toggle_document_uploads():
"""Enable or disable document uploads for non-admin users."""
if not require_admin():
return redirect(url_for('main.dashboard'))
current = AppSettings.get_bool('document_uploads_enabled', default=True)
new_value = not current
AppSettings.set_bool('document_uploads_enabled', new_value)
state = 'enabled' if new_value else 'disabled'
_log('document_uploads_toggled', f'Document uploads {state}')
flash(f'Document uploads are now {state}.', 'success')
return redirect(url_for('admin.dashboard'))
# ---------------------------------------------------------------------------
+50 -2
View File
@@ -44,6 +44,7 @@ from app.routes.users._shared import (
)
from app.routes.users.blueprint import users_bp
from app.storage import discard_documents
from app.timeslots import total_hours
from app.validators import CreateUserSchema, EditUserSchema
@@ -59,7 +60,39 @@ def list_users():
# query without a stable ORDER BY can show the same row twice and never
# show another (MNT-14).
page = paginate(User.query.order_by(User.role, User.username, User.id))
return render_template('pages/users.html', users=page.items, pagination=page, roles=USER_TYPES)
# Build a per-user hours map for the current page with two bounded
# queries (one per availability table), avoiding an N+1 per row.
user_ids = [u.id for u in page.items]
hours_by_user: dict[int, float] = {}
for slots, fk in [
(
PlayerDisponibility.query.filter(
PlayerDisponibility.player_id.in_(user_ids),
).all(),
'player_id',
),
(
CoachAvailability.query.filter(
CoachAvailability.coach_id.in_(user_ids),
).all(),
'coach_id',
),
]:
buckets: dict[int, list] = {}
for slot in slots:
buckets.setdefault(getattr(slot, fk), []).append(slot)
for uid, group in buckets.items():
hours_by_user[uid] = total_hours(group)
return render_template(
'pages/users.html',
users=page.items,
pagination=page,
roles=USER_TYPES,
hours=hours_by_user,
)
@users_bp.route('/<int:user_id>/edit', methods=['GET', 'POST'])
@@ -380,4 +413,19 @@ def create_user():
def view_user(user_id):
"""View a public profile for any user."""
user = db.get_or_404(User, user_id)
return render_template('pages/view_user.html', profile_user=user)
# Load availability for players and coaches so the public profile
# can render a read-only weekly grid.
availability = None
if user.role == 'player':
availability = user.disponibilities
elif user.role == 'coach':
availability = user.coach_availabilities
availability_hours = total_hours(availability) if availability else None
return render_template(
'pages/view_user.html',
profile_user=user,
availability=availability,
availability_hours=availability_hours,
)
+20
View File
@@ -11,6 +11,7 @@ from werkzeug.utils import secure_filename
from app.extensions import db
from app.models import Admin, Coach, Contract, Manager, Player, User
from app.models.admin_settings import AppSettings
from app.permissions import can_manage_player_contract, coach_player_ids
from app.routes.users._shared import (
ALLOWED_CONTRACT_EXTENSIONS,
@@ -49,6 +50,17 @@ def manageable_players():
return User.query.filter_by(role='player', is_active_account=True).order_by(User.username).all()
def document_uploads_locked():
"""Return True when document uploads are globally disabled.
Admins are always allowed to bypass the lock. Managers, coaches, and
players are blocked when the toggle is off.
"""
if isinstance(current_user, Admin):
return False
return not AppSettings.get_bool('document_uploads_enabled', default=True)
@users_bp.route('/contracts')
@login_required
def list_contracts():
@@ -92,6 +104,10 @@ def upload_contract():
flash(_('Only presidents, managers, and coaches can upload contracts.'), 'danger')
return redirect(url_for('users.list_contracts'))
if document_uploads_locked():
flash(_('Document uploads are currently disabled.'), 'danger')
return redirect(url_for('users.list_contracts'))
players = manageable_players()
if request.method == 'POST':
@@ -169,6 +185,10 @@ def upload_signed_contract(contract_id):
flash(_('Only the player can upload their signed contract.'), 'danger')
return redirect(url_for('users.list_contracts'))
if document_uploads_locked():
flash(_('Document uploads are currently disabled.'), 'danger')
return redirect(url_for('users.list_contracts'))
file = request.files.get('signed_file')
error = pdf_upload_error(file, ALLOWED_SIGNED_EXTENSIONS)
if error:
+58
View File
@@ -1256,6 +1256,64 @@ a:hover { color: var(--primary-dark); }
color: white !important;
border-color: #4f46e5 !important;
}
/* Read-only weekly availability grid (public profile) */
.readonly-availability-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 8px;
margin-top: 8px;
}
.ra-day-column {
background: var(--bg-secondary);
border-radius: 8px;
padding: 8px;
min-height: 120px;
}
.ra-day-header {
text-align: center;
font-weight: 600;
padding: 6px 0;
border-bottom: 1px solid var(--border-color);
margin-bottom: 6px;
color: var(--primary);
font-size: 0.85rem;
}
.ra-slot {
padding: 4px 6px;
margin: 3px 0;
border-radius: 4px;
font-size: 0.75rem;
text-align: center;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
}
.ra-slot.selected {
background: var(--primary);
color: white;
border-color: var(--primary-dark);
}
.ra-slot.ra-empty {
color: var(--gray-400);
border: 1px dashed var(--gray-300);
background: transparent;
}
@media (max-width: 768px) {
.readonly-availability-grid {
grid-template-columns: repeat(3, 1fr);
}
}
@media (max-width: 480px) {
.readonly-availability-grid {
grid-template-columns: 1fr;
}
}
.merged-disponibility-time-block.high-availability {
background: var(--success);
+27
View File
@@ -82,6 +82,33 @@
</div>
</div>
<div class="card">
<div class="card-header">
<h3><i class="fas fa-toggle-{% if settings.document_uploads_enabled %}on{% else %}off{% endif %}"></i> Document Uploads</h3>
</div>
<div class="card-body">
<p>
Status:
<span class="badge badge-{% if settings.document_uploads_enabled %}success{% else %}danger{% endif %}">
{% if settings.document_uploads_enabled %}ENABLED{% else %}DISABLED{% endif %}
</span>
</p>
<p class="text-muted" style="font-size: 0.85rem; margin: 8px 0;">
{% if settings.document_uploads_enabled %}
Managers and coaches can upload contracts. Players can upload signed contracts.
{% else %}
Only admins can upload or sign contracts. Other roles are blocked.
{% endif %}
</p>
<form method="POST" action="{{ url_for('admin.toggle_document_uploads') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-{% if settings.document_uploads_enabled %}warning{% else %}success{% endif %}">
{% if settings.document_uploads_enabled %}Disable Uploads{% else %}Enable Uploads{% endif %}
</button>
</form>
</div>
</div>
<div class="card">
<div class="card-header">
<h3><i class="fas fa-calendar-check"></i> Season Management</h3>
+8
View File
@@ -21,6 +21,7 @@
<th>{{ _('Username') }}</th>
<th>{{ _('Email') }}</th>
<th>{{ _('Role') }}</th>
<th>{{ _('Hours') }}</th>
<th>{{ _('Status') }}</th>
<th>{{ _('Joined') }}</th>
<th>{{ _('Actions') }}</th>
@@ -38,6 +39,13 @@
<td>{{ u.username }}</td>
<td>{{ u.email }}</td>
<td><span class="badge badge-{{ u.role }}">{{ u.role | capitalize }}</span></td>
<td>
{% if u.role in ('player', 'coach') %}
{{ '%.1f'|format(hours.get(u.id, 0.0)) }}
{% else %}
—
{% endif %}
</td>
<td>
{% if u.is_active_account %}
<span class="badge badge-success">Active</span>
+25
View File
@@ -81,6 +81,31 @@
</table>
</div>
{% endif %}
{% if profile_user.role in ('player', 'coach') and availability %}
<hr class="my-4">
<h4 class="mb-3"><i class="fas fa-clock"></i> {{ _('Availability') }}
<small class="text-muted">({{ '%.1f'|format(availability_hours or 0.0) }} h)</small>
</h4>
<div class="readonly-availability-grid">
{% set day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] %}
{% for day_idx in range(7) %}
<div class="ra-day-column">
<div class="ra-day-header">{{ day_names[day_idx][:3] }}</div>
{% set day_slots = availability | selectattr('day_of_week', 'equalto', day_idx) | list %}
{% if day_slots %}
{% for slot in day_slots | sort(attribute='start_time') %}
<div class="ra-slot selected">
{{ slot.start_time.strftime('%H:%M') }}–{{ slot.end_time.strftime('%H:%M') }}
</div>
{% endfor %}
{% else %}
<div class="ra-slot ra-empty">—</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
</div>
{% endblock %}
+36
View File
@@ -58,3 +58,39 @@ def day_name(day_of_week):
if 0 <= day_of_week < len(DAY_NAMES):
return DAY_NAMES[day_of_week]
return f'Day {day_of_week}'
def slot_duration_minutes(start_time, end_time):
"""Minutes a slot spans, wrapping past midnight like slot_end does.
Works on SQLite where ``Time`` columns are stored as text — the
arithmetic stays in pure Python so it is portable across databases.
Args:
start_time: A ``datetime.time``.
end_time: A ``datetime.time`` (may be earlier if the slot wraps
past midnight).
Returns:
int: Duration in whole minutes.
"""
anchor = date_cls(2000, 1, 1)
start_dt = datetime.combine(anchor, start_time)
end_dt = datetime.combine(anchor, end_time)
if end_dt <= start_dt:
end_dt += timedelta(days=1)
return int((end_dt - start_dt).total_seconds() // 60)
def total_hours(slots):
"""Aggregate slot durations into a single float, rounded to one decimal.
Args:
slots: Iterable of objects with ``start_time`` and ``end_time``
attributes (``PlayerDisponibility`` or ``CoachAvailability``).
Returns:
float: Total hours across all slots, e.g. ``8.5``.
"""
total_minutes = sum(slot_duration_minutes(s.start_time, s.end_time) for s in slots)
return round(total_minutes / 60, 1)
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
+135
View File
@@ -0,0 +1,135 @@
"""Admin document-upload toggle — enable/disable gate and enforcement
on contract upload routes.
ADMIN-006 style. The document_uploads_enabled setting gates every
contract upload route for non-admins. Admins always bypass the lock.
"""
import pytest
from app.extensions import db
from app.models import AppSettings, Contract, User
NON_ADMIN_ROLES = ['manager', 'coach']
def _redirected(response):
return response.status_code in (301, 302)
class TestDocumentUploadToggle:
"""Toggle logic — on/off round-trip and audit log."""
def test_toggle_from_enabled_to_disabled(self, client, as_role):
as_role('admin')
# Default is enabled
client.post('/admin/toggle-document-uploads', data={}, follow_redirects=False)
with client.application.app_context():
assert not AppSettings.get_bool('document_uploads_enabled', default=True)
def test_toggle_from_disabled_to_enabled(self, client, as_role):
as_role('admin')
client.post('/admin/toggle-document-uploads', data={}, follow_redirects=False)
client.post('/admin/toggle-document-uploads', data={}, follow_redirects=False)
with client.application.app_context():
assert AppSettings.get_bool('document_uploads_enabled', default=True)
def test_toggle_creates_audit_log(self, client, as_role):
from app.models import AuditLog
as_role('admin')
client.post('/admin/toggle-document-uploads', data={}, follow_redirects=False)
with client.application.app_context():
entry = AuditLog.query.filter_by(action='document_uploads_toggled').first()
assert entry is not None
def test_default_is_enabled(self, app):
with app.app_context():
assert AppSettings.get_bool('document_uploads_enabled', default=True)
class TestDocumentUploadGateEnforcement:
"""Non-admin roles are blocked when the toggle is off."""
def _contract_for(self, app, player_id):
"""Create a minimal contract for enforcement tests."""
from datetime import datetime
with app.app_context():
admin = User.query.filter_by(role='admin').first()
contract = Contract(
player_id=player_id,
uploaded_by_id=admin.id,
original_filename='test.pdf',
stored_filename='test.pdf',
file_path='contrats signes/test.pdf',
status='pending_player_signing',
uploaded_at=datetime.utcnow(),
)
db.session.add(contract)
db.session.commit()
return contract.id
@pytest.mark.parametrize('role', NON_ADMIN_ROLES)
def test_non_admin_cannot_upload_contract_when_disabled(
self, app, client, as_role, make_user, role
):
as_role('admin')
client.post('/admin/toggle-document-uploads', data={}) # disable
as_role(role)
response = client.post(
'/users/contracts/upload',
data={'player_id': '', 'contract_file': ''},
follow_redirects=True,
)
html = response.data.decode()
# Default locale is French — the flash message says "désactivés"
assert 'désactivés' in html or 'disabled' in html.lower()
@pytest.mark.parametrize('role', NON_ADMIN_ROLES)
def test_admin_can_always_upload_contract(self, client, as_role, role):
as_role('admin')
# Pre-create a player for the contract
as_role('player')
client.post('/admin/toggle-document-uploads', data={}) # disable
# Admin should still be able to reach the upload page
response = client.get('/users/contracts/upload', follow_redirects=False)
assert _redirected(response) or response.status_code == 200
def test_player_cannot_upload_signed_when_disabled(self, app, client, as_role, make_user):
as_role('admin')
client.post('/admin/toggle-document-uploads', data={}) # disable while logged in as admin
player_id = make_user('player')
contract_id = self._contract_for(app, player_id)
# Log in as the player
with app.app_context():
username = db.session.get(User, player_id).username
client.post('/auth/login', data={'username': username, 'password': 'Password123'})
response = client.post(
f'/users/contracts/{contract_id}/upload_signed',
data={'signed_file': ''},
follow_redirects=True,
)
html = response.data.decode()
assert 'désactivés' in html or 'disabled' in html.lower()
def test_admin_can_always_upload(self, app, client, as_role):
as_role('admin')
client.post('/admin/toggle-document-uploads', data={}) # disable
# Admin GET the upload page — should be allowed (not redirected away)
response = client.get('/users/contracts/upload', follow_redirects=False)
# The admin bypasses the lock so they see the upload form (200)
# or get redirected (if no players exist, etc). Either way is fine
# as long as it's not the flash about uploads being disabled.
body = response.data.decode() if response.status_code == 200 else ''
# The toggle flash ("désactivés") could still be present, but the
# upload-disabled message ("désactivés") must not appear in the body.
# We check for the French lock message specifically.
assert 'actuellement désactivés' not in body
+1
View File
@@ -12,6 +12,7 @@ ADMIN_ROUTES = [
'/admin',
'/admin/backup/create',
'/admin/toggle-tryouts',
'/admin/toggle-document-uploads',
'/admin/season/start',
'/admin/season/end',
'/admin/teams/wipe',
+116
View File
@@ -0,0 +1,116 @@
"""Tests for the hours column in the user list and the read-only
availability grid on public profiles."""
from datetime import time
from app.extensions import db
from app.models import (
CoachAvailability,
PlayerDisponibility,
)
class TestHoursColumn:
"""The manage-users table shows available hours for players/coaches."""
def test_admin_sees_hours_header(self, app, client, as_role):
as_role('admin')
body = client.get('/users').get_data(as_text=True)
# Default locale is French, so _("Hours") renders as "Heures"
assert 'Heures' in body
def test_player_without_slots_shows_0(self, app, client, as_role, make_user):
as_role('admin')
make_user('player') # create a player but stay logged in as admin
body = client.get('/users').get_data(as_text=True)
assert '0.0' in body
def test_player_with_slots_shows_hours(self, app, client, as_role, make_user):
as_role('admin')
player_id = make_user('player')
with app.app_context():
db.session.add(
PlayerDisponibility(
player_id=player_id,
day_of_week=0,
start_time=time(17, 0),
end_time=time(19, 0),
)
)
db.session.add(
PlayerDisponibility(
player_id=player_id,
day_of_week=1,
start_time=time(18, 0),
end_time=time(20, 0),
)
)
db.session.commit()
body = client.get('/users').get_data(as_text=True)
# 2h + 2h = 4.0
assert '4.0' in body
def test_coach_without_slots_shows_0(self, app, client, as_role, make_user):
as_role('admin')
make_user('coach')
body = client.get('/users').get_data(as_text=True)
assert '0.0' in body
def test_admin_roles_show_dash(self, app, client, as_role, make_user):
as_role('admin')
make_user('manager')
make_user('scout')
body = client.get('/users').get_data(as_text=True)
# managers and scouts should show mdash
assert '\u2014' in body
class TestAvailabilityOnPublicProfile:
"""view_user renders a weekly availability grid for players/coaches."""
def test_player_without_availability_shows_no_grid(self, app, client, as_role):
as_role('admin')
player_id = as_role('player')
body = client.get(f'/users/{player_id}/view').get_data(as_text=True)
# Default locale is French
assert 'Disponibilit\u00e9s' not in body
def test_player_with_slots_shows_grid(self, app, client, as_role, make_user):
as_role('admin')
player_id = make_user('player')
with app.app_context():
db.session.add(
PlayerDisponibility(
player_id=player_id,
day_of_week=2,
start_time=time(18, 0),
end_time=time(18, 30),
)
)
db.session.commit()
body = client.get(f'/users/{player_id}/view').get_data(as_text=True)
assert 'Disponibilit\u00e9s' in body
assert '18:00' in body
def test_coach_with_slots_shows_grid(self, app, client, as_role, make_user):
as_role('admin')
coach_id = make_user('coach')
with app.app_context():
db.session.add(
CoachAvailability(
coach_id=coach_id,
day_of_week=3,
start_time=time(10, 0),
end_time=time(10, 30),
)
)
db.session.commit()
body = client.get(f'/users/{coach_id}/view').get_data(as_text=True)
assert 'Disponibilit\u00e9s' in body
assert '10:00' in body
def test_admin_profile_shows_no_grid(self, app, client, as_role):
admin_id = as_role('admin')
body = client.get(f'/users/{admin_id}/view').get_data(as_text=True)
assert 'Disponibilit\u00e9s' not in body