Compare commits
2 Commits
b1b7d12a9f
...
bb15933e69
| Author | SHA1 | Date | |
|---|---|---|---|
| bb15933e69 | |||
| a0ab7224e1 |
196
backend/api/helpers.py
Normal file
196
backend/api/helpers.py
Normal file
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
Fonctions utilitaires partagées entre les routes API.
|
||||
Élimine la duplication de code pour les patterns courants.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from typing import Optional, Dict, List, Tuple, Any, Callable
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from infrastructure.database.models import (
|
||||
AppConfig,
|
||||
StudentEnrollment,
|
||||
Student,
|
||||
)
|
||||
from schemas.assessment import HeatmapCell, HeatmapData
|
||||
|
||||
|
||||
def eligible_enrollment_filter(class_group_id: int, at_date: date):
|
||||
"""
|
||||
Retourne les clauses WHERE pour filtrer les inscriptions actives à une date donnée.
|
||||
|
||||
Usage:
|
||||
query = select(StudentEnrollment).where(
|
||||
*eligible_enrollment_filter(class_id, assessment.date)
|
||||
)
|
||||
"""
|
||||
return (
|
||||
StudentEnrollment.class_group_id == class_group_id,
|
||||
StudentEnrollment.enrollment_date <= at_date,
|
||||
(
|
||||
StudentEnrollment.departure_date.is_(None)
|
||||
| (StudentEnrollment.departure_date >= at_date)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def count_eligible_students(
|
||||
session: AsyncSession, class_group_id: int, at_date: date
|
||||
) -> int:
|
||||
"""Compte les élèves inscrits dans une classe à une date donnée."""
|
||||
query = select(func.count(StudentEnrollment.id)).where(
|
||||
*eligible_enrollment_filter(class_group_id, at_date)
|
||||
)
|
||||
result = await session.execute(query)
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
def eligible_student_ids_subquery(class_group_id: int, at_date: date):
|
||||
"""Retourne une sous-requête des student_id éligibles à une date donnée."""
|
||||
return select(StudentEnrollment.student_id).where(
|
||||
*eligible_enrollment_filter(class_group_id, at_date)
|
||||
)
|
||||
|
||||
|
||||
async def get_eligible_enrollments(
|
||||
session: AsyncSession, class_group_id: int, at_date: date
|
||||
):
|
||||
"""Récupère les inscriptions éligibles avec les étudiants chargés."""
|
||||
query = (
|
||||
select(StudentEnrollment)
|
||||
.options(selectinload(StudentEnrollment.student))
|
||||
.where(*eligible_enrollment_filter(class_group_id, at_date))
|
||||
)
|
||||
result = await session.execute(query)
|
||||
return result.scalars().all()
|
||||
|
||||
|
||||
def get_active_enrollment(
|
||||
student: Student,
|
||||
) -> Optional[StudentEnrollment]:
|
||||
"""Retourne l'inscription active (sans date de départ) d'un élève."""
|
||||
for enrollment in student.enrollments:
|
||||
if enrollment.departure_date is None:
|
||||
return enrollment
|
||||
return None
|
||||
|
||||
|
||||
async def ensure_unique_name(
|
||||
session: AsyncSession,
|
||||
model_class,
|
||||
name: str,
|
||||
*,
|
||||
field_name: str = "name",
|
||||
exclude_id: Optional[int] = None,
|
||||
entity_label: str = "enregistrement",
|
||||
):
|
||||
"""
|
||||
Vérifie qu'un nom est unique pour un modèle donné.
|
||||
Lève HTTPException 400 si un doublon est trouvé.
|
||||
"""
|
||||
field = getattr(model_class, field_name)
|
||||
query = select(model_class).where(field == name)
|
||||
|
||||
if exclude_id is not None:
|
||||
query = query.where(model_class.id != exclude_id)
|
||||
|
||||
result = await session.execute(query)
|
||||
if result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Un(e) {entity_label} avec le nom '{name}' existe déjà",
|
||||
)
|
||||
|
||||
|
||||
async def upsert_app_configs(
|
||||
session: AsyncSession, updates: Dict[str, str]
|
||||
) -> None:
|
||||
"""
|
||||
Met à jour ou crée des entrées AppConfig en lot.
|
||||
Ne fait PAS de commit — l'appelant doit appeler session.commit().
|
||||
"""
|
||||
for key, value in updates.items():
|
||||
query = select(AppConfig).where(AppConfig.key == key)
|
||||
result = await session.execute(query)
|
||||
config = result.scalar_one_or_none()
|
||||
|
||||
if config:
|
||||
config.value = value
|
||||
else:
|
||||
session.add(AppConfig(key=key, value=value))
|
||||
|
||||
|
||||
def build_heatmap(
|
||||
enrollments,
|
||||
assessment,
|
||||
items: dict,
|
||||
item_extractor: Callable,
|
||||
grading_calc,
|
||||
sorted_student_names: List[str],
|
||||
*,
|
||||
color_map: Optional[Dict[str, str]] = None,
|
||||
) -> Optional[HeatmapData]:
|
||||
"""
|
||||
Construit une HeatmapData pour des compétences ou domaines.
|
||||
|
||||
Args:
|
||||
enrollments: liste d'inscriptions avec .student chargé
|
||||
assessment: l'évaluation avec .exercises chargés
|
||||
items: set ou dict des items à évaluer (noms)
|
||||
item_extractor: fonction (element) -> nom de l'item ou None
|
||||
grading_calc: instance de GradingCalculator
|
||||
sorted_student_names: noms triés pour l'axe Y
|
||||
color_map: optionnel, dict nom -> couleur pour les cellules
|
||||
"""
|
||||
if not items:
|
||||
return None
|
||||
|
||||
item_names = set(items) if isinstance(items, dict) else items
|
||||
cells = []
|
||||
|
||||
for enrollment in enrollments:
|
||||
student = enrollment.student
|
||||
student_name = student.full_name_reversed
|
||||
|
||||
item_scores = {name: {"score": 0.0, "max": 0.0} for name in item_names}
|
||||
|
||||
for exercise in assessment.exercises:
|
||||
for element in exercise.grading_elements:
|
||||
item_name = item_extractor(element)
|
||||
if item_name and item_name in item_scores:
|
||||
for g in element.grades:
|
||||
if g.student_id == student.id and g.value:
|
||||
calc_score = grading_calc.calculate_score(
|
||||
g.value.strip(),
|
||||
element.grading_type,
|
||||
element.max_points,
|
||||
)
|
||||
if calc_score is not None:
|
||||
item_scores[item_name]["score"] += calc_score
|
||||
item_scores[item_name]["max"] += element.max_points
|
||||
break
|
||||
|
||||
for name, data in item_scores.items():
|
||||
if data["max"] > 0:
|
||||
pct = round((data["score"] / data["max"]) * 100, 1)
|
||||
cell_kwargs = dict(
|
||||
student_id=student.id,
|
||||
student_name=student_name,
|
||||
item_name=name,
|
||||
score=round(data["score"], 2),
|
||||
max_points=data["max"],
|
||||
percentage=pct,
|
||||
)
|
||||
if color_map and name in color_map:
|
||||
cell_kwargs["color"] = color_map[name]
|
||||
cells.append(HeatmapCell(**cell_kwargs))
|
||||
|
||||
return HeatmapData(
|
||||
items=sorted(list(item_names)),
|
||||
students=sorted_student_names,
|
||||
cells=cells,
|
||||
)
|
||||
@@ -11,6 +11,12 @@ from sqlalchemy import select, func
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from api.dependencies import AsyncSessionDep
|
||||
from api.helpers import (
|
||||
count_eligible_students,
|
||||
eligible_student_ids_subquery,
|
||||
get_eligible_enrollments,
|
||||
build_heatmap,
|
||||
)
|
||||
from infrastructure.database.models import (
|
||||
Assessment,
|
||||
Exercise,
|
||||
@@ -36,8 +42,6 @@ from schemas.assessment import (
|
||||
SendReportsRequest,
|
||||
SendReportResult,
|
||||
SendReportsResponse,
|
||||
HeatmapCell,
|
||||
HeatmapData,
|
||||
)
|
||||
from schemas.grading import BulkGradeCreate, BulkGradeResponse, GradeRead
|
||||
from domain.services import GradingCalculator, StatisticsService, StudentReportService, generate_report_html, ConfigService
|
||||
@@ -124,21 +128,13 @@ async def get_assessments(
|
||||
total_elements += 1
|
||||
|
||||
# Compter les élèves éligibles (inscrits à la date de l'évaluation)
|
||||
eligible_query = select(func.count(StudentEnrollment.id)).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_students_count = await count_eligible_students(
|
||||
session, assessment.class_group_id, assessment.date
|
||||
)
|
||||
eligible_result = await session.execute(eligible_query)
|
||||
eligible_students_count = eligible_result.scalar() or 0
|
||||
|
||||
# Compter les notes saisies uniquement pour les élèves éligibles
|
||||
eligible_student_ids = select(StudentEnrollment.student_id).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_student_ids = eligible_student_ids_subquery(
|
||||
assessment.class_group_id, assessment.date
|
||||
)
|
||||
grades_query = select(func.count(Grade.id)).where(
|
||||
Grade.grading_element_id.in_(
|
||||
@@ -239,21 +235,13 @@ async def get_assessment(
|
||||
)
|
||||
|
||||
# Calculer la progression
|
||||
eligible_query = select(func.count(StudentEnrollment.id)).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_students_count = await count_eligible_students(
|
||||
session, assessment.class_group_id, assessment.date
|
||||
)
|
||||
eligible_result = await session.execute(eligible_query)
|
||||
eligible_students_count = eligible_result.scalar() or 0
|
||||
|
||||
# Compter les notes uniquement pour les élèves éligibles
|
||||
eligible_student_ids = select(StudentEnrollment.student_id).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_student_ids = eligible_student_ids_subquery(
|
||||
assessment.class_group_id, assessment.date
|
||||
)
|
||||
grades_query = select(func.count(Grade.id)).where(
|
||||
Grade.grading_element_id.in_(
|
||||
@@ -322,18 +310,9 @@ async def get_assessment_results(
|
||||
raise HTTPException(status_code=404, detail="Évaluation non trouvée")
|
||||
|
||||
# Récupérer les élèves éligibles
|
||||
eligible_query = (
|
||||
select(StudentEnrollment)
|
||||
.options(selectinload(StudentEnrollment.student))
|
||||
.where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
)
|
||||
enrollments = await get_eligible_enrollments(
|
||||
session, assessment.class_group_id, assessment.date
|
||||
)
|
||||
eligible_result = await session.execute(eligible_query)
|
||||
enrollments = eligible_result.scalars().all()
|
||||
|
||||
# Calculer le total des points maximum
|
||||
total_max_points = 0
|
||||
@@ -392,7 +371,7 @@ async def get_assessment_results(
|
||||
|
||||
student_scores[student_id] = StudentScore(
|
||||
student_id=student_id,
|
||||
student_name=f"{student.last_name} {student.first_name}",
|
||||
student_name=student.full_name_reversed,
|
||||
email=student.email, # Ajouter l'email de l'élève
|
||||
total_score=round(total_score, 2),
|
||||
total_max_points=counted_max,
|
||||
@@ -440,97 +419,25 @@ async def get_assessment_results(
|
||||
all_domains[element.domain.name] = element.domain.color
|
||||
|
||||
# Calculer heatmap des compétences si présentes
|
||||
if all_competences:
|
||||
competences_cells = []
|
||||
|
||||
for enrollment in enrollments:
|
||||
student = enrollment.student
|
||||
student_name = f"{student.last_name} {student.first_name}"
|
||||
|
||||
# Calculer score par compétence pour cet élève
|
||||
competence_scores = {}
|
||||
for comp in all_competences:
|
||||
competence_scores[comp] = {"score": 0.0, "max": 0.0}
|
||||
|
||||
for exercise in assessment.exercises:
|
||||
for element in exercise.grading_elements:
|
||||
if element.skill and element.skill in competence_scores:
|
||||
# Trouver la note
|
||||
for g in element.grades:
|
||||
if g.student_id == student.id and g.value:
|
||||
calc_score = grading_calc.calculate_score(
|
||||
g.value.strip(), element.grading_type, element.max_points
|
||||
)
|
||||
if calc_score is not None:
|
||||
competence_scores[element.skill]["score"] += calc_score
|
||||
competence_scores[element.skill]["max"] += element.max_points
|
||||
break
|
||||
|
||||
# Créer les cellules
|
||||
for comp, data in competence_scores.items():
|
||||
if data["max"] > 0:
|
||||
pct = round((data["score"] / data["max"]) * 100, 1)
|
||||
competences_cells.append(HeatmapCell(
|
||||
student_id=student.id,
|
||||
student_name=student_name,
|
||||
item_name=comp,
|
||||
score=round(data["score"], 2),
|
||||
max_points=data["max"],
|
||||
percentage=pct
|
||||
))
|
||||
|
||||
competences_heatmap = HeatmapData(
|
||||
items=sorted(list(all_competences)),
|
||||
students=[s.student_name for s in sorted_scores],
|
||||
cells=competences_cells
|
||||
)
|
||||
competences_heatmap = build_heatmap(
|
||||
enrollments=enrollments,
|
||||
assessment=assessment,
|
||||
items=all_competences,
|
||||
item_extractor=lambda el: el.skill,
|
||||
grading_calc=grading_calc,
|
||||
sorted_student_names=[s.student_name for s in sorted_scores],
|
||||
)
|
||||
|
||||
# Calculer heatmap des domaines si présents
|
||||
if all_domains:
|
||||
domains_cells = []
|
||||
|
||||
for enrollment in enrollments:
|
||||
student = enrollment.student
|
||||
student_name = f"{student.last_name} {student.first_name}"
|
||||
|
||||
# Calculer score par domaine pour cet élève
|
||||
domain_scores = {}
|
||||
for dom in all_domains:
|
||||
domain_scores[dom] = {"score": 0.0, "max": 0.0}
|
||||
|
||||
for exercise in assessment.exercises:
|
||||
for element in exercise.grading_elements:
|
||||
if element.domain and element.domain.name in domain_scores:
|
||||
# Trouver la note
|
||||
for g in element.grades:
|
||||
if g.student_id == student.id and g.value:
|
||||
calc_score = grading_calc.calculate_score(
|
||||
g.value.strip(), element.grading_type, element.max_points
|
||||
)
|
||||
if calc_score is not None:
|
||||
domain_scores[element.domain.name]["score"] += calc_score
|
||||
domain_scores[element.domain.name]["max"] += element.max_points
|
||||
break
|
||||
|
||||
# Créer les cellules
|
||||
for dom, data in domain_scores.items():
|
||||
if data["max"] > 0:
|
||||
pct = round((data["score"] / data["max"]) * 100, 1)
|
||||
domains_cells.append(HeatmapCell(
|
||||
student_id=student.id,
|
||||
student_name=student_name,
|
||||
item_name=dom,
|
||||
score=round(data["score"], 2),
|
||||
max_points=data["max"],
|
||||
percentage=pct,
|
||||
color=all_domains.get(dom)
|
||||
))
|
||||
|
||||
domains_heatmap = HeatmapData(
|
||||
items=sorted(list(all_domains.keys())),
|
||||
students=[s.student_name for s in sorted_scores],
|
||||
cells=domains_cells
|
||||
)
|
||||
domains_heatmap = build_heatmap(
|
||||
enrollments=enrollments,
|
||||
assessment=assessment,
|
||||
items=all_domains,
|
||||
item_extractor=lambda el: el.domain.name if el.domain else None,
|
||||
grading_calc=grading_calc,
|
||||
sorted_student_names=[s.student_name for s in sorted_scores],
|
||||
color_map=all_domains,
|
||||
)
|
||||
|
||||
return AssessmentResults(
|
||||
assessment_id=assessment.id,
|
||||
@@ -827,21 +734,13 @@ async def update_assessment(
|
||||
)
|
||||
|
||||
# Calculer la progression
|
||||
eligible_query = select(func.count(StudentEnrollment.id)).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_students_count = await count_eligible_students(
|
||||
session, assessment.class_group_id, assessment.date
|
||||
)
|
||||
eligible_result = await session.execute(eligible_query)
|
||||
eligible_students_count = eligible_result.scalar() or 0
|
||||
|
||||
# Compter les notes uniquement pour les élèves éligibles
|
||||
eligible_student_ids = select(StudentEnrollment.student_id).where(
|
||||
StudentEnrollment.class_group_id == assessment.class_group_id,
|
||||
StudentEnrollment.enrollment_date <= assessment.date,
|
||||
(StudentEnrollment.departure_date.is_(None) |
|
||||
(StudentEnrollment.departure_date >= assessment.date))
|
||||
eligible_student_ids = eligible_student_ids_subquery(
|
||||
assessment.class_group_id, assessment.date
|
||||
)
|
||||
grades_query = select(func.count(Grade.id)).where(
|
||||
Grade.grading_element_id.in_(
|
||||
@@ -1132,7 +1031,7 @@ async def send_reports(
|
||||
total_failed = 0
|
||||
|
||||
for student in students:
|
||||
student_name = f"{student.first_name} {student.last_name}"
|
||||
student_name = student.full_name
|
||||
|
||||
# Vérifier que l'élève a une adresse email
|
||||
if not student.email:
|
||||
@@ -1307,7 +1206,7 @@ async def preview_report(
|
||||
if student_id not in all_students_grades:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"L'élève {student.first_name} {student.last_name} n'a pas de notes pour cette évaluation"
|
||||
detail=f"L'élève {student.full_name} n'a pas de notes pour cette évaluation"
|
||||
)
|
||||
|
||||
# Créer le service de rapport
|
||||
|
||||
@@ -12,6 +12,7 @@ from sqlalchemy import select, func
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from api.dependencies import AsyncSessionDep
|
||||
from api.helpers import ensure_unique_name
|
||||
from infrastructure.database.models import (
|
||||
ClassGroup,
|
||||
Student,
|
||||
@@ -201,7 +202,7 @@ async def get_class_students(
|
||||
last_name=student.last_name,
|
||||
first_name=student.first_name,
|
||||
email=student.email,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
current_class_id=class_id if is_active else None,
|
||||
current_class_name=cls.name if is_active else None,
|
||||
enrollment_id=enrollment.id,
|
||||
@@ -419,13 +420,7 @@ async def create_class(
|
||||
Crée une nouvelle classe.
|
||||
"""
|
||||
# Vérifier l'unicité du nom
|
||||
existing_query = select(ClassGroup).where(ClassGroup.name == class_data.name)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Une classe avec le nom '{class_data.name}' existe déjà"
|
||||
)
|
||||
await ensure_unique_name(session, ClassGroup, class_data.name, entity_label="classe")
|
||||
|
||||
# Créer la nouvelle classe
|
||||
new_class = ClassGroup(
|
||||
@@ -466,16 +461,10 @@ async def update_class(
|
||||
|
||||
# Vérifier l'unicité du nouveau nom si modifié
|
||||
if class_data.name and class_data.name != cls.name:
|
||||
existing_query = select(ClassGroup).where(
|
||||
ClassGroup.name == class_data.name,
|
||||
ClassGroup.id != class_id
|
||||
await ensure_unique_name(
|
||||
session, ClassGroup, class_data.name,
|
||||
exclude_id=class_id, entity_label="classe"
|
||||
)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Une autre classe avec le nom '{class_data.name}' existe déjà"
|
||||
)
|
||||
|
||||
# Appliquer les modifications
|
||||
if class_data.name is not None:
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, HTTPException
|
||||
from sqlalchemy import select, func, delete
|
||||
|
||||
from api.dependencies import AsyncSessionDep
|
||||
from api.helpers import ensure_unique_name, upsert_app_configs
|
||||
from infrastructure.database.models import (
|
||||
AppConfig,
|
||||
Competence,
|
||||
@@ -228,13 +229,7 @@ async def create_competence(
|
||||
Crée une nouvelle compétence.
|
||||
"""
|
||||
# Vérifier l'unicité du nom
|
||||
existing_query = select(Competence).where(Competence.name == data.name)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Une compétence avec le nom '{data.name}' existe déjà"
|
||||
)
|
||||
await ensure_unique_name(session, Competence, data.name, entity_label="compétence")
|
||||
|
||||
# Déterminer l'index d'ordre
|
||||
if data.order_index is None:
|
||||
@@ -284,16 +279,7 @@ async def update_competence(
|
||||
|
||||
# Vérifier l'unicité du nouveau nom
|
||||
if data.name and data.name != competence.name:
|
||||
existing_query = select(Competence).where(
|
||||
Competence.name == data.name,
|
||||
Competence.id != competence_id
|
||||
)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Une autre compétence avec le nom '{data.name}' existe déjà"
|
||||
)
|
||||
await ensure_unique_name(session, Competence, data.name, exclude_id=competence_id, entity_label="compétence")
|
||||
|
||||
# Appliquer les modifications
|
||||
if data.name is not None:
|
||||
@@ -353,13 +339,7 @@ async def create_domain(
|
||||
Crée un nouveau domaine.
|
||||
"""
|
||||
# Vérifier l'unicité du nom
|
||||
existing_query = select(Domain).where(Domain.name == data.name)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Un domaine avec le nom '{data.name}' existe déjà"
|
||||
)
|
||||
await ensure_unique_name(session, Domain, data.name, entity_label="domaine")
|
||||
|
||||
# Créer le domaine
|
||||
domain = Domain(
|
||||
@@ -398,16 +378,7 @@ async def update_domain(
|
||||
|
||||
# Vérifier l'unicité du nouveau nom
|
||||
if data.name and data.name != domain.name:
|
||||
existing_query = select(Domain).where(
|
||||
Domain.name == data.name,
|
||||
Domain.id != domain_id
|
||||
)
|
||||
existing_result = await session.execute(existing_query)
|
||||
if existing_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Un autre domaine avec le nom '{data.name}' existe déjà"
|
||||
)
|
||||
await ensure_unique_name(session, Domain, data.name, exclude_id=domain_id, entity_label="domaine")
|
||||
|
||||
# Appliquer les modifications
|
||||
if data.name is not None:
|
||||
@@ -669,18 +640,7 @@ async def update_app_config(
|
||||
if data.default_grading_system is not None:
|
||||
updates.append(("default_grading_system", data.default_grading_system))
|
||||
|
||||
for key, value in updates:
|
||||
# Chercher la config existante
|
||||
query = select(AppConfig).where(AppConfig.key == key)
|
||||
result = await session.execute(query)
|
||||
config = result.scalar_one_or_none()
|
||||
|
||||
if config:
|
||||
config.value = value
|
||||
else:
|
||||
# Créer si n'existe pas
|
||||
new_config = AppConfig(key=key, value=value)
|
||||
session.add(new_config)
|
||||
await upsert_app_configs(session, dict(updates))
|
||||
|
||||
await session.commit()
|
||||
|
||||
@@ -755,18 +715,7 @@ async def update_smtp_config(
|
||||
if data.from_address is not None:
|
||||
updates.append(("email.from_address", data.from_address))
|
||||
|
||||
for key, value in updates:
|
||||
# Chercher la config existante
|
||||
query = select(AppConfig).where(AppConfig.key == key)
|
||||
result = await session.execute(query)
|
||||
config = result.scalar_one_or_none()
|
||||
|
||||
if config:
|
||||
config.value = value
|
||||
else:
|
||||
# Créer si n'existe pas
|
||||
new_config = AppConfig(key=key, value=value)
|
||||
session.add(new_config)
|
||||
await upsert_app_configs(session, dict(updates))
|
||||
|
||||
await session.commit()
|
||||
|
||||
@@ -843,16 +792,7 @@ async def update_notes_gradient(
|
||||
if data.enabled is not None:
|
||||
updates.append(("grading.notes_gradient.enabled", "true" if data.enabled else "false"))
|
||||
|
||||
for key, value in updates:
|
||||
query = select(AppConfig).where(AppConfig.key == key)
|
||||
result = await session.execute(query)
|
||||
config = result.scalar_one_or_none()
|
||||
|
||||
if config:
|
||||
config.value = value
|
||||
else:
|
||||
new_config = AppConfig(key=key, value=value)
|
||||
session.add(new_config)
|
||||
await upsert_app_configs(session, dict(updates))
|
||||
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -202,7 +202,7 @@ async def get_council_preparation(
|
||||
student_id=student.id,
|
||||
first_name=student.first_name,
|
||||
last_name=student.last_name,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
overall_average=overall_average,
|
||||
assessment_count=assessment_count,
|
||||
grades_by_assessment=grades_by_assessment,
|
||||
|
||||
@@ -10,6 +10,7 @@ from sqlalchemy import select, func
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from api.dependencies import AsyncSessionDep
|
||||
from api.helpers import get_active_enrollment
|
||||
from infrastructure.database.models import (
|
||||
Student,
|
||||
StudentEnrollment,
|
||||
@@ -62,11 +63,7 @@ async def get_students(
|
||||
students_list = []
|
||||
for student in students:
|
||||
# Trouver l'inscription active
|
||||
current_enrollment = None
|
||||
for enrollment in student.enrollments:
|
||||
if enrollment.departure_date is None:
|
||||
current_enrollment = enrollment
|
||||
break
|
||||
current_enrollment = get_active_enrollment(student)
|
||||
|
||||
# Filtrer par classe si demandé
|
||||
if class_id and (not current_enrollment or current_enrollment.class_group_id != class_id):
|
||||
@@ -78,7 +75,7 @@ async def get_students(
|
||||
last_name=student.last_name,
|
||||
first_name=student.first_name,
|
||||
email=student.email,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
current_class_id=current_enrollment.class_group_id if current_enrollment else None,
|
||||
current_class_name=current_enrollment.class_group.name if current_enrollment else None
|
||||
)
|
||||
@@ -113,13 +110,10 @@ async def get_student(
|
||||
raise HTTPException(status_code=404, detail="Étudiant non trouvé")
|
||||
|
||||
# Trouver l'inscription active
|
||||
current_enrollment = None
|
||||
current_enrollment = get_active_enrollment(student)
|
||||
enrollments_list = []
|
||||
|
||||
for enrollment in student.enrollments:
|
||||
if enrollment.departure_date is None:
|
||||
current_enrollment = enrollment
|
||||
|
||||
enrollments_list.append(
|
||||
EnrollmentRead(
|
||||
id=enrollment.id,
|
||||
@@ -144,7 +138,7 @@ async def get_student(
|
||||
last_name=student.last_name,
|
||||
first_name=student.first_name,
|
||||
email=student.email,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
current_class_id=current_enrollment.class_group_id if current_enrollment else None,
|
||||
current_class_name=current_enrollment.class_group.name if current_enrollment else None,
|
||||
enrollments=enrollments_list
|
||||
@@ -210,7 +204,7 @@ async def create_student(
|
||||
last_name=new_student.last_name,
|
||||
first_name=new_student.first_name,
|
||||
email=new_student.email,
|
||||
full_name=f"{new_student.first_name} {new_student.last_name}",
|
||||
full_name=new_student.full_name,
|
||||
current_class_id=current_class_id,
|
||||
current_class_name=current_class_name
|
||||
)
|
||||
@@ -264,18 +258,14 @@ async def update_student(
|
||||
await session.refresh(student)
|
||||
|
||||
# Trouver la classe actuelle
|
||||
current_enrollment = None
|
||||
for enrollment in student.enrollments:
|
||||
if enrollment.departure_date is None:
|
||||
current_enrollment = enrollment
|
||||
break
|
||||
current_enrollment = get_active_enrollment(student)
|
||||
|
||||
return StudentWithClass(
|
||||
id=student.id,
|
||||
last_name=student.last_name,
|
||||
first_name=student.first_name,
|
||||
email=student.email,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
current_class_id=current_enrollment.class_group_id if current_enrollment else None,
|
||||
current_class_name=current_enrollment.class_group.name if current_enrollment else None
|
||||
)
|
||||
@@ -325,18 +315,14 @@ async def update_student_email(
|
||||
await session.refresh(student)
|
||||
|
||||
# Trouver la classe actuelle
|
||||
current_enrollment = None
|
||||
for enrollment in student.enrollments:
|
||||
if enrollment.departure_date is None:
|
||||
current_enrollment = enrollment
|
||||
break
|
||||
current_enrollment = get_active_enrollment(student)
|
||||
|
||||
return StudentWithClass(
|
||||
id=student.id,
|
||||
last_name=student.last_name,
|
||||
first_name=student.first_name,
|
||||
email=student.email,
|
||||
full_name=f"{student.first_name} {student.last_name}",
|
||||
full_name=student.full_name,
|
||||
current_class_id=current_enrollment.class_group_id if current_enrollment else None,
|
||||
current_class_name=current_enrollment.class_group.name if current_enrollment else None
|
||||
)
|
||||
@@ -403,7 +389,7 @@ async def enroll_student(
|
||||
if active_result.scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"L'élève {student.first_name} {student.last_name} est déjà inscrit dans une classe"
|
||||
detail=f"L'élève {student.full_name} est déjà inscrit dans une classe"
|
||||
)
|
||||
else:
|
||||
# Nouvel élève
|
||||
@@ -447,9 +433,9 @@ async def enroll_student(
|
||||
return EnrollmentResponse(
|
||||
enrollment_id=enrollment.id,
|
||||
student_id=student.id,
|
||||
student_name=f"{student.first_name} {student.last_name}",
|
||||
student_name=student.full_name,
|
||||
class_name=class_group.name,
|
||||
message=f"Élève {student.first_name} {student.last_name} inscrit en {class_group.name}",
|
||||
message=f"Élève {student.full_name} inscrit en {class_group.name}",
|
||||
is_new_student=is_new_student
|
||||
)
|
||||
|
||||
@@ -493,7 +479,7 @@ async def transfer_student(
|
||||
if not old_enrollment:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Aucune inscription active trouvée pour l'élève {student.first_name} {student.last_name}"
|
||||
detail=f"Aucune inscription active trouvée pour l'élève {student.full_name}"
|
||||
)
|
||||
|
||||
old_class_name = old_enrollment.class_group.name
|
||||
@@ -516,10 +502,10 @@ async def transfer_student(
|
||||
return TransferResponse(
|
||||
old_enrollment_id=old_enrollment.id,
|
||||
new_enrollment_id=new_enrollment.id,
|
||||
student_name=f"{student.first_name} {student.last_name}",
|
||||
student_name=student.full_name,
|
||||
old_class_name=old_class_name,
|
||||
new_class_name=new_class.name,
|
||||
message=f"Élève {student.first_name} {student.last_name} transféré de {old_class_name} vers {new_class.name}"
|
||||
message=f"Élève {student.full_name} transféré de {old_class_name} vers {new_class.name}"
|
||||
)
|
||||
|
||||
|
||||
@@ -554,7 +540,7 @@ async def record_departure(
|
||||
if not enrollment:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Aucune inscription active trouvée pour l'élève {student.first_name} {student.last_name}"
|
||||
detail=f"Aucune inscription active trouvée pour l'élève {student.full_name}"
|
||||
)
|
||||
|
||||
class_name = enrollment.class_group.name
|
||||
@@ -567,7 +553,7 @@ async def record_departure(
|
||||
|
||||
return DepartureResponse(
|
||||
enrollment_id=enrollment.id,
|
||||
student_name=f"{student.first_name} {student.last_name}",
|
||||
student_name=student.full_name,
|
||||
class_name=class_name,
|
||||
message=f"Départ de {student.first_name} {student.last_name} de {class_name} enregistré"
|
||||
message=f"Départ de {student.full_name} de {class_name} enregistré"
|
||||
)
|
||||
|
||||
@@ -123,6 +123,16 @@ class Student(Base):
|
||||
"CouncilAppreciation", back_populates="student", lazy="selectin"
|
||||
)
|
||||
|
||||
@property
|
||||
def full_name(self) -> str:
|
||||
"""Prénom Nom"""
|
||||
return f"{self.first_name} {self.last_name}"
|
||||
|
||||
@property
|
||||
def full_name_reversed(self) -> str:
|
||||
"""Nom Prénom"""
|
||||
return f"{self.last_name} {self.first_name}"
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Student {self.first_name} {self.last_name}>"
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<div class="xl:col-span-3 space-y-2">
|
||||
<!-- Chart -->
|
||||
<section v-if="chartData.labels.length > 0">
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Parcours sur l'annee</h3>
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Parcours sur l'année</h3>
|
||||
<div class="bg-gray-50 rounded-lg p-2" style="height: 220px">
|
||||
<Bar :key="student.student_id" :data="chartData" :options="chartOptions" />
|
||||
</div>
|
||||
@@ -72,7 +72,7 @@
|
||||
<div class="xl:col-span-2 space-y-3">
|
||||
<!-- Evaluations -->
|
||||
<section v-if="assessmentList.length">
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Evaluations</h3>
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Évaluations</h3>
|
||||
<div class="space-y-0.5">
|
||||
<div
|
||||
v-for="a in assessmentList"
|
||||
@@ -106,7 +106,7 @@
|
||||
</div>
|
||||
</section>
|
||||
<section v-if="competenceList.length">
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Competences</h3>
|
||||
<h3 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wide mb-1">Compétences</h3>
|
||||
<div class="bg-gray-50 rounded-lg p-2" :style="{ height: competenceChartHeight }">
|
||||
<ChartGeneric type="boxplot" :data="competenceBoxPlotData" :options="boxPlotOptions" />
|
||||
</div>
|
||||
@@ -182,7 +182,7 @@ const chartData = computed(() => {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Eleve',
|
||||
label: 'Élève',
|
||||
data: studentScores,
|
||||
backgroundColor: barBgColors,
|
||||
borderRadius: 3,
|
||||
@@ -302,7 +302,7 @@ const competenceList = computed(() => {
|
||||
const meta = lookup[c.competence_id] || {}
|
||||
return {
|
||||
id: c.competence_id,
|
||||
name: meta.name || `Competence ${c.competence_id}`,
|
||||
name: meta.name || `Compétence ${c.competence_id}`,
|
||||
color: meta.color || '#6B7280',
|
||||
pct: (c.total_points_obtained / c.total_points_possible) * 100
|
||||
}
|
||||
@@ -358,7 +358,7 @@ const domainBoxPlotData = computed(() => {
|
||||
},
|
||||
{
|
||||
type: 'scatter',
|
||||
label: 'Eleve',
|
||||
label: 'Élève',
|
||||
data: domains.map((d, i) => ({ x: d.pct, y: i })),
|
||||
pointRadius: 7,
|
||||
pointStyle: 'rectRot',
|
||||
@@ -388,7 +388,7 @@ const competenceBoxPlotData = computed(() => {
|
||||
},
|
||||
{
|
||||
type: 'scatter',
|
||||
label: 'Eleve',
|
||||
label: 'Élève',
|
||||
data: comps.map((c, i) => ({ x: c.pct, y: i })),
|
||||
pointRadius: 7,
|
||||
pointStyle: 'rectRot',
|
||||
@@ -410,7 +410,7 @@ const boxPlotOptions = {
|
||||
callbacks: {
|
||||
label(ctx) {
|
||||
if (ctx.dataset.type === 'scatter') {
|
||||
return `Eleve: ${ctx.raw.x.toFixed(0)}%`
|
||||
return `Élève : ${ctx.raw.x.toFixed(0)}%`
|
||||
}
|
||||
const item = ctx.raw
|
||||
return [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import assessmentsService from '@/services/assessments'
|
||||
import { withLoading } from './helpers'
|
||||
|
||||
export const useAssessmentsStore = defineStore('assessments', () => {
|
||||
// State
|
||||
@@ -44,130 +45,61 @@ export const useAssessmentsStore = defineStore('assessments', () => {
|
||||
)
|
||||
|
||||
// Actions
|
||||
async function fetchAssessments(customFilters = null) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const queryFilters = customFilters || filters.value
|
||||
assessments.value = await assessmentsService.getAll(queryFilters)
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchAssessments = withLoading(loading, error, async (customFilters = null) => {
|
||||
const queryFilters = customFilters || filters.value
|
||||
assessments.value = await assessmentsService.getAll(queryFilters)
|
||||
})
|
||||
|
||||
async function fetchAssessment(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
currentAssessment.value = await assessmentsService.getById(id)
|
||||
return currentAssessment.value
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchAssessment = withLoading(loading, error, async (id) => {
|
||||
currentAssessment.value = await assessmentsService.getById(id)
|
||||
return currentAssessment.value
|
||||
})
|
||||
|
||||
async function fetchResults(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
currentResults.value = await assessmentsService.getResults(id)
|
||||
return currentResults.value
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchResults = withLoading(loading, error, async (id) => {
|
||||
currentResults.value = await assessmentsService.getResults(id)
|
||||
return currentResults.value
|
||||
})
|
||||
|
||||
async function fetchGrades(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
currentGrades.value = await assessmentsService.getGrades(id)
|
||||
return currentGrades.value
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchGrades = withLoading(loading, error, async (id) => {
|
||||
currentGrades.value = await assessmentsService.getGrades(id)
|
||||
return currentGrades.value
|
||||
})
|
||||
|
||||
async function createAssessment(data) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const newAssessment = await assessmentsService.create(data)
|
||||
assessments.value.unshift(newAssessment)
|
||||
return newAssessment
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const createAssessment = withLoading(loading, error, async (data) => {
|
||||
const newAssessment = await assessmentsService.create(data)
|
||||
assessments.value.unshift(newAssessment)
|
||||
return newAssessment
|
||||
})
|
||||
|
||||
async function updateAssessment(id, data) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const updated = await assessmentsService.update(id, data)
|
||||
const index = assessments.value.findIndex(a => a.id === id)
|
||||
if (index !== -1) {
|
||||
assessments.value[index] = updated
|
||||
}
|
||||
if (currentAssessment.value?.id === id) {
|
||||
currentAssessment.value = updated
|
||||
}
|
||||
return updated
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
const updateAssessment = withLoading(loading, error, async (id, data) => {
|
||||
const updated = await assessmentsService.update(id, data)
|
||||
const index = assessments.value.findIndex(a => a.id === id)
|
||||
if (index !== -1) {
|
||||
assessments.value[index] = updated
|
||||
}
|
||||
}
|
||||
if (currentAssessment.value?.id === id) {
|
||||
currentAssessment.value = updated
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
async function deleteAssessment(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
await assessmentsService.delete(id)
|
||||
assessments.value = assessments.value.filter(a => a.id !== id)
|
||||
if (currentAssessment.value?.id === id) {
|
||||
currentAssessment.value = null
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
const deleteAssessment = withLoading(loading, error, async (id) => {
|
||||
await assessmentsService.delete(id)
|
||||
assessments.value = assessments.value.filter(a => a.id !== id)
|
||||
if (currentAssessment.value?.id === id) {
|
||||
currentAssessment.value = null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
async function saveGrades(id, grades) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const result = await assessmentsService.saveGrades(id, grades)
|
||||
// Refresh assessment to update progress
|
||||
await fetchAssessment(id)
|
||||
return result
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
// fetchAssessment is declared above so it can be called here safely.
|
||||
// withLoading sets loading=false in its finally block, so the inner call
|
||||
// to fetchAssessment runs as a nested operation within the outer wrapper.
|
||||
const saveGrades = withLoading(loading, error, async (id, grades) => {
|
||||
const result = await assessmentsService.saveGrades(id, grades)
|
||||
// Refresh assessment to update progress
|
||||
await fetchAssessment(id)
|
||||
return result
|
||||
})
|
||||
|
||||
function setFilters(newFilters) {
|
||||
filters.value = { ...filters.value, ...newFilters }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import classesService from '@/services/classes'
|
||||
import { withLoading } from './helpers'
|
||||
|
||||
export const useClassesStore = defineStore('classes', () => {
|
||||
// State
|
||||
@@ -17,99 +18,45 @@ export const useClassesStore = defineStore('classes', () => {
|
||||
)
|
||||
|
||||
// Actions
|
||||
async function fetchClasses() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
classes.value = await classesService.getAll()
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchClasses = withLoading(loading, error, async () => {
|
||||
classes.value = await classesService.getAll()
|
||||
})
|
||||
|
||||
async function fetchClass(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
currentClass.value = await classesService.getById(id)
|
||||
return currentClass.value
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchClass = withLoading(loading, error, async (id) => {
|
||||
currentClass.value = await classesService.getById(id)
|
||||
return currentClass.value
|
||||
})
|
||||
|
||||
async function fetchClassStats(id, trimester = null) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
currentStats.value = await classesService.getStats(id, trimester)
|
||||
return currentStats.value
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const fetchClassStats = withLoading(loading, error, async (id, trimester = null) => {
|
||||
currentStats.value = await classesService.getStats(id, trimester)
|
||||
return currentStats.value
|
||||
})
|
||||
|
||||
async function createClass(data) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const newClass = await classesService.create(data)
|
||||
classes.value.push(newClass)
|
||||
return newClass
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const createClass = withLoading(loading, error, async (data) => {
|
||||
const newClass = await classesService.create(data)
|
||||
classes.value.push(newClass)
|
||||
return newClass
|
||||
})
|
||||
|
||||
async function updateClass(id, data) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const updated = await classesService.update(id, data)
|
||||
const index = classes.value.findIndex(c => c.id === id)
|
||||
if (index !== -1) {
|
||||
classes.value[index] = updated
|
||||
}
|
||||
if (currentClass.value?.id === id) {
|
||||
currentClass.value = updated
|
||||
}
|
||||
return updated
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
const updateClass = withLoading(loading, error, async (id, data) => {
|
||||
const updated = await classesService.update(id, data)
|
||||
const index = classes.value.findIndex(c => c.id === id)
|
||||
if (index !== -1) {
|
||||
classes.value[index] = updated
|
||||
}
|
||||
}
|
||||
if (currentClass.value?.id === id) {
|
||||
currentClass.value = updated
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
async function deleteClass(id) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
await classesService.delete(id)
|
||||
classes.value = classes.value.filter(c => c.id !== id)
|
||||
if (currentClass.value?.id === id) {
|
||||
currentClass.value = null
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
const deleteClass = withLoading(loading, error, async (id) => {
|
||||
await classesService.delete(id)
|
||||
classes.value = classes.value.filter(c => c.id !== id)
|
||||
if (currentClass.value?.id === id) {
|
||||
currentClass.value = null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function clearCurrent() {
|
||||
currentClass.value = null
|
||||
|
||||
22
frontend/src/stores/helpers.js
Normal file
22
frontend/src/stores/helpers.js
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Wraps an async function with loading/error state management.
|
||||
*
|
||||
* @param {import('vue').Ref<boolean>} loading - shared loading ref
|
||||
* @param {import('vue').Ref<string|null>} error - shared error ref
|
||||
* @param {Function} fn - async function to wrap
|
||||
* @returns {Function} wrapped function with identical signature
|
||||
*/
|
||||
export function withLoading(loading, error, fn) {
|
||||
return async (...args) => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await fn(...args)
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<router-link
|
||||
:to="`/assessments/${assessment.id}/grading`"
|
||||
class="card card-body text-center hover:shadow-md transition-shadow"
|
||||
class="card card-body text-center hover:shadow-md transition-shadow bg-primary-50 border-2 border-primary-200"
|
||||
>
|
||||
<PencilIcon class="w-8 h-8 text-primary-600 mx-auto mb-2" />
|
||||
<span class="font-medium">Noter</span>
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
<button
|
||||
@click="confirmDelete"
|
||||
class="card card-body text-center hover:shadow-md transition-shadow"
|
||||
class="card card-body text-center hover:shadow-md transition-shadow border-dashed border-red-200 opacity-75"
|
||||
>
|
||||
<TrashIcon class="w-8 h-8 text-danger-600 mx-auto mb-2" />
|
||||
<span class="font-medium">Supprimer</span>
|
||||
|
||||
@@ -277,8 +277,8 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, computed, nextTick } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from 'vue'
|
||||
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
|
||||
import { useAssessmentsStore } from '@/stores/assessments'
|
||||
import { useClassesStore } from '@/stores/classes'
|
||||
import { useNotificationsStore } from '@/stores/notifications'
|
||||
@@ -295,6 +295,7 @@ const isEdit = computed(() => !!route.params.id)
|
||||
const submitting = ref(false)
|
||||
const classes = computed(() => classesStore.classes)
|
||||
const competences = ref([])
|
||||
const formDirty = ref(false)
|
||||
|
||||
// Computed pour le récapitulatif
|
||||
const totalElements = computed(() => {
|
||||
@@ -368,6 +369,29 @@ const form = ref({
|
||||
exercises: []
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
formDirty.value = true
|
||||
}, { deep: true })
|
||||
|
||||
onBeforeRouteLeave((to, from, next) => {
|
||||
if (formDirty.value && !submitting.value) {
|
||||
if (confirm('Vous avez des modifications non sauvegardées. Quitter cette page ?')) {
|
||||
next()
|
||||
} else {
|
||||
next(false)
|
||||
}
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
function handleBeforeUnload(event) {
|
||||
if (formDirty.value) {
|
||||
event.preventDefault()
|
||||
event.returnValue = 'Vous avez des modifications non sauvegardées.'
|
||||
}
|
||||
}
|
||||
|
||||
function addExercise() {
|
||||
const newOrder = form.value.exercises.length + 1
|
||||
form.value.exercises.push({
|
||||
@@ -387,8 +411,13 @@ function addExercise() {
|
||||
}
|
||||
|
||||
function removeExercise(idx) {
|
||||
const exercise = form.value.exercises[idx]
|
||||
if (isEdit.value && exercise.id) {
|
||||
if (!confirm('Cet exercice contient potentiellement des notes. Supprimer ?')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
form.value.exercises.splice(idx, 1)
|
||||
// Renumber exercises
|
||||
form.value.exercises.forEach((ex, i) => {
|
||||
ex.order = i + 1
|
||||
})
|
||||
@@ -417,6 +446,12 @@ function addElement(exIdx) {
|
||||
}
|
||||
|
||||
function removeElement(exIdx, elIdx) {
|
||||
const element = form.value.exercises[exIdx].grading_elements[elIdx]
|
||||
if (isEdit.value && element.id) {
|
||||
if (!confirm('Cet élément contient potentiellement des notes. Supprimer ?')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
form.value.exercises[exIdx].grading_elements.splice(elIdx, 1)
|
||||
}
|
||||
|
||||
@@ -470,10 +505,12 @@ async function submit() {
|
||||
if (isEdit.value) {
|
||||
await assessmentsStore.updateAssessment(route.params.id, data)
|
||||
notifications.success('Évaluation modifiée avec succès')
|
||||
formDirty.value = false
|
||||
router.push(`/assessments/${route.params.id}`)
|
||||
} else {
|
||||
const created = await assessmentsStore.createAssessment(data)
|
||||
notifications.success('Évaluation créée avec succès')
|
||||
formDirty.value = false
|
||||
router.push(`/assessments/${created.id}`)
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -526,6 +563,13 @@ onMounted(async () => {
|
||||
// Add first exercise for new assessment
|
||||
addExercise()
|
||||
}
|
||||
window.addEventListener('beforeunload', handleBeforeUnload)
|
||||
// Reset dirty flag after initial load
|
||||
nextTick(() => { formDirty.value = false })
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
})
|
||||
|
||||
async function loadCompetences() {
|
||||
|
||||
@@ -124,9 +124,14 @@
|
||||
<ProgressIndicator
|
||||
:progress="assessment.progress"
|
||||
size="md"
|
||||
:clickable="true"
|
||||
@click.prevent="goToGrading(assessment.id)"
|
||||
/>
|
||||
<router-link
|
||||
:to="`/assessments/${assessment.id}/grading`"
|
||||
class="text-xs font-medium text-primary-600 hover:text-primary-800 whitespace-nowrap"
|
||||
@click.stop
|
||||
>
|
||||
Corriger
|
||||
</router-link>
|
||||
<ChevronRightIcon class="w-5 h-5 text-gray-400" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -57,7 +57,11 @@
|
||||
</div>
|
||||
|
||||
<!-- Stats principales - Grid 4 colonnes -->
|
||||
<div v-if="stats" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
<div v-if="stats" class="relative">
|
||||
<div v-if="statsLoading" class="absolute inset-0 bg-white/60 z-10 flex items-center justify-center rounded-xl">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
<!-- Moyenne classe -->
|
||||
<div class="bg-white rounded-xl shadow-md p-6 hover:shadow-lg transition-all duration-300">
|
||||
<p class="text-sm text-gray-500 mb-1">Moyenne classe</p>
|
||||
@@ -96,6 +100,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Domaines et Compétences en 2 colonnes -->
|
||||
<div v-if="stats" class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
|
||||
@@ -243,6 +248,7 @@ const stats = ref(null)
|
||||
const trimester = ref(null) // null = vision annuelle par défaut
|
||||
const sortColumn = ref('name')
|
||||
const sortDirection = ref('asc')
|
||||
const statsLoading = ref(false)
|
||||
|
||||
async function fetchData() {
|
||||
loading.value = true
|
||||
@@ -257,7 +263,12 @@ async function fetchData() {
|
||||
|
||||
async function selectTrimester(t) {
|
||||
trimester.value = t
|
||||
stats.value = await classesStore.fetchClassStats(route.params.id, t)
|
||||
statsLoading.value = true
|
||||
try {
|
||||
stats.value = await classesStore.fetchClassStats(route.params.id, t)
|
||||
} finally {
|
||||
statsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Récupérer la liste des évaluations triée par date
|
||||
|
||||
@@ -97,6 +97,27 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal v-model="showDeleteModal" title="Confirmer la suppression" size="sm">
|
||||
<p class="text-gray-600">
|
||||
Êtes-vous sûr de vouloir supprimer la classe
|
||||
<strong>{{ classToDelete?.name }}</strong> ?
|
||||
</p>
|
||||
<p class="mt-2 text-sm text-gray-500">
|
||||
Cette classe contient <strong>{{ classToDelete?.students_count || 0 }}</strong> élève(s).
|
||||
Cette action est irréversible.
|
||||
</p>
|
||||
<template #footer>
|
||||
<div class="flex justify-end gap-3">
|
||||
<button @click="showDeleteModal = false" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
|
||||
Annuler
|
||||
</button>
|
||||
<button @click="executeDelete" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700">
|
||||
Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</Modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -105,6 +126,7 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import { useClassesStore } from '@/stores/classes'
|
||||
import SkeletonLoader from '@/components/common/SkeletonLoader.vue'
|
||||
import EmptyState from '@/components/common/EmptyState.vue'
|
||||
import Modal from '@/components/common/Modal.vue'
|
||||
|
||||
// Icons
|
||||
const PlusIcon = { template: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" /></svg>' }
|
||||
@@ -113,6 +135,8 @@ const ClipboardIcon = { template: '<svg xmlns="http://www.w3.org/2000/svg" fill=
|
||||
|
||||
const classesStore = useClassesStore()
|
||||
const loading = ref(true)
|
||||
const showDeleteModal = ref(false)
|
||||
const classToDelete = ref(null)
|
||||
|
||||
const classes = computed(() => classesStore.classes)
|
||||
const totalStudents = computed(() => classesStore.totalStudents)
|
||||
@@ -153,9 +177,16 @@ function getAccentBgClass(className) {
|
||||
|
||||
// Confirmation de suppression
|
||||
function confirmDelete(cls) {
|
||||
if (confirm(`Êtes-vous sûr de vouloir supprimer la classe "${cls.name}" ?`)) {
|
||||
classesStore.deleteClass(cls.id)
|
||||
classToDelete.value = cls
|
||||
showDeleteModal.value = true
|
||||
}
|
||||
|
||||
function executeDelete() {
|
||||
if (classToDelete.value) {
|
||||
classesStore.deleteClass(classToDelete.value.id)
|
||||
}
|
||||
showDeleteModal.value = false
|
||||
classToDelete.value = null
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -63,10 +63,10 @@ import ConfigEmailTab from '@/components/config/ConfigEmailTab.vue'
|
||||
const configStore = useConfigStore()
|
||||
|
||||
const tabs = [
|
||||
{ id: 'general', label: 'General' },
|
||||
{ id: 'competences', label: 'Competences' },
|
||||
{ id: 'general', label: 'Général' },
|
||||
{ id: 'competences', label: 'Compétences' },
|
||||
{ id: 'domains', label: 'Domaines' },
|
||||
{ id: 'scale', label: 'Echelle' },
|
||||
{ id: 'scale', label: 'Échelle' },
|
||||
{ id: 'email', label: 'Email' }
|
||||
]
|
||||
|
||||
|
||||
@@ -66,14 +66,14 @@
|
||||
@next="navigateStudent(1)"
|
||||
/>
|
||||
<div v-else class="bg-white rounded-xl shadow-md p-12 text-center">
|
||||
<p class="text-gray-400">Selectionnez un eleve dans la liste</p>
|
||||
<p class="text-gray-400">Sélectionnez un élève dans la liste</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Empty state -->
|
||||
<div v-else-if="currentStats" class="flex-1 flex items-center justify-center">
|
||||
<p class="text-gray-500">Aucune donnee disponible pour le trimestre {{ trimester }}</p>
|
||||
<p class="text-gray-500">Aucune donnée disponible pour le trimestre {{ trimester }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -57,9 +57,12 @@
|
||||
</div>
|
||||
</router-link>
|
||||
|
||||
<div class="card card-body">
|
||||
<router-link
|
||||
to="/assessments"
|
||||
class="card card-body hover:shadow-md transition-shadow group"
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<div class="p-3 rounded-lg bg-danger-100 text-danger-600">
|
||||
<div class="p-3 rounded-lg bg-danger-100 text-danger-600 group-hover:bg-danger-200 transition-colors">
|
||||
<PencilIcon class="w-6 h-6" />
|
||||
</div>
|
||||
<div class="ml-4">
|
||||
@@ -67,7 +70,7 @@
|
||||
<p class="text-2xl font-bold">{{ assessmentsStore.incompleteAssessments.length }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<!-- Quick actions -->
|
||||
|
||||
@@ -314,8 +314,8 @@
|
||||
</div>
|
||||
<div class="flex space-x-3">
|
||||
<button
|
||||
@click="resetForm"
|
||||
class="px-3 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50 transition-colors"
|
||||
@click="showResetModal = true"
|
||||
class="px-3 py-1 text-xs border border-red-200 rounded bg-red-50 text-red-600 hover:bg-red-100 transition-colors"
|
||||
>
|
||||
Réinitialiser
|
||||
</button>
|
||||
@@ -396,26 +396,66 @@
|
||||
</template>
|
||||
</Modal>
|
||||
|
||||
<!-- Toast -->
|
||||
<Transition name="toast">
|
||||
<div
|
||||
v-if="toast.show"
|
||||
class="fixed bottom-4 right-4 z-50"
|
||||
>
|
||||
<div
|
||||
class="px-4 py-3 rounded-lg shadow-lg flex items-center"
|
||||
:class="toastClass"
|
||||
>
|
||||
<svg v-if="toast.type === 'success'" class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
<svg v-else-if="toast.type === 'error'" class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
<span>{{ toast.message }}</span>
|
||||
<!-- Modal réinitialisation -->
|
||||
<Modal v-model="showResetModal" title="Réinitialiser les notes" size="sm">
|
||||
<p class="text-gray-600">
|
||||
Réinitialiser toutes les notes ? Cette action est irréversible.
|
||||
</p>
|
||||
<template #footer>
|
||||
<div class="flex justify-end space-x-3">
|
||||
<button
|
||||
@click="showResetModal = false"
|
||||
class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
<button
|
||||
@click="resetForm"
|
||||
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700"
|
||||
>
|
||||
Réinitialiser
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</Modal>
|
||||
|
||||
<!-- Modal erreurs de validation -->
|
||||
<Modal v-model="showErrorsModal" title="Valeurs invalides" size="md">
|
||||
<p class="text-gray-600 mb-3">
|
||||
{{ invalidEntries.length }} valeur(s) invalide(s) n'ont pas été sauvegardées :
|
||||
</p>
|
||||
<div class="max-h-60 overflow-y-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500">Élève</th>
|
||||
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500">Élément</th>
|
||||
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500">Valeur</th>
|
||||
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500">Erreur</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200">
|
||||
<tr v-for="(entry, idx) in invalidEntries" :key="idx">
|
||||
<td class="px-3 py-2 text-gray-900">{{ entry.studentName }}</td>
|
||||
<td class="px-3 py-2 text-gray-700">{{ entry.elementLabel }}</td>
|
||||
<td class="px-3 py-2 font-mono text-red-600">{{ entry.value }}</td>
|
||||
<td class="px-3 py-2 text-red-500 text-xs">{{ entry.error }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Transition>
|
||||
<template #footer>
|
||||
<div class="flex justify-end">
|
||||
<button
|
||||
@click="showErrorsModal = false"
|
||||
class="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-md hover:bg-primary-700"
|
||||
>
|
||||
Compris
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</Modal>
|
||||
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -425,6 +465,7 @@ import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useAssessmentsStore } from '@/stores/assessments'
|
||||
import { useConfigStore } from '@/stores/config'
|
||||
import { useNotificationsStore } from '@/stores/notifications'
|
||||
import classesService from '@/services/classes'
|
||||
import assessmentsService from '@/services/assessments'
|
||||
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
|
||||
@@ -434,6 +475,7 @@ const route = useRoute()
|
||||
const router = useRouter()
|
||||
const assessmentsStore = useAssessmentsStore()
|
||||
const configStore = useConfigStore()
|
||||
const notifications = useNotificationsStore()
|
||||
|
||||
// Color interpolation functions
|
||||
function hexToRgb(hex) {
|
||||
@@ -527,13 +569,14 @@ const studentFilter = ref('')
|
||||
const filterFocused = ref(false)
|
||||
const showKeyboardHelp = ref(false)
|
||||
const showQuickComplete = ref(false)
|
||||
const showResetModal = ref(false)
|
||||
const showErrorsModal = ref(false)
|
||||
const invalidEntries = ref([])
|
||||
const quickCompleteStudentId = ref(null)
|
||||
const quickCompleteValue = ref('.')
|
||||
const quickCompleteOverwrite = ref(false)
|
||||
const currentPosition = ref(null)
|
||||
|
||||
// Toast
|
||||
const toast = ref({ show: false, message: '', type: 'success' })
|
||||
|
||||
// Computed
|
||||
const allElements = computed(() => {
|
||||
@@ -597,15 +640,6 @@ const progressColorClass = computed(() => {
|
||||
|
||||
const hasUnsavedChanges = computed(() => unsavedChanges.value.size > 0)
|
||||
|
||||
const toastClass = computed(() => {
|
||||
const classes = {
|
||||
success: 'bg-green-500 text-white',
|
||||
error: 'bg-red-500 text-white',
|
||||
info: 'bg-blue-500 text-white',
|
||||
warning: 'bg-orange-500 text-white'
|
||||
}
|
||||
return classes[toast.value.type] || classes.info
|
||||
})
|
||||
|
||||
// Options d'échelle depuis la config
|
||||
const scaleOptions = computed(() => {
|
||||
@@ -1091,7 +1125,7 @@ async function saveAll() {
|
||||
saving.value = true
|
||||
try {
|
||||
const gradesArray = []
|
||||
const errors = []
|
||||
const collectedErrors = []
|
||||
|
||||
for (const key in grades.value) {
|
||||
const [studentId, elementId] = key.split('_').map(Number)
|
||||
@@ -1104,7 +1138,12 @@ async function saveAll() {
|
||||
const validation = validateGradeValue(value, element.grading_type, element.max_points)
|
||||
if (!validation.valid) {
|
||||
const student = students.value.find(s => s.id === studentId)
|
||||
errors.push(`${student?.last_name || 'Élève'} - ${element.label || element.name}: ${validation.error}`)
|
||||
collectedErrors.push({
|
||||
studentName: `${student?.last_name || 'Élève'} ${student?.first_name || ''}`.trim(),
|
||||
elementLabel: element.label || element.name,
|
||||
value: value,
|
||||
error: validation.error
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -1117,16 +1156,16 @@ async function saveAll() {
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
showToast(`${errors.length} valeur(s) invalide(s) ignorée(s)`, 'warning')
|
||||
console.warn('Erreurs de validation:', errors)
|
||||
if (collectedErrors.length > 0) {
|
||||
invalidEntries.value = collectedErrors
|
||||
showErrorsModal.value = true
|
||||
}
|
||||
|
||||
if (gradesArray.length > 0) {
|
||||
await assessmentsStore.saveGrades(assessment.value.id, gradesArray)
|
||||
unsavedChanges.value.clear()
|
||||
showToast('Notes sauvegardées avec succès', 'success')
|
||||
} else if (errors.length === 0) {
|
||||
} else if (collectedErrors.length === 0) {
|
||||
showToast('Aucune note à sauvegarder', 'info')
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -1137,22 +1176,17 @@ async function saveAll() {
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
if (!confirm('Êtes-vous sûr de vouloir réinitialiser toutes les notes ? Cette action est irréversible.')) {
|
||||
return
|
||||
}
|
||||
|
||||
grades.value = {}
|
||||
unsavedChanges.value.clear()
|
||||
undoStack.value = []
|
||||
showResetModal.value = false
|
||||
showToast('Formulaire réinitialisé', 'info')
|
||||
}
|
||||
|
||||
// Toast
|
||||
// Notification helper
|
||||
function showToast(message, type = 'success') {
|
||||
toast.value = { show: true, message, type }
|
||||
setTimeout(() => {
|
||||
toast.value.show = false
|
||||
}, 3000)
|
||||
const fn = { success: 'success', error: 'error', warning: 'warning', info: 'info' }
|
||||
notifications[fn[type] || 'info'](message)
|
||||
}
|
||||
|
||||
// Protection fermeture
|
||||
@@ -1229,14 +1263,4 @@ onUnmounted(() => {
|
||||
transform: translateX(20px);
|
||||
}
|
||||
|
||||
.toast-enter-active,
|
||||
.toast-leave-active {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.toast-enter-from,
|
||||
.toast-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -202,80 +202,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toolbar de sélection (mode sélection activé) -->
|
||||
<div v-if="selectionMode && gradedStudentsWithEmail.length > 0" class="card mb-6 border-2 border-blue-500 bg-blue-50">
|
||||
<div class="card-body">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h3 class="font-semibold text-blue-900">Mode Sélection Activé</h3>
|
||||
<p class="text-sm text-blue-700">
|
||||
Cliquez sur les cases pour sélectionner les élèves qui recevront leur bilan
|
||||
<span v-if="selectedStudents.length > 0" class="font-semibold">
|
||||
({{ selectedStudents.length }} sélectionné{{selectedStudents.length > 1 ? 's' : ''}})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
@click="toggleSelectAll"
|
||||
class="btn btn-sm btn-secondary"
|
||||
>
|
||||
{{ allSelected ? 'Tout désélectionner' : 'Tout sélectionner' }}
|
||||
</button>
|
||||
<button
|
||||
@click="cancelSelectionMode"
|
||||
class="btn btn-sm btn-secondary"
|
||||
>
|
||||
<svg class="w-4 h-4 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
Annuler
|
||||
</button>
|
||||
<button
|
||||
@click="openSendModal"
|
||||
:disabled="selectedStudents.length === 0"
|
||||
class="btn btn-primary shadow-lg"
|
||||
:class="{ 'opacity-50 cursor-not-allowed': selectedStudents.length === 0 }"
|
||||
>
|
||||
<svg class="w-5 h-5 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||
</svg>
|
||||
Envoyer à {{ selectedStudents.length }} élève{{selectedStudents.length > 1 ? 's' : ''}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Student scores table -->
|
||||
<div class="card">
|
||||
<div class="card-header flex justify-between items-center">
|
||||
<h2 class="text-lg font-semibold">Détail par élève</h2>
|
||||
|
||||
<!-- Mode Normal : Bouton pour activer la sélection -->
|
||||
<button
|
||||
v-if="!selectionMode && gradedStudentsWithEmail.length > 0"
|
||||
@click="activateSelectionMode"
|
||||
class="btn btn-primary"
|
||||
v-if="gradedStudentsWithEmail.length > 0"
|
||||
@click="toggleSelectAll"
|
||||
class="btn btn-sm btn-secondary"
|
||||
>
|
||||
<svg class="w-5 h-5 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||
</svg>
|
||||
📧 Envoyer des bilans
|
||||
{{ allSelected ? 'Tout désélectionner' : 'Tout sélectionner' }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-if="selectionMode && gradedStudentsWithEmail.length > 0" class="w-16">
|
||||
<th v-if="gradedStudentsWithEmail.length > 0" class="w-16">
|
||||
<div class="flex items-center gap-1">
|
||||
<svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
@@ -295,10 +239,10 @@
|
||||
:key="student.student_id"
|
||||
:class="{
|
||||
'bg-gray-50 opacity-60': !isStudentGraded(student),
|
||||
'bg-blue-50 border-l-4 border-blue-500': selectionMode && isSelected(student.student_id)
|
||||
'bg-blue-50 border-l-4 border-blue-500': isSelected(student.student_id)
|
||||
}"
|
||||
>
|
||||
<td v-if="selectionMode && gradedStudentsWithEmail.length > 0" class="w-16">
|
||||
<td v-if="gradedStudentsWithEmail.length > 0" class="w-16">
|
||||
<input
|
||||
v-if="isStudentGraded(student) && student.email"
|
||||
type="checkbox"
|
||||
@@ -379,6 +323,31 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Sticky bottom bar for sending emails -->
|
||||
<Transition name="slide-up">
|
||||
<div
|
||||
v-if="selectedStudents.length > 0"
|
||||
class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-40 px-6 py-3"
|
||||
>
|
||||
<div class="max-w-7xl mx-auto flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-sm text-gray-600">
|
||||
<strong>{{ selectedStudents.length }}</strong> élève{{ selectedStudents.length > 1 ? 's' : '' }} sélectionné{{ selectedStudents.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
<button @click="selectedStudents = []" class="text-sm text-gray-500 hover:text-gray-700">
|
||||
Effacer
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
@click="openSendModal"
|
||||
class="btn btn-primary"
|
||||
>
|
||||
Envoyer les bilans à {{ selectedStudents.length }} élève{{ selectedStudents.length > 1 ? 's' : '' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<!-- Modal d'envoi de bilans -->
|
||||
<SendReportsModal
|
||||
v-if="showSendModal"
|
||||
@@ -409,7 +378,6 @@ const configStore = useConfigStore()
|
||||
// État pour la sélection d'élèves et l'envoi d'emails
|
||||
const selectedStudents = ref([])
|
||||
const showSendModal = ref(false)
|
||||
const selectionMode = ref(false) // Mode sélection activé/désactivé
|
||||
|
||||
// Color interpolation functions
|
||||
function hexToRgb(hex) {
|
||||
@@ -735,23 +703,6 @@ const selectedStudentsData = computed(() => {
|
||||
}))
|
||||
})
|
||||
|
||||
// Activer le mode sélection
|
||||
function activateSelectionMode() {
|
||||
selectionMode.value = true
|
||||
selectedStudents.value = [] // Réinitialiser la sélection
|
||||
}
|
||||
|
||||
// Annuler le mode sélection
|
||||
function cancelSelectionMode() {
|
||||
selectionMode.value = false
|
||||
selectedStudents.value = []
|
||||
}
|
||||
|
||||
// Vider la sélection
|
||||
function clearSelection() {
|
||||
selectedStudents.value = []
|
||||
}
|
||||
|
||||
// Vérifier si un élève est sélectionné
|
||||
function isSelected(studentId) {
|
||||
return selectedStudents.value.includes(studentId)
|
||||
@@ -776,7 +727,6 @@ function openSendModal() {
|
||||
function handleReportsSent(result) {
|
||||
showSendModal.value = false
|
||||
selectedStudents.value = []
|
||||
selectionMode.value = false // Désactiver le mode sélection après envoi
|
||||
// Le modal affiche déjà les résultats, pas besoin de notification supplémentaire
|
||||
}
|
||||
|
||||
@@ -801,3 +751,14 @@ onMounted(async () => {
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.slide-up-enter-active,
|
||||
.slide-up-leave-active {
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
.slide-up-enter-from,
|
||||
.slide-up-leave-to {
|
||||
transform: translateY(100%);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -35,7 +35,12 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200">
|
||||
<tr v-for="student in students" :key="student.id">
|
||||
<tr
|
||||
v-for="student in students"
|
||||
:key="student.id"
|
||||
:class="student.current_class_id ? 'hover:bg-gray-50 cursor-pointer' : ''"
|
||||
@click="student.current_class_id && $router.push(`/classes/${student.current_class_id}/students`)"
|
||||
>
|
||||
<td class="font-medium">{{ student.last_name }}</td>
|
||||
<td>{{ student.first_name }}</td>
|
||||
<td>
|
||||
|
||||
Reference in New Issue
Block a user