forked from ScoDoc/DocScoDoc
249 lines
8.7 KiB
Python
249 lines
8.7 KiB
Python
# -*- coding: UTF-8 -*
|
|
|
|
"""ScoDoc models: evaluations
|
|
"""
|
|
import datetime
|
|
|
|
from app import db
|
|
from app.models.moduleimpls import ModuleImpl
|
|
from app.models.ues import UniteEns
|
|
|
|
from app.scodoc.sco_exceptions import ScoValueError
|
|
import app.scodoc.notesdb as ndb
|
|
|
|
|
|
class Evaluation(db.Model):
|
|
"""Evaluation (contrôle, examen, ...)"""
|
|
|
|
__tablename__ = "notes_evaluation"
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
evaluation_id = db.synonym("id")
|
|
moduleimpl_id = db.Column(
|
|
db.Integer, db.ForeignKey("notes_moduleimpl.id"), index=True
|
|
)
|
|
jour = db.Column(db.Date)
|
|
heure_debut = db.Column(db.Time)
|
|
heure_fin = db.Column(db.Time)
|
|
description = db.Column(db.Text)
|
|
note_max = db.Column(db.Float)
|
|
coefficient = db.Column(db.Float)
|
|
visibulletin = db.Column(
|
|
db.Boolean, nullable=False, default=True, server_default="true"
|
|
)
|
|
publish_incomplete = db.Column(
|
|
db.Boolean, nullable=False, default=False, server_default="false"
|
|
)
|
|
# type d'evaluation: 0 normale, 1 rattrapage, 2 "2eme session"
|
|
evaluation_type = db.Column(
|
|
db.Integer, nullable=False, default=0, server_default="0"
|
|
)
|
|
# ordre de presentation (par défaut, le plus petit numero
|
|
# est la plus ancienne eval):
|
|
numero = db.Column(db.Integer)
|
|
ues = db.relationship("UniteEns", secondary="evaluation_ue_poids", viewonly=True)
|
|
|
|
def __repr__(self):
|
|
return f"""<Evaluation {self.id} {self.jour.isoformat() if self.jour else ''} "{self.description[:16] if self.description else ''}">"""
|
|
|
|
def to_dict(self) -> dict:
|
|
"Représentation dict, pour json"
|
|
e = dict(self.__dict__)
|
|
e.pop("_sa_instance_state", None)
|
|
# ScoDoc7 output_formators
|
|
e["evaluation_id"] = self.id
|
|
e["jour"] = e["jour"].strftime("%d/%m/%Y") if e["jour"] else ""
|
|
if self.jour is None:
|
|
e["date_debut"] = None
|
|
e["date_fin"] = None
|
|
else:
|
|
e["date_debut"] = datetime.datetime.combine(
|
|
self.jour, self.heure_debut or datetime.time(0, 0)
|
|
).isoformat()
|
|
e["date_fin"] = datetime.datetime.combine(
|
|
self.jour, self.heure_fin or datetime.time(0, 0)
|
|
).isoformat()
|
|
e["numero"] = ndb.int_null_is_zero(e["numero"])
|
|
e["poids"] = self.get_ue_poids_dict() # { ue_id : poids }
|
|
return evaluation_enrich_dict(e)
|
|
|
|
def from_dict(self, data):
|
|
"""Set evaluation attributes from given dict values."""
|
|
check_evaluation_args(data)
|
|
for k in self.__dict__.keys():
|
|
if k != "_sa_instance_state" and k != "id" and k in data:
|
|
setattr(self, k, data[k])
|
|
|
|
def clone(self, not_copying=()):
|
|
"""Clone, not copying the given attrs
|
|
Attention: la copie n'a pas d'id avant le prochain commit
|
|
"""
|
|
d = dict(self.__dict__)
|
|
d.pop("id") # get rid of id
|
|
d.pop("_sa_instance_state") # get rid of SQLAlchemy special attr
|
|
for k in not_copying:
|
|
d.pop(k)
|
|
copy = self.__class__(**d)
|
|
db.session.add(copy)
|
|
return copy
|
|
|
|
def set_ue_poids(self, ue, poids: float) -> None:
|
|
"""Set poids évaluation vers cette UE"""
|
|
self.update_ue_poids_dict({ue.id: poids})
|
|
|
|
def set_ue_poids_dict(self, ue_poids_dict: dict) -> None:
|
|
"""set poids vers les UE (remplace existants)
|
|
ue_poids_dict = { ue_id : poids }
|
|
"""
|
|
L = []
|
|
for ue_id, poids in ue_poids_dict.items():
|
|
ue = UniteEns.query.get(ue_id)
|
|
L.append(EvaluationUEPoids(evaluation=self, ue=ue, poids=poids))
|
|
self.ue_poids = L
|
|
self.moduleimpl.invalidate_evaluations_poids() # inval cache
|
|
|
|
def update_ue_poids_dict(self, ue_poids_dict: dict) -> None:
|
|
"""update poids vers UE (ajoute aux existants)"""
|
|
current = self.get_ue_poids_dict()
|
|
current.update(ue_poids_dict)
|
|
self.set_ue_poids_dict(current)
|
|
|
|
def get_ue_poids_dict(self) -> dict:
|
|
"""returns { ue_id : poids }"""
|
|
return {p.ue.id: p.poids for p in self.ue_poids}
|
|
|
|
def get_ue_poids_str(self) -> str:
|
|
"""string describing poids, for excel cells and pdfs
|
|
Note: si les poids ne sont pas initialisés (poids par défaut),
|
|
ils ne sont pas affichés.
|
|
"""
|
|
# restreint aux UE du semestre dans lequel est cette évaluation
|
|
# au cas où le module ait changé de semestre et qu'il reste des poids
|
|
evaluation_semestre_idx = self.moduleimpl.module.semestre_id
|
|
return ", ".join(
|
|
[
|
|
f"{p.ue.acronyme}: {p.poids}"
|
|
for p in self.ue_poids
|
|
if evaluation_semestre_idx == p.ue.semestre_idx
|
|
]
|
|
)
|
|
|
|
|
|
class EvaluationUEPoids(db.Model):
|
|
"""Poids des évaluations (BUT)
|
|
association many to many
|
|
"""
|
|
|
|
evaluation_id = db.Column(
|
|
db.Integer,
|
|
db.ForeignKey("notes_evaluation.id", ondelete="CASCADE"),
|
|
primary_key=True,
|
|
)
|
|
ue_id = db.Column(
|
|
db.Integer,
|
|
db.ForeignKey("notes_ue.id", ondelete="CASCADE"),
|
|
primary_key=True,
|
|
)
|
|
poids = db.Column(
|
|
db.Float,
|
|
nullable=False,
|
|
)
|
|
evaluation = db.relationship(
|
|
Evaluation,
|
|
backref=db.backref("ue_poids", cascade="all, delete-orphan"),
|
|
)
|
|
ue = db.relationship(
|
|
UniteEns,
|
|
backref=db.backref("evaluation_ue_poids", cascade="all, delete-orphan"),
|
|
)
|
|
|
|
def __repr__(self):
|
|
return f"<EvaluationUEPoids {self.evaluation} {self.ue} poids={self.poids}>"
|
|
|
|
|
|
# Fonction héritée de ScoDoc7 à refactorer
|
|
def evaluation_enrich_dict(e):
|
|
"""add or convert some fields in an evaluation dict"""
|
|
# For ScoDoc7 compat
|
|
heure_debut_dt = e["heure_debut"] or datetime.time(
|
|
8, 00
|
|
) # au cas ou pas d'heure (note externe?)
|
|
heure_fin_dt = e["heure_fin"] or datetime.time(8, 00)
|
|
e["heure_debut"] = ndb.TimefromISO8601(e["heure_debut"])
|
|
e["heure_fin"] = ndb.TimefromISO8601(e["heure_fin"])
|
|
e["jouriso"] = ndb.DateDMYtoISO(e["jour"])
|
|
heure_debut, heure_fin = e["heure_debut"], e["heure_fin"]
|
|
d = ndb.TimeDuration(heure_debut, heure_fin)
|
|
if d is not None:
|
|
m = d % 60
|
|
e["duree"] = "%dh" % (d / 60)
|
|
if m != 0:
|
|
e["duree"] += "%02d" % m
|
|
else:
|
|
e["duree"] = ""
|
|
if heure_debut and (not heure_fin or heure_fin == heure_debut):
|
|
e["descrheure"] = " à " + heure_debut
|
|
elif heure_debut and heure_fin:
|
|
e["descrheure"] = " de %s à %s" % (heure_debut, heure_fin)
|
|
else:
|
|
e["descrheure"] = ""
|
|
# matin, apresmidi: utile pour se referer aux absences:
|
|
|
|
if e["jour"] and heure_debut_dt < datetime.time(12, 00):
|
|
e["matin"] = 1
|
|
else:
|
|
e["matin"] = 0
|
|
if e["jour"] and heure_fin_dt > datetime.time(12, 00):
|
|
e["apresmidi"] = 1
|
|
else:
|
|
e["apresmidi"] = 0
|
|
return e
|
|
|
|
|
|
def check_evaluation_args(args):
|
|
"Check coefficient, dates and duration, raises exception if invalid"
|
|
moduleimpl_id = args["moduleimpl_id"]
|
|
# check bareme
|
|
note_max = args.get("note_max", None)
|
|
if note_max is None:
|
|
raise ScoValueError("missing note_max")
|
|
try:
|
|
note_max = float(note_max)
|
|
except ValueError:
|
|
raise ScoValueError("Invalid note_max value")
|
|
if note_max < 0:
|
|
raise ScoValueError("Invalid note_max value (must be positive or null)")
|
|
# check coefficient
|
|
coef = args.get("coefficient", None)
|
|
if coef is None:
|
|
raise ScoValueError("missing coefficient")
|
|
try:
|
|
coef = float(coef)
|
|
except ValueError:
|
|
raise ScoValueError("Invalid coefficient value")
|
|
if coef < 0:
|
|
raise ScoValueError("Invalid coefficient value (must be positive or null)")
|
|
# check date
|
|
jour = args.get("jour", None)
|
|
args["jour"] = jour
|
|
if jour:
|
|
modimpl = ModuleImpl.query.get(moduleimpl_id)
|
|
formsemestre = modimpl.formsemestre
|
|
y, m, d = [int(x) for x in ndb.DateDMYtoISO(jour).split("-")]
|
|
jour = datetime.date(y, m, d)
|
|
if (jour > formsemestre.date_fin) or (jour < formsemestre.date_debut):
|
|
raise ScoValueError(
|
|
"La date de l'évaluation (%s/%s/%s) n'est pas dans le semestre !"
|
|
% (d, m, y),
|
|
dest_url="javascript:history.back();",
|
|
)
|
|
heure_debut = args.get("heure_debut", None)
|
|
args["heure_debut"] = heure_debut
|
|
heure_fin = args.get("heure_fin", None)
|
|
args["heure_fin"] = heure_fin
|
|
if jour and ((not heure_debut) or (not heure_fin)):
|
|
raise ScoValueError("Les heures doivent être précisées")
|
|
d = ndb.TimeDuration(heure_debut, heure_fin)
|
|
if d and ((d < 0) or (d > 60 * 12)):
|
|
raise ScoValueError("Heures de l'évaluation incohérentes !")
|