feat: Sauvegarde des compétences d'un élève [#16]

This commit is contained in:
N3WT DE COMPET
2025-05-20 17:31:50 +02:00
parent c9c7e7715e
commit 05136035ab
19 changed files with 269 additions and 137 deletions

View File

@ -324,15 +324,19 @@ class RegistrationSchoolFileTemplate(models.Model):
class StudentCompetency(models.Model):
student = models.ForeignKey('Subscriptions.Student', on_delete=models.CASCADE, related_name='competency_scores')
competency = models.ForeignKey('Common.Competency', on_delete=models.CASCADE, related_name='student_scores')
establishment_competency = models.ForeignKey('School.EstablishmentCompetency', on_delete=models.CASCADE, related_name='student_scores')
score = models.IntegerField(null=True, blank=True)
comment = models.TextField(blank=True, null=True)
class Meta:
unique_together = ('student', 'competency')
unique_together = ('student', 'establishment_competency')
indexes = [
models.Index(fields=['student', 'establishment_competency']),
]
def __str__(self):
return f"{self.student} - {self.competency.name} - Score: {self.score}"
return f"{self.student} - {self.establishment_competency} - Score: {self.score}"
####### Parent files templates (par dossier d'inscription) #######
class RegistrationParentFileTemplate(models.Model):

View File

@ -17,7 +17,6 @@ import Subscriptions.util as util
from Subscriptions.serializers import RegistrationFormSerializer, RegistrationSchoolFileTemplateSerializer, RegistrationParentFileTemplateSerializer
from Subscriptions.pagination import CustomSubscriptionPagination
from Subscriptions.models import (
Student,
Guardian,
RegistrationForm,
RegistrationSchoolFileTemplate,
@ -26,7 +25,7 @@ from Subscriptions.models import (
StudentCompetency
)
from Subscriptions.automate import updateStateMachine
from Common.models import Competency
from School.models import EstablishmentCompetency
from N3wtSchool import settings, bdd
from django.db.models import Q
@ -246,6 +245,7 @@ class RegisterFormWithIdView(APIView):
"""
studentForm_data = request.data.get('data', '{}')
try:
data = json.loads(studentForm_data)
except json.JSONDecodeError:
@ -306,13 +306,13 @@ class RegisterFormWithIdView(APIView):
# L'école doit désormais valider le dossier d'inscription
try:
# Génération de la fiche d'inscription au format PDF
base_dir = os.path.join(settings.MEDIA_ROOT, f"registration_files/dossier_rf_{registerForm.pk}")
os.makedirs(base_dir, exist_ok=True)
# base_dir = os.path.join(settings.MEDIA_ROOT, f"registration_files/dossier_rf_{registerForm.pk}")
# os.makedirs(base_dir, exist_ok=True)
# Fichier PDF initial
initial_pdf = f"{base_dir}/Inscription_{registerForm.student.last_name}_{registerForm.student.first_name}.pdf"
registerForm.registration_file = util.rfToPDF(registerForm, initial_pdf)
registerForm.save()
# # Fichier PDF initial
# initial_pdf = f"{base_dir}/Inscription_{registerForm.student.last_name}_{registerForm.student.first_name}.pdf"
# registerForm.registration_file = util.rfToPDF(registerForm, initial_pdf)
# registerForm.save()
# Mise à jour de l'automate
# Vérification de la présence du fichier SEPA
@ -376,7 +376,6 @@ class RegisterFormWithIdView(APIView):
File(merged_pdf_content),
save=True
)
# Valorisation des StudentCompetency pour l'élève
try:
student = registerForm.student
@ -384,15 +383,19 @@ class RegisterFormWithIdView(APIView):
if student.level:
cycle = student.level.cycle.number
if cycle:
competencies = Competency.objects.filter(
category__domain__cycle=cycle
).filter(
Q(end_of_cycle=True) | Q(level=student.level.name)
# Récupérer les EstablishmentCompetency de l'établissement et du cycle de l'élève
establishment_competencies = EstablishmentCompetency.objects.filter(
establishment=registerForm.establishment,
custom_category__domain__cycle=cycle
) | EstablishmentCompetency.objects.filter(
establishment=registerForm.establishment,
competency__category__domain__cycle=cycle
)
for comp in competencies:
establishment_competencies = establishment_competencies.distinct()
for ec in establishment_competencies:
StudentCompetency.objects.get_or_create(
student=student,
competency=comp
establishment_competency=ec
)
except Exception as e:
logger.error(f"Erreur lors de la valorisation des StudentCompetency: {e}")

View File

@ -6,7 +6,8 @@ from drf_yasg import openapi
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect
from django.utils.decorators import method_decorator
from Subscriptions.models import StudentCompetency, Student
from Common.models import Domain, Competency
from Common.models import Domain
from School.models import Competency
from N3wtSchool.bdd import delete_object
@method_decorator(csrf_protect, name='dispatch')
@ -21,10 +22,14 @@ class StudentCompetencyListCreateView(APIView):
except Student.DoesNotExist:
return JsonResponse({'error': 'Élève introuvable'}, status=404)
student_competencies = StudentCompetency.objects.filter(student=student).select_related('competency', 'competency__category', 'competency__category__domain')
# On ne garde que les IDs des compétences de l'élève
student_competency_ids = set(sc.competency_id for sc in student_competencies)
student_competencies = StudentCompetency.objects.filter(student=student).select_related(
'establishment_competency',
'establishment_competency__competency',
'establishment_competency__competency__category',
'establishment_competency__competency__category__domain',
'establishment_competency__custom_category',
'establishment_competency__custom_category__domain',
)
result = []
total_competencies = 0
@ -44,15 +49,26 @@ class StudentCompetencyListCreateView(APIView):
}
# On ne boucle que sur les compétences du student pour cette catégorie
for sc in student_competencies:
comp = sc.competency
if comp.category_id == categorie.id:
ec = sc.establishment_competency
# Cas compétence de référence
if ec.competency and ec.competency.category_id == categorie.id:
comp = ec.competency
categorie_dict["competences"].append({
"competence_id": comp.id,
"competence_id": ec.id, # <-- retourne l'id de l'EstablishmentCompetency
"nom": comp.name,
"score": sc.score,
"comment": sc.comment or "",
})
total_competencies += 1
# Cas compétence custom
elif ec.competency is None and ec.custom_category_id == categorie.id:
categorie_dict["competences"].append({
"competence_id": ec.id, # <-- retourne l'id de l'EstablishmentCompetency
"nom": ec.custom_name,
"score": sc.score,
"comment": sc.comment or "",
})
total_competencies += 1
if categorie_dict["competences"]:
domaine_dict["categories"].append(categorie_dict)
if domaine_dict["categories"]:
@ -77,14 +93,13 @@ class StudentCompetencyListCreateView(APIView):
comp_id = item.get("competenceId")
grade = item.get("grade")
student_id = item.get('studentId')
print(f'lecture des données : {comp_id} - {grade} - {student_id}')
if comp_id is None or grade is None:
errors.append({"competenceId": comp_id, "error": "champ manquant"})
continue
try:
# Ajoute le filtre student_id
sc = StudentCompetency.objects.get(
competency_id=comp_id,
establishment_competency_id=comp_id,
student_id=student_id
)
sc.score = grade