forked from ScoDoc/ScoDoc
commit
d71ea6d34f
|
@ -169,5 +169,7 @@ Thumbs.db
|
|||
.vscode/
|
||||
*.code-workspace
|
||||
|
||||
# PyCharm
|
||||
.idea/
|
||||
|
||||
copy
|
||||
|
|
15
README.md
15
README.md
|
@ -18,12 +18,12 @@ Flask, SQLAlchemy, au lien de Python2/Zope dans les versions précédentes).
|
|||
|
||||
|
||||
|
||||
### État actuel (4 dec 21)
|
||||
### État actuel (26 jan 22)
|
||||
|
||||
- 9.0 (master) reproduit l'ensemble des fonctions de ScoDoc 7 (donc pas de BUT), sauf:
|
||||
- ancien module "Entreprises" (obsolète)
|
||||
- 9.1.5x (master) reproduit l'ensemble des fonctions de ScoDoc 7 (donc pas de BUT), sauf:
|
||||
- ancien module "Entreprises" (obsolète) et ajoute la gestion du BUT.
|
||||
|
||||
- 9.1 (branche "PNBUT") est la version de développement.
|
||||
- 9.2 (branche dev92) est la version de développement.
|
||||
|
||||
|
||||
### Lignes de commandes
|
||||
|
@ -69,7 +69,12 @@ Puis remplacer `/opt/scodoc` par un clone du git.
|
|||
cd /opt
|
||||
git clone https://scodoc.org/git/viennet/ScoDoc.git
|
||||
# (ou bien utiliser votre clone gitea si vous l'avez déjà créé !)
|
||||
mv ScoDoc scodoc # important !
|
||||
|
||||
# Renommer le répertoire:
|
||||
mv ScoDoc scodoc
|
||||
|
||||
# Et donner ce répertoire à l'utilisateur scodoc:
|
||||
chown -R scodoc.scodoc /opt/scodoc
|
||||
|
||||
Il faut ensuite installer l'environnement et le fichier de configuration:
|
||||
|
||||
|
|
|
@ -10,10 +10,11 @@ import traceback
|
|||
|
||||
import logging
|
||||
from logging.handlers import SMTPHandler, WatchedFileHandler
|
||||
from threading import Thread
|
||||
|
||||
from flask import current_app, g, request
|
||||
from flask import Flask
|
||||
from flask import abort, has_request_context, jsonify
|
||||
from flask import abort, flash, has_request_context, jsonify
|
||||
from flask import render_template
|
||||
from flask.logging import default_handler
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
@ -27,6 +28,7 @@ import sqlalchemy
|
|||
|
||||
from app.scodoc.sco_exceptions import (
|
||||
AccessDenied,
|
||||
ScoBugCatcher,
|
||||
ScoGenError,
|
||||
ScoValueError,
|
||||
APIInvalidParams,
|
||||
|
@ -43,11 +45,13 @@ mail = Mail()
|
|||
bootstrap = Bootstrap()
|
||||
moment = Moment()
|
||||
|
||||
cache = Cache( # XXX TODO: configuration file
|
||||
CACHE_TYPE = os.environ.get("CACHE_TYPE")
|
||||
cache = Cache(
|
||||
config={
|
||||
# see https://flask-caching.readthedocs.io/en/latest/index.html#configuring-flask-caching
|
||||
"CACHE_TYPE": "RedisCache",
|
||||
"CACHE_DEFAULT_TIMEOUT": 0, # by default, never expire
|
||||
"CACHE_TYPE": CACHE_TYPE or "RedisCache",
|
||||
# by default, never expire:
|
||||
"CACHE_DEFAULT_TIMEOUT": os.environ.get("CACHE_DEFAULT_TIMEOUT") or 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
@ -60,7 +64,7 @@ def handle_access_denied(exc):
|
|||
return render_template("error_access_denied.html", exc=exc), 403
|
||||
|
||||
|
||||
def internal_server_error(e):
|
||||
def internal_server_error(exc):
|
||||
"""Bugs scodoc, erreurs 500"""
|
||||
# note that we set the 500 status explicitly
|
||||
return (
|
||||
|
@ -68,11 +72,35 @@ def internal_server_error(e):
|
|||
"error_500.html",
|
||||
SCOVERSION=sco_version.SCOVERSION,
|
||||
date=datetime.datetime.now().isoformat(),
|
||||
exc=exc,
|
||||
request_url=request.url,
|
||||
),
|
||||
500,
|
||||
)
|
||||
|
||||
|
||||
def handle_sco_bug(exc):
|
||||
"""Un bug, en général rare, sur lequel les dev cherchent des
|
||||
informations pour le corriger.
|
||||
"""
|
||||
Thread(
|
||||
target=_async_dump, args=(current_app._get_current_object(), request.url)
|
||||
).start()
|
||||
|
||||
return internal_server_error(exc)
|
||||
|
||||
|
||||
def _async_dump(app, request_url: str):
|
||||
from app.scodoc.sco_dump_db import sco_dump_and_send_db
|
||||
|
||||
with app.app_context():
|
||||
ndb.open_db_connection()
|
||||
try:
|
||||
sco_dump_and_send_db("ScoBugCatcher", request_url=request_url)
|
||||
except ScoValueError:
|
||||
pass
|
||||
|
||||
|
||||
def handle_invalid_usage(error):
|
||||
response = jsonify(error.to_dict())
|
||||
response.status_code = error.status_code
|
||||
|
@ -187,10 +215,12 @@ def create_app(config_class=DevConfig):
|
|||
moment.init_app(app)
|
||||
cache.init_app(app)
|
||||
sco_cache.CACHE = cache
|
||||
if CACHE_TYPE: # non default
|
||||
app.logger.info(f"CACHE_TYPE={CACHE_TYPE}")
|
||||
|
||||
app.register_error_handler(ScoGenError, handle_sco_value_error)
|
||||
app.register_error_handler(ScoValueError, handle_sco_value_error)
|
||||
|
||||
app.register_error_handler(ScoBugCatcher, handle_sco_bug)
|
||||
app.register_error_handler(AccessDenied, handle_access_denied)
|
||||
app.register_error_handler(500, internal_server_error)
|
||||
app.register_error_handler(503, postgresql_server_error)
|
||||
|
@ -200,6 +230,10 @@ def create_app(config_class=DevConfig):
|
|||
|
||||
app.register_blueprint(auth_bp, url_prefix="/auth")
|
||||
|
||||
from app.entreprises import bp as entreprises_bp
|
||||
|
||||
app.register_blueprint(entreprises_bp, url_prefix="/ScoDoc/entreprises")
|
||||
|
||||
from app.views import scodoc_bp
|
||||
from app.views import scolar_bp
|
||||
from app.views import notes_bp
|
||||
|
@ -291,10 +325,12 @@ def create_app(config_class=DevConfig):
|
|||
|
||||
from app.scodoc.sco_bulletins_legacy import BulletinGeneratorLegacy
|
||||
from app.scodoc.sco_bulletins_standard import BulletinGeneratorStandard
|
||||
from app.but.bulletin_but_pdf import BulletinGeneratorStandardBUT
|
||||
from app.scodoc.sco_bulletins_ucac import BulletinGeneratorUCAC
|
||||
|
||||
# l'ordre est important, le premeir sera le "défaut" pour les nouveaux départements.
|
||||
# l'ordre est important, le premier sera le "défaut" pour les nouveaux départements.
|
||||
sco_bulletins_generator.register_bulletin_class(BulletinGeneratorStandard)
|
||||
sco_bulletins_generator.register_bulletin_class(BulletinGeneratorStandardBUT)
|
||||
sco_bulletins_generator.register_bulletin_class(BulletinGeneratorLegacy)
|
||||
sco_bulletins_generator.register_bulletin_class(BulletinGeneratorUCAC)
|
||||
if app.testing or app.debug:
|
||||
|
@ -330,7 +366,7 @@ def user_db_init():
|
|||
|
||||
current_app.logger.info("Init User's db")
|
||||
# Create roles:
|
||||
Role.insert_roles()
|
||||
Role.reset_standard_roles_permissions()
|
||||
current_app.logger.info("created initial roles")
|
||||
# Ensure that admin exists
|
||||
admin_mail = current_app.config.get("SCODOC_ADMIN_MAIL")
|
||||
|
@ -453,15 +489,12 @@ from app.models import Departement
|
|||
from app.scodoc import notesdb as ndb, sco_preferences
|
||||
from app.scodoc import sco_cache
|
||||
|
||||
# admin_role = Role.query.filter_by(name="SuperAdmin").first()
|
||||
# if admin_role:
|
||||
# admin = (
|
||||
# User.query.join(UserRole)
|
||||
# .filter((UserRole.user_id == User.id) & (UserRole.role_id == admin_role.id))
|
||||
# .first()
|
||||
# )
|
||||
# else:
|
||||
# click.echo(
|
||||
# "Warning: user database not initialized !\n (use: flask user-db-init)"
|
||||
# )
|
||||
# admin = None
|
||||
|
||||
def scodoc_flash_status_messages():
|
||||
"""Should be called on each page: flash messages indicating specific ScoDoc status"""
|
||||
email_test_mode_address = sco_preferences.get_preference("email_test_mode_address")
|
||||
if email_test_mode_address:
|
||||
flash(
|
||||
f"Mode test: mails redirigés vers {email_test_mode_address}",
|
||||
category="warning",
|
||||
)
|
||||
|
|
|
@ -49,10 +49,11 @@ from app.api.auth import token_auth
|
|||
from app.api.errors import error_response
|
||||
from app import models
|
||||
from app.models import FormSemestre, FormSemestreInscription, Identite
|
||||
from app.models import ApcReferentielCompetences
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
|
||||
|
||||
@bp.route("list_depts", methods=["GET"])
|
||||
@bp.route("/list_depts", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def list_depts():
|
||||
depts = models.Departement.query.filter_by(visible=True).all()
|
||||
|
@ -66,7 +67,7 @@ def etudiants():
|
|||
"""Liste de tous les étudiants actuellement inscrits à un semestre
|
||||
en cours.
|
||||
"""
|
||||
# Vérification de l'accès: permission Observateir sur tous les départements
|
||||
# Vérification de l'accès: permission Observateur sur tous les départements
|
||||
# (c'est un exemple à compléter)
|
||||
if not g.current_user.has_permission(Permission.ScoObservateur, None):
|
||||
return error_response(401, message="accès interdit")
|
||||
|
@ -78,3 +79,413 @@ def etudiants():
|
|||
FormSemestre.date_fin >= func.now(),
|
||||
)
|
||||
return jsonify([e.to_dict_bul(include_urls=False) for e in query])
|
||||
|
||||
|
||||
######################## Departements ##################################
|
||||
|
||||
|
||||
@bp.route("/departements", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def departements():
|
||||
"""
|
||||
Liste des ids de départements
|
||||
"""
|
||||
depts = models.Departement.query.filter_by(visible=True).all()
|
||||
data = [d.id for d in depts]
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@bp.route("/departements/<string:dept>/etudiants/liste/<int:sem_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def liste_etudiants(dept, *args, sem_id): # XXX TODO A REVOIR
|
||||
"""
|
||||
Liste des étudiants d'un département
|
||||
"""
|
||||
# Test si le sem_id à été renseigné ou non
|
||||
if sem_id is not None:
|
||||
# Récupération du/des depts
|
||||
list_depts = models.Departement.query.filter(
|
||||
models.Departement.acronym == dept,
|
||||
models.FormSemestre.semestre_id == sem_id,
|
||||
)
|
||||
list_etuds = []
|
||||
for dept in list_depts:
|
||||
# Récupération des étudiants d'un département
|
||||
x = models.Identite.query.filter(models.Identite.dept_id == dept.getId())
|
||||
for y in x:
|
||||
# Ajout des étudiants dans la liste global
|
||||
list_etuds.append(y)
|
||||
else:
|
||||
list_depts = models.Departement.query.filter(
|
||||
models.Departement.acronym == dept,
|
||||
models.FormSemestre.semestre_id == models.Departement.formsemestres,
|
||||
)
|
||||
list_etuds = []
|
||||
for dept in list_depts:
|
||||
x = models.Identite.query.filter(models.Identite.dept_id == dept.getId())
|
||||
for y in x:
|
||||
list_etuds.append(y)
|
||||
|
||||
data = [d.to_dict() for d in list_etuds]
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/departements/<string:dept>/semestres_actifs", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def liste_semestres_actifs(dept): # TODO : changer nom
|
||||
"""
|
||||
Liste des semestres actifs d'un départements donné
|
||||
"""
|
||||
# Récupération de l'id du dept
|
||||
dept_id = models.Departement.query.filter(models.Departement.acronym == dept)
|
||||
# Puis ici récupération du FormSemestre correspondant
|
||||
depts_actifs = models.FormSemestre.query.filter_by(
|
||||
etat=True,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
data = [da.to_dict() for da in depts_actifs]
|
||||
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/referentiel_competences/<int:referentiel_competence_id>")
|
||||
@token_auth.login_required
|
||||
def referentiel_competences(referentiel_competence_id):
|
||||
"""
|
||||
Le référentiel de compétences
|
||||
"""
|
||||
ref = ApcReferentielCompetences.query.get_or_404(referentiel_competence_id)
|
||||
return jsonify(ref.to_dict())
|
||||
|
||||
|
||||
####################### Etudiants ##################################
|
||||
|
||||
|
||||
@bp.route("/etudiant/<int:etudid>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def etudiant(etudid):
|
||||
"""
|
||||
Un dictionnaire avec les informations de l'étudiant correspondant à l'id passé en paramètres.
|
||||
"""
|
||||
etud: Identite = Identite.query.get_or_404(etudid)
|
||||
return jsonify(etud.to_dict_bul())
|
||||
|
||||
|
||||
@bp.route("/etudiant/<int:etudid>/semestre/<int:sem_id>/bulletin", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def etudiant_bulletin_semestre(etudid, sem_id):
|
||||
"""
|
||||
Le bulletin d'un étudiant en fonction de son id et d'un semestre donné
|
||||
"""
|
||||
# return jsonify(models.BulAppreciations.query.filter_by(etudid=etudid, formsemestre_id=sem_id))
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/formsemestre/<int:formsemestre_id>/departements/<string:dept>/etudiant/nip/<int:NIP>/releve",
|
||||
methods=["GET"],
|
||||
)
|
||||
@bp.route(
|
||||
"/formsemestre/<int:formsemestre_id>/departements/<string:dept>/etudiant/id/<int:etudid>/releve",
|
||||
methods=["GET"],
|
||||
)
|
||||
@bp.route(
|
||||
"/formsemestre/<int:formsemestre_id>/departements/<string:dept>/etudiant/ine/<int:numScodoc>/releve",
|
||||
methods=["GET"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def etudiant_bulletin(formsemestre_id, dept, etudid, format="json", *args, size):
|
||||
"""
|
||||
Un bulletin de note
|
||||
"""
|
||||
formsemestres = models.FormSemestre.query.filter_by(id=formsemestre_id)
|
||||
depts = models.Departement.query.filter_by(acronym=dept)
|
||||
etud = ""
|
||||
|
||||
data = []
|
||||
if args[0] == "short":
|
||||
pass
|
||||
elif args[0] == "selectevals":
|
||||
pass
|
||||
elif args[0] == "long":
|
||||
pass
|
||||
else:
|
||||
return "erreur"
|
||||
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/etudiant/<int:etudid>/semestre/<int:formsemestre_id>/groups", methods=["GET"]
|
||||
)
|
||||
@token_auth.login_required
|
||||
def etudiant_groups(etudid: int, formsemestre_id: int):
|
||||
"""
|
||||
Liste des groupes auxquels appartient l'étudiant dans le semestre indiqué
|
||||
"""
|
||||
semestre = models.FormSemestre.query.filter_by(id=formsemestre_id)
|
||||
etudiant = models.Identite.query.filter_by(id=etudid)
|
||||
|
||||
groups = models.Partition.query.filter(
|
||||
models.Partition.formsemestre_id == semestre,
|
||||
models.GroupDescr.etudiants == etudiant,
|
||||
)
|
||||
data = [d.to_dict() for d in groups]
|
||||
# return jsonify(data)
|
||||
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
#######################" Programmes de formations #########################
|
||||
|
||||
|
||||
@bp.route("/formations", methods=["GET"])
|
||||
@bp.route("/formations/<int:formation_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def formations(formation_id: int):
|
||||
"""
|
||||
Liste des formations
|
||||
"""
|
||||
formations = models.Formation.query.filter_by(id=formation_id)
|
||||
data = [d.to_dict() for d in formations]
|
||||
# return jsonify(data)
|
||||
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/formations/formation_export/<int:formation_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def formation_export(formation_id: int, export_ids=False):
|
||||
"""
|
||||
La formation, avec UE, matières, modules
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
###################### UE #######################################
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/departements/<string:dept>/formations/programme/<string:sem_id>", methods=["GET"]
|
||||
)
|
||||
@token_auth.login_required
|
||||
def eus(dept: str, sem_id: int):
|
||||
"""
|
||||
Liste des UES, ressources et SAE d'un semestre
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
######## Semestres de formation ###############
|
||||
|
||||
|
||||
@bp.route("/formations/formsemestre/<int:formsemestre_id>", methods=["GET"])
|
||||
@bp.route("/formations/apo/<int:etape_apo>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def formsemestre(
|
||||
id: int,
|
||||
):
|
||||
"""
|
||||
Information sur les formsemestres
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
############ Modules de formation ##############
|
||||
|
||||
|
||||
@bp.route("/formations/moduleimpl/<int:moduleimpl_id>", methods=["GET"])
|
||||
@bp.route(
|
||||
"/formations/moduleimpl/<int:moduleimpl_id>/formsemestre/<int:formsemestre_id>",
|
||||
methods=["GET"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def moduleimpl(id: int):
|
||||
"""
|
||||
Liste de moduleimpl
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
########### Groupes et partitions ###############
|
||||
|
||||
|
||||
@bp.route("/partitions/<int:formsemestre_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def partition(formsemestre_id: int):
|
||||
"""
|
||||
La liste de toutes les partitions d'un formsemestre
|
||||
"""
|
||||
partitions = models.Partition.query.filter_by(id=formsemestre_id)
|
||||
data = [d.to_dict() for d in partitions]
|
||||
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/partitions/formsemestre/<int:formsemestre_id>/groups/group_ids?with_codes=&all_groups=&etat=",
|
||||
methods=["GET"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def groups(formsemestre_id: int, group_ids: int):
|
||||
"""
|
||||
Liste des étudiants dans un groupe
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/partitions/set_groups?partition_id=<int:partition_id>&groups=<int:groups>&groups_to_delete=<int:groups_to_delete>&groups_to_create=<int:groups_to_create>",
|
||||
methods=["POST"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def set_groups(
|
||||
partition_id: int, groups: int, groups_to_delete: int, groups_to_create: int
|
||||
):
|
||||
"""
|
||||
Set les groups
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
####### Bulletins de notes ###########
|
||||
|
||||
|
||||
@bp.route("/evaluations/<int:moduleimpl_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def evaluations(moduleimpl_id: int):
|
||||
"""
|
||||
Liste des évaluations à partir de l'id d'un moduleimpl
|
||||
"""
|
||||
evals = models.Evaluation.query.filter_by(id=moduleimpl_id)
|
||||
data = [d.to_dict() for d in evals]
|
||||
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/evaluations/eval_notes/<int:evaluation_id>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def evaluation_notes(evaluation_id: int):
|
||||
"""
|
||||
Liste des notes à partir de l'id d'une évaluation donnée
|
||||
"""
|
||||
evals = models.Evaluation.query.filter_by(id=evaluation_id)
|
||||
notes = evals.get_notes()
|
||||
|
||||
data = [d.to_dict() for d in notes]
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/evaluations/eval_set_notes?eval_id=<int:eval_id>&etudid=<int:etudid>¬e=<int:note>",
|
||||
methods=["POST"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def evaluation_set_notes(eval_id: int, etudid: int, note: float):
|
||||
"""
|
||||
Set les notes d'une évaluation pour un étudiant donnée
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
############## Absences #############
|
||||
|
||||
|
||||
@bp.route("/absences/<int:etudid>", methods=["GET"])
|
||||
@bp.route("/absences/<int:etudid>/abs_just_only", methods=["GET"])
|
||||
def absences(etudid: int):
|
||||
"""
|
||||
Liste des absences d'un étudiant donnée
|
||||
"""
|
||||
abs = models.Absence.query.filter_by(id=etudid)
|
||||
|
||||
data = [d.to_dict() for d in abs]
|
||||
|
||||
# return jsonify(data)
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/absences/abs_signale", methods=["POST"])
|
||||
@token_auth.login_required
|
||||
def abs_signale():
|
||||
"""
|
||||
Retourne un html
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/absences/abs_annule", methods=["POST"])
|
||||
@token_auth.login_required
|
||||
def abs_annule():
|
||||
"""
|
||||
Retourne un html
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/absences/abs_annule_justif", methods=["POST"])
|
||||
@token_auth.login_required
|
||||
def abs_annule_justif():
|
||||
"""
|
||||
Retourne un html
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route(
|
||||
"/absences/abs_group_etat/?group_ids=<int:group_ids>&date_debut=date_debut&date_fin=date_fin",
|
||||
methods=["GET"],
|
||||
)
|
||||
@token_auth.login_required
|
||||
def abs_groupe_etat(
|
||||
group_ids: int, date_debut, date_fin, with_boursier=True, format="html"
|
||||
):
|
||||
"""
|
||||
Liste des absences d'un ou plusieurs groupes entre deux dates
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
################ Logos ################
|
||||
|
||||
|
||||
@bp.route("/logos", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def liste_logos(format="json"):
|
||||
"""
|
||||
Liste des logos définis pour le site scodoc.
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/logos/<string:nom>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def recup_logo_global(nom: str):
|
||||
"""
|
||||
Retourne l'image au format png ou jpg
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/departements/<string:dept>/logos", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def logo_dept(dept: str):
|
||||
"""
|
||||
Liste des logos définis pour le département visé.
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
||||
|
||||
@bp.route("/departement/<string:dept>/logos/<string:nom>", methods=["GET"])
|
||||
@token_auth.login_required
|
||||
def recup_logo_dept_global(dept: str, nom: str):
|
||||
"""
|
||||
L'image format png ou jpg
|
||||
"""
|
||||
return error_response(501, message="Not implemented")
|
||||
|
|
|
@ -76,7 +76,9 @@ class User(UserMixin, db.Model):
|
|||
"Departement",
|
||||
foreign_keys=[Departement.acronym],
|
||||
primaryjoin=(dept == Departement.acronym),
|
||||
lazy="dynamic",
|
||||
lazy="select",
|
||||
passive_deletes="all",
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
|
@ -171,7 +173,7 @@ class User(UserMixin, db.Model):
|
|||
"id": self.id,
|
||||
"active": self.active,
|
||||
"status_txt": "actif" if self.active else "fermé",
|
||||
"last_seen": self.last_seen.isoformat() + "Z",
|
||||
"last_seen": self.last_seen.isoformat() + "Z" if self.last_seen else "",
|
||||
"nom": (self.nom or ""), # sco8
|
||||
"prenom": (self.prenom or ""), # sco8
|
||||
"roles_string": self.get_roles_string(), # eg "Ens_RT, Ens_Info"
|
||||
|
@ -236,7 +238,7 @@ class User(UserMixin, db.Model):
|
|||
def get_dept_id(self) -> int:
|
||||
"returns user's department id, or None"
|
||||
if self.dept:
|
||||
return self._departement.first().id
|
||||
return self._departement.id
|
||||
return None
|
||||
|
||||
# Permissions management:
|
||||
|
@ -268,6 +270,8 @@ class User(UserMixin, db.Model):
|
|||
"""Add a role to this user.
|
||||
:param role: Role to add.
|
||||
"""
|
||||
if not isinstance(role, Role):
|
||||
raise ScoValueError("add_role: rôle invalide")
|
||||
self.user_roles.append(UserRole(user=self, role=role, dept=dept))
|
||||
|
||||
def add_roles(self, roles, dept):
|
||||
|
@ -279,7 +283,9 @@ class User(UserMixin, db.Model):
|
|||
|
||||
def set_roles(self, roles, dept):
|
||||
"set roles in the given dept"
|
||||
self.user_roles = [UserRole(user=self, role=r, dept=dept) for r in roles]
|
||||
self.user_roles = [
|
||||
UserRole(user=self, role=r, dept=dept) for r in roles if isinstance(r, Role)
|
||||
]
|
||||
|
||||
def get_roles(self):
|
||||
"iterator on my roles"
|
||||
|
@ -290,7 +296,11 @@ class User(UserMixin, db.Model):
|
|||
"""string repr. of user's roles (with depts)
|
||||
e.g. "Ens_RT, Ens_Info, Secr_CJ"
|
||||
"""
|
||||
return ",".join(f"{r.role.name or ''}_{r.dept or ''}" for r in self.user_roles)
|
||||
return ",".join(
|
||||
f"{r.role.name or ''}_{r.dept or ''}"
|
||||
for r in self.user_roles
|
||||
if r is not None
|
||||
)
|
||||
|
||||
def is_administrator(self):
|
||||
"True if i'm an active SuperAdmin"
|
||||
|
@ -400,20 +410,30 @@ class Role(db.Model):
|
|||
return self.permissions & perm == perm
|
||||
|
||||
@staticmethod
|
||||
def insert_roles():
|
||||
"""Create default roles"""
|
||||
def reset_standard_roles_permissions(reset_permissions=True):
|
||||
"""Create default roles if missing, then, if reset_permissions,
|
||||
reset their permissions to default values.
|
||||
"""
|
||||
default_role = "Observateur"
|
||||
for role_name, permissions in SCO_ROLES_DEFAULTS.items():
|
||||
role = Role.query.filter_by(name=role_name).first()
|
||||
if role is None:
|
||||
role = Role(name=role_name)
|
||||
role.reset_permissions()
|
||||
for perm in permissions:
|
||||
role.add_permission(perm)
|
||||
role.default = role.name == default_role
|
||||
db.session.add(role)
|
||||
role.default = role.name == default_role
|
||||
db.session.add(role)
|
||||
if reset_permissions:
|
||||
role.reset_permissions()
|
||||
for perm in permissions:
|
||||
role.add_permission(perm)
|
||||
db.session.add(role)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
@staticmethod
|
||||
def ensure_standard_roles():
|
||||
"""Create default roles if missing"""
|
||||
Role.reset_standard_roles_permissions(reset_permissions=False)
|
||||
|
||||
@staticmethod
|
||||
def get_named_role(name):
|
||||
"""Returns existing role with given name, or None."""
|
||||
|
|
|
@ -19,7 +19,7 @@ from app.auth.forms import (
|
|||
ResetPasswordForm,
|
||||
DeactivateUserForm,
|
||||
)
|
||||
from app.auth.models import Permission
|
||||
from app.auth.models import Role
|
||||
from app.auth.models import User
|
||||
from app.auth.email import send_password_reset_email
|
||||
from app.decorators import admin_required
|
||||
|
@ -121,3 +121,11 @@ def reset_password(token):
|
|||
flash(_("Votre mot de passe a été changé."))
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("auth/reset_password.html", form=form, user=user)
|
||||
|
||||
|
||||
@bp.route("/reset_standard_roles_permissions", methods=["GET", "POST"])
|
||||
@admin_required
|
||||
def reset_standard_roles_permissions():
|
||||
Role.reset_standard_roles_permissions()
|
||||
flash("rôles standard réinitialisés !")
|
||||
return redirect(url_for("scodoc.configuration"))
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
# empty but required for pylint
|
|
@ -4,154 +4,126 @@
|
|||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
from collections import defaultdict
|
||||
"""Génération bulletin BUT
|
||||
"""
|
||||
|
||||
import collections
|
||||
import datetime
|
||||
from flask import url_for, g
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from flask import url_for, g
|
||||
|
||||
from app import db
|
||||
|
||||
from app.comp import moy_ue, moy_sem, inscr_mod
|
||||
from app.models import ModuleImpl
|
||||
from app.scodoc import sco_utils as scu
|
||||
from app.scodoc.sco_cache import ResultatsSemestreBUTCache
|
||||
from app.scodoc import sco_abs
|
||||
from app.comp.res_but import ResultatsSemestreBUT
|
||||
from app.models import FormSemestre, Identite
|
||||
from app.models.ues import UniteEns
|
||||
from app.scodoc import sco_bulletins, sco_utils as scu
|
||||
from app.scodoc import sco_bulletins_json
|
||||
from app.scodoc import sco_bulletins_pdf
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.sco_utils import jsnan, fmt_note
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT, DEF
|
||||
from app.scodoc.sco_utils import fmt_note
|
||||
|
||||
|
||||
class ResultatsSemestreBUT:
|
||||
"""Structure légère pour stocker les résultats du semestre et
|
||||
générer les bulletins.
|
||||
__init__ : charge depuis le cache ou calcule
|
||||
class BulletinBUT:
|
||||
"""Génération du bulletin BUT.
|
||||
Cette classe génère des dictionnaires avec toutes les informations
|
||||
du bulletin, qui sont immédiatement traduisibles en JSON.
|
||||
"""
|
||||
|
||||
_cached_attrs = (
|
||||
"sem_cube",
|
||||
"modimpl_inscr_df",
|
||||
"modimpl_coefs_df",
|
||||
"etud_moy_ue",
|
||||
"modimpls_evals_poids",
|
||||
"modimpls_evals_notes",
|
||||
"etud_moy_gen",
|
||||
"etud_moy_gen_ranks",
|
||||
"modimpls_evaluations_complete",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre):
|
||||
self.formsemestre = formsemestre
|
||||
self.ues = formsemestre.query_ues().all()
|
||||
self.modimpls = formsemestre.modimpls.all()
|
||||
self.etuds = self.formsemestre.get_inscrits(include_dem=False)
|
||||
self.etud_index = {e.id: idx for idx, e in enumerate(self.etuds)}
|
||||
self.saes = [
|
||||
m for m in self.modimpls if m.module.module_type == scu.ModuleType.SAE
|
||||
]
|
||||
self.ressources = [
|
||||
m for m in self.modimpls if m.module.module_type == scu.ModuleType.RESSOURCE
|
||||
]
|
||||
if not self.load_cached():
|
||||
self.compute()
|
||||
self.store()
|
||||
|
||||
def load_cached(self) -> bool:
|
||||
"Load cached dataframes, returns False si pas en cache"
|
||||
data = ResultatsSemestreBUTCache.get(self.formsemestre.id)
|
||||
if not data:
|
||||
return False
|
||||
for attr in self._cached_attrs:
|
||||
setattr(self, attr, data[attr])
|
||||
return True
|
||||
|
||||
def store(self):
|
||||
"Cache our dataframes"
|
||||
ResultatsSemestreBUTCache.set(
|
||||
self.formsemestre.id,
|
||||
{attr: getattr(self, attr) for attr in self._cached_attrs},
|
||||
)
|
||||
|
||||
def compute(self):
|
||||
"Charge les notes et inscriptions et calcule toutes les moyennes"
|
||||
(
|
||||
self.sem_cube,
|
||||
self.modimpls_evals_poids,
|
||||
self.modimpls_evals_notes,
|
||||
modimpls_evaluations,
|
||||
self.modimpls_evaluations_complete,
|
||||
) = moy_ue.notes_sem_load_cube(self.formsemestre)
|
||||
self.modimpl_inscr_df = inscr_mod.df_load_modimpl_inscr(self.formsemestre)
|
||||
self.modimpl_coefs_df, _, _ = moy_ue.df_load_modimpl_coefs(
|
||||
self.formsemestre, ues=self.ues, modimpls=self.modimpls
|
||||
)
|
||||
# l'idx de la colonne du mod modimpl.id est
|
||||
# modimpl_coefs_df.columns.get_loc(modimpl.id)
|
||||
# idx de l'UE: modimpl_coefs_df.index.get_loc(ue.id)
|
||||
self.etud_moy_ue = moy_ue.compute_ue_moys(
|
||||
self.sem_cube,
|
||||
self.etuds,
|
||||
self.modimpls,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs_df,
|
||||
)
|
||||
self.etud_moy_gen = moy_sem.compute_sem_moys(
|
||||
self.etud_moy_ue, self.modimpl_coefs_df
|
||||
)
|
||||
self.etud_moy_gen_ranks = moy_sem.comp_ranks_series(self.etud_moy_gen)
|
||||
def __init__(self, formsemestre: FormSemestre):
|
||||
""" """
|
||||
self.res = ResultatsSemestreBUT(formsemestre)
|
||||
self.prefs = sco_preferences.SemPreferences(formsemestre.id)
|
||||
|
||||
def etud_ue_mod_results(self, etud, ue, modimpls) -> dict:
|
||||
"dict synthèse résultats dans l'UE pour les modules indiqués"
|
||||
res = self.res
|
||||
d = {}
|
||||
etud_idx = self.etud_index[etud.id]
|
||||
ue_idx = self.modimpl_coefs_df.index.get_loc(ue.id)
|
||||
etud_moy_module = self.sem_cube[etud_idx] # module x UE
|
||||
for mi in modimpls:
|
||||
if self.modimpl_inscr_df[str(mi.id)][etud.id]: # si inscrit
|
||||
coef = self.modimpl_coefs_df[mi.id][ue.id]
|
||||
if coef > 0:
|
||||
d[mi.module.code] = {
|
||||
"id": mi.id,
|
||||
"coef": coef,
|
||||
"moyenne": fmt_note(
|
||||
etud_moy_module[
|
||||
self.modimpl_coefs_df.columns.get_loc(mi.id)
|
||||
][ue_idx]
|
||||
),
|
||||
}
|
||||
etud_idx = res.etud_index[etud.id]
|
||||
if ue.type != UE_SPORT:
|
||||
ue_idx = res.modimpl_coefs_df.index.get_loc(ue.id)
|
||||
etud_moy_module = res.sem_cube[etud_idx] # module x UE
|
||||
for modimpl in modimpls:
|
||||
if res.modimpl_inscr_df[modimpl.id][etud.id]: # si inscrit
|
||||
if ue.type != UE_SPORT:
|
||||
coef = res.modimpl_coefs_df[modimpl.id][ue.id]
|
||||
if coef > 0:
|
||||
d[modimpl.module.code] = {
|
||||
"id": modimpl.id,
|
||||
"coef": coef,
|
||||
"moyenne": fmt_note(
|
||||
etud_moy_module[
|
||||
res.modimpl_coefs_df.columns.get_loc(modimpl.id)
|
||||
][ue_idx]
|
||||
),
|
||||
}
|
||||
# else: # modules dans UE bonus sport
|
||||
# d[modimpl.module.code] = {
|
||||
# "id": modimpl.id,
|
||||
# "coef": "",
|
||||
# "moyenne": "?x?",
|
||||
# }
|
||||
return d
|
||||
|
||||
def etud_ue_results(self, etud, ue):
|
||||
def etud_ue_results(self, etud: Identite, ue: UniteEns, decision_ue: dict) -> dict:
|
||||
"dict synthèse résultats UE"
|
||||
res = self.res
|
||||
|
||||
d = {
|
||||
"id": ue.id,
|
||||
"titre": ue.titre,
|
||||
"numero": ue.numero,
|
||||
"ECTS": {
|
||||
"acquis": 0, # XXX TODO voir jury
|
||||
"total": ue.ects,
|
||||
},
|
||||
"type": ue.type,
|
||||
"color": ue.color,
|
||||
"competence": None, # XXX TODO lien avec référentiel
|
||||
"moyenne": {
|
||||
"value": fmt_note(self.etud_moy_ue[ue.id][etud.id]),
|
||||
"min": fmt_note(self.etud_moy_ue[ue.id].min()),
|
||||
"max": fmt_note(self.etud_moy_ue[ue.id].max()),
|
||||
"moy": fmt_note(self.etud_moy_ue[ue.id].mean()),
|
||||
},
|
||||
"bonus": None, # XXX TODO
|
||||
"malus": None, # XXX TODO voir ce qui est ici
|
||||
"capitalise": None, # "AAAA-MM-JJ" TODO
|
||||
"ressources": self.etud_ue_mod_results(etud, ue, self.ressources),
|
||||
"saes": self.etud_ue_mod_results(etud, ue, self.saes),
|
||||
"moyenne": None,
|
||||
# Le bonus sport appliqué sur cette UE
|
||||
"bonus": fmt_note(res.bonus_ues[ue.id][etud.id])
|
||||
if res.bonus_ues is not None and ue.id in res.bonus_ues
|
||||
else fmt_note(0.0),
|
||||
"malus": fmt_note(res.malus[ue.id][etud.id]),
|
||||
"capitalise": None, # "AAAA-MM-JJ" TODO #sco92
|
||||
"ressources": self.etud_ue_mod_results(etud, ue, res.ressources),
|
||||
"saes": self.etud_ue_mod_results(etud, ue, res.saes),
|
||||
}
|
||||
if self.prefs["bul_show_ects"]:
|
||||
d["ECTS"] = {
|
||||
"acquis": decision_ue.get("ects", 0.0),
|
||||
"total": ue.ects or 0.0, # float même si non renseigné
|
||||
}
|
||||
if ue.type != UE_SPORT:
|
||||
if self.prefs["bul_show_ue_rangs"]:
|
||||
rangs, effectif = res.ue_rangs[ue.id]
|
||||
rang = rangs[etud.id]
|
||||
else:
|
||||
rang, effectif = "", 0
|
||||
d["moyenne"] = {
|
||||
"value": fmt_note(res.etud_moy_ue[ue.id][etud.id]),
|
||||
"min": fmt_note(res.etud_moy_ue[ue.id].min()),
|
||||
"max": fmt_note(res.etud_moy_ue[ue.id].max()),
|
||||
"moy": fmt_note(res.etud_moy_ue[ue.id].mean()),
|
||||
"rang": rang,
|
||||
"total": effectif, # nb etud avec note dans cette UE
|
||||
}
|
||||
else:
|
||||
# ceci suppose que l'on a une seule UE bonus,
|
||||
# en tous cas elles auront la même description
|
||||
d["bonus_description"] = self.etud_bonus_description(etud.id)
|
||||
modimpls_spo = [
|
||||
modimpl
|
||||
for modimpl in res.formsemestre.modimpls_sorted
|
||||
if modimpl.module.ue.type == UE_SPORT
|
||||
]
|
||||
d["modules"] = self.etud_mods_results(etud, modimpls_spo)
|
||||
return d
|
||||
|
||||
def etud_mods_results(self, etud, modimpls) -> dict:
|
||||
def etud_mods_results(self, etud, modimpls, version="long") -> dict:
|
||||
"""dict synthèse résultats des modules indiqués,
|
||||
avec évaluations de chacun."""
|
||||
avec évaluations de chacun (sauf si version == "short")
|
||||
"""
|
||||
res = self.res
|
||||
d = {}
|
||||
# etud_idx = self.etud_index[etud.id]
|
||||
for mi in modimpls:
|
||||
for modimpl in modimpls:
|
||||
# mod_idx = self.modimpl_coefs_df.columns.get_loc(mi.id)
|
||||
# # moyennes indicatives (moyennes de moyennes d'UE)
|
||||
# try:
|
||||
|
@ -159,24 +131,27 @@ class ResultatsSemestreBUT:
|
|||
# np.nanmean(self.sem_cube[:, mod_idx, :], axis=1),
|
||||
# copy=False,
|
||||
# )
|
||||
# except RuntimeWarning: # all nans in np.nanmean (sur certains etuds sans notes valides)
|
||||
# except RuntimeWarning:
|
||||
# # all nans in np.nanmean (sur certains etuds sans notes valides)
|
||||
# pass
|
||||
# try:
|
||||
# moy_indicative_mod = np.nanmean(self.sem_cube[etud_idx, mod_idx])
|
||||
# except RuntimeWarning: # all nans in np.nanmean
|
||||
# pass
|
||||
if self.modimpl_inscr_df[str(mi.id)][etud.id]: # si inscrit
|
||||
d[mi.module.code] = {
|
||||
"id": mi.id,
|
||||
"titre": mi.module.titre,
|
||||
"code_apogee": mi.module.code_apogee,
|
||||
modimpl_results = res.modimpls_results[modimpl.id]
|
||||
if res.modimpl_inscr_df[modimpl.id][etud.id]: # si inscrit
|
||||
d[modimpl.module.code] = {
|
||||
"id": modimpl.id,
|
||||
"titre": modimpl.module.titre,
|
||||
"code_apogee": modimpl.module.code_apogee,
|
||||
"url": url_for(
|
||||
"notes.moduleimpl_status",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
moduleimpl_id=mi.id,
|
||||
moduleimpl_id=modimpl.id,
|
||||
),
|
||||
"moyenne": {
|
||||
# # moyenne indicative de module: moyenne des UE, ignorant celles sans notes (nan)
|
||||
# # moyenne indicative de module: moyenne des UE,
|
||||
# # ignorant celles sans notes (nan)
|
||||
# "value": fmt_note(moy_indicative_mod),
|
||||
# "min": fmt_note(moyennes_etuds.min()),
|
||||
# "max": fmt_note(moyennes_etuds.max()),
|
||||
|
@ -184,28 +159,43 @@ class ResultatsSemestreBUT:
|
|||
},
|
||||
"evaluations": [
|
||||
self.etud_eval_results(etud, e)
|
||||
for eidx, e in enumerate(mi.evaluations)
|
||||
if e.visibulletin
|
||||
and self.modimpls_evaluations_complete[mi.id][eidx]
|
||||
],
|
||||
for e in modimpl.evaluations
|
||||
if (e.visibulletin or version == "long")
|
||||
and (
|
||||
modimpl_results.evaluations_etat[e.id].is_complete
|
||||
or self.prefs["bul_show_all_evals"]
|
||||
)
|
||||
]
|
||||
if version != "short"
|
||||
else [],
|
||||
}
|
||||
return d
|
||||
|
||||
def etud_eval_results(self, etud, e) -> dict:
|
||||
"dict resultats d'un étudiant à une évaluation"
|
||||
eval_notes = self.modimpls_evals_notes[e.moduleimpl_id][e.id] # pd.Series
|
||||
# eval_notes est une pd.Series avec toutes les notes des étudiants inscrits
|
||||
eval_notes = self.res.modimpls_results[e.moduleimpl_id].evals_notes[e.id]
|
||||
notes_ok = eval_notes.where(eval_notes > scu.NOTES_ABSENCE).dropna()
|
||||
modimpls_evals_poids = self.res.modimpls_evals_poids[e.moduleimpl_id]
|
||||
try:
|
||||
poids = {
|
||||
ue.acronyme: modimpls_evals_poids[ue.id][e.id]
|
||||
for ue in self.res.ues
|
||||
if ue.type != UE_SPORT
|
||||
}
|
||||
except KeyError:
|
||||
poids = collections.defaultdict(lambda: 0.0)
|
||||
d = {
|
||||
"id": e.id,
|
||||
"description": e.description,
|
||||
"date": e.jour.isoformat() if e.jour else None,
|
||||
"heure_debut": e.heure_debut.strftime("%H:%M") if e.heure_debut else None,
|
||||
"heure_fin": e.heure_fin.strftime("%H:%M") if e.heure_debut else None,
|
||||
"coef": e.coefficient,
|
||||
"poids": {p.ue.acronyme: p.poids for p in e.ue_poids},
|
||||
"coef": fmt_note(e.coefficient),
|
||||
"poids": poids,
|
||||
"note": {
|
||||
"value": fmt_note(
|
||||
self.modimpls_evals_notes[e.moduleimpl_id][e.id][etud.id],
|
||||
eval_notes[etud.id],
|
||||
note_max=e.note_max,
|
||||
),
|
||||
"min": fmt_note(notes_ok.min()),
|
||||
|
@ -220,12 +210,48 @@ class ResultatsSemestreBUT:
|
|||
}
|
||||
return d
|
||||
|
||||
def bulletin_etud(self, etud, formsemestre, force_publishing=False) -> dict:
|
||||
"""Le bulletin de l'étudiant dans ce semestre.
|
||||
Si force_publishing, rempli le bulletin même si bul_hide_xml est vrai
|
||||
def etud_bonus_description(self, etudid):
|
||||
"""description du bonus affichée dans la section "UE bonus"."""
|
||||
res = self.res
|
||||
if res.bonus_ues is None or res.bonus_ues.shape[1] == 0:
|
||||
return ""
|
||||
|
||||
bonus_vect = res.bonus_ues.loc[etudid]
|
||||
if bonus_vect.nunique() > 1:
|
||||
# détail UE par UE
|
||||
details = [
|
||||
f"{fmt_note(bonus_vect[ue.id])} sur {ue.acronyme}"
|
||||
for ue in res.ues
|
||||
if ue.type != UE_SPORT
|
||||
and res.modimpls_in_ue(ue.id, etudid)
|
||||
and ue.id in res.bonus_ues
|
||||
and bonus_vect[ue.id] > 0.0
|
||||
]
|
||||
if details:
|
||||
return "Bonus de " + ", ".join(details)
|
||||
else:
|
||||
return "" # aucun bonus
|
||||
else:
|
||||
return f"Bonus de {fmt_note(bonus_vect.iloc[0])}"
|
||||
|
||||
def bulletin_etud(
|
||||
self,
|
||||
etud: Identite,
|
||||
formsemestre: FormSemestre,
|
||||
force_publishing=False,
|
||||
version="long",
|
||||
) -> dict:
|
||||
"""Le bulletin de l'étudiant dans ce semestre: dict pour la version JSON / HTML.
|
||||
- version:
|
||||
"long", "selectedevals": toutes les infos (notes des évaluations)
|
||||
"short" : ne descend pas plus bas que les modules.
|
||||
|
||||
- Si force_publishing, rempli le bulletin même si bul_hide_xml est vrai
|
||||
(bulletins non publiés).
|
||||
"""
|
||||
etat_inscription = etud.etat_inscription(formsemestre.id)
|
||||
res = self.res
|
||||
etat_inscription = etud.inscription_etat(formsemestre.id)
|
||||
nb_inscrits = self.res.get_inscriptions_counts()[scu.INSCRIT]
|
||||
published = (not formsemestre.bul_hide_xml) or force_publishing
|
||||
d = {
|
||||
"version": "0",
|
||||
|
@ -241,7 +267,9 @@ class ResultatsSemestreBUT:
|
|||
},
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etat_inscription": etat_inscription,
|
||||
"options": bulletin_option_affichage(formsemestre),
|
||||
"options": sco_preferences.bulletin_option_affichage(
|
||||
formsemestre.id, self.prefs
|
||||
),
|
||||
}
|
||||
if not published:
|
||||
return d
|
||||
|
@ -251,39 +279,59 @@ class ResultatsSemestreBUT:
|
|||
"etapes": [str(x.etape_apo) for x in formsemestre.etapes if x.etape_apo],
|
||||
"date_debut": formsemestre.date_debut.isoformat(),
|
||||
"date_fin": formsemestre.date_fin.isoformat(),
|
||||
"annee_universitaire": self.formsemestre.annee_scolaire_str(),
|
||||
"inscription": "TODO-MM-JJ", # XXX TODO
|
||||
"annee_universitaire": formsemestre.annee_scolaire_str(),
|
||||
"numero": formsemestre.semestre_id,
|
||||
"inscription": "", # inutilisé mais nécessaire pour le js de Seb.
|
||||
"groupes": [], # XXX TODO
|
||||
"absences": {
|
||||
"injustifie": nbabsjust,
|
||||
"total": nbabs,
|
||||
},
|
||||
}
|
||||
if self.prefs["bul_show_abs"]:
|
||||
semestre_infos["absences"] = {
|
||||
"injustifie": nbabs - nbabsjust,
|
||||
"total": nbabs,
|
||||
}
|
||||
decisions_ues = self.res.get_etud_decision_ues(etud.id) or {}
|
||||
if self.prefs["bul_show_ects"]:
|
||||
ects_tot = sum([ue.ects or 0 for ue in res.ues]) if res.ues else 0.0
|
||||
ects_acquis = sum([d.get("ects", 0) for d in decisions_ues.values()])
|
||||
semestre_infos["ECTS"] = {"acquis": ects_acquis, "total": ects_tot}
|
||||
semestre_infos.update(
|
||||
sco_bulletins_json.dict_decision_jury(etud.id, formsemestre.id)
|
||||
)
|
||||
if etat_inscription == scu.INSCRIT:
|
||||
semestre_infos.update(
|
||||
{
|
||||
"notes": { # moyenne des moyennes générales du semestre
|
||||
"value": fmt_note(self.etud_moy_gen[etud.id]),
|
||||
"min": fmt_note(self.etud_moy_gen.min()),
|
||||
"moy": fmt_note(self.etud_moy_gen.mean()),
|
||||
"max": fmt_note(self.etud_moy_gen.max()),
|
||||
},
|
||||
"rang": { # classement wrt moyenne général, indicatif
|
||||
"value": self.etud_moy_gen_ranks[etud.id],
|
||||
"total": len(self.etuds),
|
||||
},
|
||||
},
|
||||
)
|
||||
# moyenne des moyennes générales du semestre
|
||||
semestre_infos["notes"] = {
|
||||
"value": fmt_note(res.etud_moy_gen[etud.id]),
|
||||
"min": fmt_note(res.etud_moy_gen.min()),
|
||||
"moy": fmt_note(res.etud_moy_gen.mean()),
|
||||
"max": fmt_note(res.etud_moy_gen.max()),
|
||||
}
|
||||
if self.prefs["bul_show_rangs"] and not np.isnan(res.etud_moy_gen[etud.id]):
|
||||
# classement wrt moyenne général, indicatif
|
||||
semestre_infos["rang"] = {
|
||||
"value": res.etud_moy_gen_ranks[etud.id],
|
||||
"total": nb_inscrits,
|
||||
}
|
||||
else:
|
||||
semestre_infos["rang"] = {
|
||||
"value": "-",
|
||||
"total": nb_inscrits,
|
||||
}
|
||||
d.update(
|
||||
{
|
||||
"ressources": self.etud_mods_results(etud, self.ressources),
|
||||
"saes": self.etud_mods_results(etud, self.saes),
|
||||
"ressources": self.etud_mods_results(
|
||||
etud, res.ressources, version=version
|
||||
),
|
||||
"saes": self.etud_mods_results(etud, res.saes, version=version),
|
||||
"ues": {
|
||||
ue.acronyme: self.etud_ue_results(etud, ue) for ue in self.ues
|
||||
ue.acronyme: self.etud_ue_results(
|
||||
etud, ue, decision_ue=decisions_ues.get(ue.id, {})
|
||||
)
|
||||
for ue in res.ues
|
||||
# si l'UE comporte des modules auxquels on est inscrit:
|
||||
if (
|
||||
(ue.type == UE_SPORT)
|
||||
or self.res.modimpls_in_ue(ue.id, etud.id)
|
||||
)
|
||||
},
|
||||
"semestre": semestre_infos,
|
||||
},
|
||||
|
@ -297,7 +345,7 @@ class ResultatsSemestreBUT:
|
|||
"moy": "",
|
||||
"max": "",
|
||||
},
|
||||
"rang": {"value": "DEM", "total": len(self.etuds)},
|
||||
"rang": {"value": "DEM", "total": nb_inscrits},
|
||||
}
|
||||
)
|
||||
d.update(
|
||||
|
@ -311,124 +359,55 @@ class ResultatsSemestreBUT:
|
|||
|
||||
return d
|
||||
|
||||
def bulletin_etud_complet(self, etud: Identite, version="long") -> dict:
|
||||
"""Bulletin dict complet avec toutes les infos pour les bulletins BUT pdf
|
||||
Résultat compatible avec celui de sco_bulletins.formsemestre_bulletinetud_dict
|
||||
"""
|
||||
d = self.bulletin_etud(
|
||||
etud, self.res.formsemestre, version=version, force_publishing=True
|
||||
)
|
||||
d["etudid"] = etud.id
|
||||
d["etud"] = d["etudiant"]
|
||||
d["etud"]["nomprenom"] = etud.nomprenom
|
||||
d.update(self.res.sem)
|
||||
etud_etat = self.res.get_etud_etat(etud.id)
|
||||
d["filigranne"] = sco_bulletins_pdf.get_filigranne(
|
||||
etud_etat,
|
||||
self.prefs,
|
||||
decision_sem=d["semestre"].get("decision"),
|
||||
)
|
||||
if etud_etat == scu.DEMISSION:
|
||||
d["demission"] = "(Démission)"
|
||||
elif etud_etat == DEF:
|
||||
d["demission"] = "(Défaillant)"
|
||||
else:
|
||||
d["demission"] = ""
|
||||
|
||||
def bulletin_option_affichage(formsemestre):
|
||||
"dict avec les options d'affichages (préférences) pour ce semestre"
|
||||
prefs = sco_preferences.SemPreferences(formsemestre.id)
|
||||
fields = (
|
||||
"bul_show_abs",
|
||||
"bul_show_abs_modules",
|
||||
"bul_show_ects",
|
||||
"bul_show_codemodules",
|
||||
"bul_show_matieres",
|
||||
"bul_show_rangs",
|
||||
"bul_show_ue_rangs",
|
||||
"bul_show_mod_rangs",
|
||||
"bul_show_moypromo",
|
||||
"bul_show_minmax",
|
||||
"bul_show_minmax_mod",
|
||||
"bul_show_minmax_eval",
|
||||
"bul_show_coef",
|
||||
"bul_show_ue_cap_details",
|
||||
"bul_show_ue_cap_current",
|
||||
"bul_show_temporary",
|
||||
"bul_temporary_txt",
|
||||
"bul_show_uevalid",
|
||||
"bul_show_date_inscr",
|
||||
)
|
||||
# on enlève le "bul_" de la clé:
|
||||
return {field[4:]: prefs[field] for field in fields}
|
||||
# --- Absences
|
||||
d["nbabs"], d["nbabsjust"] = self.res.formsemestre.get_abs_count(etud.id)
|
||||
|
||||
# --- Decision Jury
|
||||
infos, dpv = sco_bulletins.etud_descr_situation_semestre(
|
||||
etud.id,
|
||||
self.res.formsemestre.id,
|
||||
format="html",
|
||||
show_date_inscr=self.prefs["bul_show_date_inscr"],
|
||||
show_decisions=self.prefs["bul_show_decision"],
|
||||
show_uevalid=self.prefs["bul_show_uevalid"],
|
||||
show_mention=self.prefs["bul_show_mention"],
|
||||
)
|
||||
|
||||
# Pour raccorder le code des anciens bulletins qui attendent une NoteTable
|
||||
class APCNotesTableCompat:
|
||||
"""Implementation partielle de NotesTable pour les formations APC
|
||||
Accès aux notes et rangs.
|
||||
"""
|
||||
d.update(infos)
|
||||
# --- Rangs
|
||||
d[
|
||||
"rang_nt"
|
||||
] = f"{d['semestre']['rang']['value']} / {d['semestre']['rang']['total']}"
|
||||
d["rang_txt"] = "Rang " + d["rang_nt"]
|
||||
|
||||
def __init__(self, formsemestre):
|
||||
self.results = ResultatsSemestreBUT(formsemestre)
|
||||
nb_etuds = len(self.results.etuds)
|
||||
self.rangs = self.results.etud_moy_gen_ranks
|
||||
self.moy_min = self.results.etud_moy_gen.min()
|
||||
self.moy_max = self.results.etud_moy_gen.max()
|
||||
self.moy_moy = self.results.etud_moy_gen.mean()
|
||||
self.bonus = defaultdict(lambda: 0.0) # XXX
|
||||
self.ue_rangs = {
|
||||
u.id: (defaultdict(lambda: 0.0), nb_etuds) for u in self.results.ues
|
||||
}
|
||||
self.mod_rangs = {
|
||||
m.id: (defaultdict(lambda: 0), nb_etuds) for m in self.results.modimpls
|
||||
}
|
||||
# --- Appréciations
|
||||
d.update(
|
||||
sco_bulletins.get_appreciations_list(self.res.formsemestre.id, etud.id)
|
||||
)
|
||||
d.update(sco_bulletins.make_context_dict(self.res.formsemestre, d["etud"]))
|
||||
|
||||
def get_ues(self):
|
||||
ues = []
|
||||
for ue in self.results.ues:
|
||||
d = ue.to_dict()
|
||||
d.update(
|
||||
{
|
||||
"max": self.results.etud_moy_ue[ue.id].max(),
|
||||
"min": self.results.etud_moy_ue[ue.id].min(),
|
||||
"moy": self.results.etud_moy_ue[ue.id].mean(),
|
||||
"nb_moy": len(self.results.etud_moy_ue),
|
||||
}
|
||||
)
|
||||
ues.append(d)
|
||||
return ues
|
||||
|
||||
def get_modimpls(self):
|
||||
return [m.to_dict() for m in self.results.modimpls]
|
||||
|
||||
def get_etud_moy_gen(self, etudid):
|
||||
return self.results.etud_moy_gen[etudid]
|
||||
|
||||
def get_moduleimpls_attente(self):
|
||||
return [] # XXX TODO
|
||||
|
||||
def get_etud_rang(self, etudid):
|
||||
return self.rangs[etudid]
|
||||
|
||||
def get_etud_rang_group(self, etudid, group_id):
|
||||
return (None, 0) # XXX unimplemented TODO
|
||||
|
||||
def get_etud_ue_status(self, etudid, ue_id):
|
||||
return {
|
||||
"cur_moy_ue": self.results.etud_moy_ue[ue_id][etudid],
|
||||
"is_capitalized": False, # XXX TODO
|
||||
}
|
||||
|
||||
def get_etud_mod_moy(self, moduleimpl_id, etudid):
|
||||
mod_idx = self.results.modimpl_coefs_df.columns.get_loc(moduleimpl_id)
|
||||
etud_idx = self.results.etud_index[etudid]
|
||||
# moyenne sur les UE:
|
||||
self.results.sem_cube[etud_idx, mod_idx].mean()
|
||||
|
||||
def get_mod_stats(self, moduleimpl_id):
|
||||
return {
|
||||
"moy": "-",
|
||||
"max": "-",
|
||||
"min": "-",
|
||||
"nb_notes": "-",
|
||||
"nb_missing": "-",
|
||||
"nb_valid_evals": "-",
|
||||
}
|
||||
|
||||
def get_evals_in_mod(self, moduleimpl_id):
|
||||
mi = ModuleImpl.query.get(moduleimpl_id)
|
||||
evals_results = []
|
||||
for e in mi.evaluations:
|
||||
d = e.to_dict()
|
||||
d["heure_debut"] = e.heure_debut # datetime.time
|
||||
d["heure_fin"] = e.heure_fin
|
||||
d["jour"] = e.jour # datetime
|
||||
d["notes"] = {
|
||||
etud.id: {
|
||||
"etudid": etud.id,
|
||||
"value": self.results.modimpls_evals_notes[e.moduleimpl_id][e.id][
|
||||
etud.id
|
||||
],
|
||||
}
|
||||
for etud in self.results.etuds
|
||||
}
|
||||
evals_results.append(d)
|
||||
return evals_results
|
||||
return d
|
||||
|
|
|
@ -0,0 +1,351 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Génération bulletin BUT au format PDF standard
|
||||
"""
|
||||
from reportlab.lib.colors import blue
|
||||
from reportlab.lib.units import cm, mm
|
||||
from reportlab.platypus import Paragraph, Spacer
|
||||
|
||||
from app.scodoc.sco_bulletins_standard import BulletinGeneratorStandard
|
||||
from app.scodoc import gen_tables
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
|
||||
|
||||
class BulletinGeneratorStandardBUT(BulletinGeneratorStandard):
|
||||
"""Génération du bulletin de BUT au format PDF.
|
||||
|
||||
self.infos est le dict issu de BulletinBUT.bulletin_etud_complet()
|
||||
"""
|
||||
|
||||
# spécialisation du BulletinGeneratorStandard, ne pas présenter à l'utilisateur:
|
||||
list_in_menu = False
|
||||
scale_table_in_page = False # pas de mise à l'échelle pleine page auto
|
||||
multi_pages = True # plusieurs pages par bulletins
|
||||
small_fontsize = "8"
|
||||
|
||||
def bul_table(self, format="html"):
|
||||
"""Génère la table centrale du bulletin de notes
|
||||
Renvoie:
|
||||
- en HTML: une chaine
|
||||
- en PDF: une liste d'objets PLATYPUS (eg instance de Table).
|
||||
"""
|
||||
tables_infos = [
|
||||
# ---- TABLE SYNTHESE UES
|
||||
self.but_table_synthese_ues(),
|
||||
]
|
||||
if self.version != "short":
|
||||
tables_infos += [
|
||||
# ---- TABLE RESSOURCES
|
||||
self.but_table_ressources(),
|
||||
# ---- TABLE SAE
|
||||
self.but_table_saes(),
|
||||
]
|
||||
objects = []
|
||||
for i, (col_keys, rows, pdf_style, col_widths) in enumerate(tables_infos):
|
||||
table = gen_tables.GenTable(
|
||||
rows=rows,
|
||||
columns_ids=col_keys,
|
||||
pdf_table_style=pdf_style,
|
||||
pdf_col_widths=[col_widths[k] for k in col_keys],
|
||||
preferences=self.preferences,
|
||||
html_class="notes_bulletin",
|
||||
html_class_ignore_default=True,
|
||||
html_with_td_classes=True,
|
||||
)
|
||||
table_objects = table.gen(format=format)
|
||||
objects += table_objects
|
||||
# objects += [KeepInFrame(0, 0, table_objects, mode="shrink")]
|
||||
if i != 2:
|
||||
objects.append(Spacer(1, 6 * mm))
|
||||
|
||||
return objects
|
||||
|
||||
def but_table_synthese_ues(self, title_bg=(182, 235, 255)):
|
||||
"""La table de synthèse; pour chaque UE, liste des ressources et SAÉs avec leurs notes
|
||||
et leurs coefs.
|
||||
Renvoie: colkeys, P, pdf_style, colWidths
|
||||
- colkeys: nom des colonnes de la table (clés)
|
||||
- P : table (liste de dicts de chaines de caracteres)
|
||||
- pdf_style : commandes table Platypus
|
||||
- largeurs de colonnes pour PDF
|
||||
"""
|
||||
col_widths = {
|
||||
"titre": None,
|
||||
"moyenne": 2 * cm,
|
||||
"coef": 2 * cm,
|
||||
}
|
||||
title_bg = tuple(x / 255.0 for x in title_bg)
|
||||
nota_bene = """La moyenne des ressources et SAÉs dans une UE
|
||||
dépend des poids donnés aux évaluations."""
|
||||
# elems pour générer table avec gen_table (liste de dicts)
|
||||
rows = [
|
||||
# Ligne de titres
|
||||
{
|
||||
"titre": "Unités d'enseignement",
|
||||
"moyenne": Paragraph("<para align=right><b>Note/20</b></para>"),
|
||||
"coef": "Coef.",
|
||||
"_coef_pdf": Paragraph("<para align=right><b><i>Coef.</i></b></para>"),
|
||||
"_css_row_class": "note_bold",
|
||||
"_pdf_row_markup": ["b"],
|
||||
"_pdf_style": [
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
# ("BOTTOMPADDING", (0, 0), (-1, 0), 7),
|
||||
],
|
||||
},
|
||||
{
|
||||
"titre": nota_bene,
|
||||
"_titre_pdf": Paragraph(
|
||||
f"<para fontSize={self.small_fontsize}><i>{nota_bene}</i></para>"
|
||||
),
|
||||
"_titre_colspan": 3,
|
||||
"_pdf_style": [
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
("BOTTOMPADDING", (0, 0), (-1, 0), 7),
|
||||
(
|
||||
"LINEBELOW",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
blue,
|
||||
),
|
||||
],
|
||||
},
|
||||
]
|
||||
col_keys = ["titre", "coef", "moyenne"] # noms des colonnes à afficher
|
||||
for ue_acronym, ue in self.infos["ues"].items():
|
||||
self.ue_rows(rows, ue_acronym, ue, title_bg)
|
||||
# Global pdf style commands:
|
||||
pdf_style = [
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
("BOX", (0, 0), (-1, -1), 0.4, blue), # ajoute cadre extérieur bleu:
|
||||
]
|
||||
return col_keys, rows, pdf_style, col_widths
|
||||
|
||||
def ue_rows(self, rows: list, ue_acronym: str, ue: dict, title_bg: tuple):
|
||||
"Décrit une UE dans la table synthèse: titre, sous-titre et liste modules"
|
||||
# 1er ligne titre UE
|
||||
moy_ue = ue.get("moyenne")
|
||||
t = {
|
||||
"titre": f"{ue_acronym} - {ue['titre']}",
|
||||
"moyenne": Paragraph(
|
||||
f"""<para align=right><b>{moy_ue.get("value", "-")
|
||||
if moy_ue is not None else "-"
|
||||
}</b></para>"""
|
||||
),
|
||||
"_css_row_class": "note_bold",
|
||||
"_pdf_row_markup": ["b"],
|
||||
"_pdf_style": [
|
||||
(
|
||||
"LINEABOVE",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
self.PDF_LINECOLOR,
|
||||
),
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
("BOTTOMPADDING", (0, 0), (-1, 0), 7),
|
||||
],
|
||||
}
|
||||
rows.append(t)
|
||||
if ue["type"] == UE_SPORT:
|
||||
self.ue_sport_rows(rows, ue, title_bg)
|
||||
else:
|
||||
self.ue_std_rows(rows, ue, title_bg)
|
||||
|
||||
def ue_std_rows(self, rows: list, ue: dict, title_bg: tuple):
|
||||
"Lignes décrivant une UE standard dans la table de synthèse"
|
||||
# 2eme ligne titre UE (bonus/malus/ects)
|
||||
if "ECTS" in ue:
|
||||
ects_txt = f'ECTS: {ue["ECTS"]["acquis"]:.3g} / {ue["ECTS"]["total"]:.3g}'
|
||||
else:
|
||||
ects_txt = ""
|
||||
t = {
|
||||
"titre": f"""Bonus: {ue['bonus']} - Malus: {
|
||||
ue["malus"]}""",
|
||||
"coef": ects_txt,
|
||||
"_coef_pdf": Paragraph(f"""<para align=left>{ects_txt}</para>"""),
|
||||
"_coef_colspan": 2,
|
||||
"_pdf_style": [
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
("LINEBELOW", (0, 0), (-1, 0), self.PDF_LINEWIDTH, self.PDF_LINECOLOR),
|
||||
# cadre autour du bonus/malus, gris clair
|
||||
("BOX", (0, 0), (0, 0), self.PDF_LINEWIDTH, (0.7, 0.7, 0.7)),
|
||||
],
|
||||
}
|
||||
rows.append(t)
|
||||
|
||||
# Liste chaque ressource puis chaque SAE
|
||||
for mod_type in ("ressources", "saes"):
|
||||
for mod_code, mod in ue[mod_type].items():
|
||||
t = {
|
||||
"titre": f"{mod_code} {self.infos[mod_type][mod_code]['titre']}",
|
||||
"moyenne": Paragraph(f'<para align=right>{mod["moyenne"]}</para>'),
|
||||
"coef": mod["coef"],
|
||||
"_coef_pdf": Paragraph(
|
||||
f"<para align=right><i>{mod['coef']}</i></para>"
|
||||
),
|
||||
"_pdf_style": [
|
||||
(
|
||||
"LINEBELOW",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
(0.7, 0.7, 0.7), # gris clair
|
||||
)
|
||||
],
|
||||
}
|
||||
rows.append(t)
|
||||
|
||||
def ue_sport_rows(self, rows: list, ue: dict, title_bg: tuple):
|
||||
"Lignes décrivant l'UE bonus dans la table de synthèse"
|
||||
# UE BONUS
|
||||
for mod_code, mod in ue["modules"].items():
|
||||
rows.append(
|
||||
{
|
||||
"titre": f"{mod_code} {mod['titre']}",
|
||||
}
|
||||
)
|
||||
self.evaluations_rows(rows, mod["evaluations"])
|
||||
|
||||
def but_table_ressources(self):
|
||||
"""La table de synthèse; pour chaque ressources, note et liste d'évaluations
|
||||
Renvoie: colkeys, P, pdf_style, colWidths
|
||||
"""
|
||||
return self.bul_table_modules(
|
||||
mod_type="ressources", title="Ressources", title_bg=(248, 200, 68)
|
||||
)
|
||||
|
||||
def but_table_saes(self):
|
||||
"table des SAEs"
|
||||
return self.bul_table_modules(
|
||||
mod_type="saes",
|
||||
title="Situations d'apprentissage et d'évaluation",
|
||||
title_bg=(198, 255, 171),
|
||||
)
|
||||
|
||||
def bul_table_modules(self, mod_type=None, title="", title_bg=(248, 200, 68)):
|
||||
"""Table ressources ou SAEs
|
||||
- colkeys: nom des colonnes de la table (clés)
|
||||
- P : table (liste de dicts de chaines de caracteres)
|
||||
- pdf_style : commandes table Platypus
|
||||
- largeurs de colonnes pour PDF
|
||||
"""
|
||||
# UE à utiliser pour les poids (# colonne/UE)
|
||||
ue_infos = self.infos["ues"]
|
||||
ue_acros = list(
|
||||
[k for k in ue_infos if ue_infos[k]["type"] != UE_SPORT]
|
||||
) # ['RT1.1', 'RT2.1', 'RT3.1']
|
||||
# Colonnes à afficher:
|
||||
col_keys = ["titre"] + ue_acros + ["coef", "moyenne"]
|
||||
# Largeurs des colonnes:
|
||||
col_widths = {
|
||||
"titre": None,
|
||||
# "poids": None,
|
||||
"moyenne": 2 * cm,
|
||||
"coef": 2 * cm,
|
||||
}
|
||||
for ue_acro in ue_acros:
|
||||
col_widths[ue_acro] = 12 * mm # largeur col. poids
|
||||
|
||||
title_bg = tuple(x / 255.0 for x in title_bg)
|
||||
# elems pour générer table avec gen_table (liste de dicts)
|
||||
# Ligne de titres
|
||||
t = {
|
||||
"titre": title,
|
||||
# "_titre_colspan": 1 + len(ue_acros),
|
||||
"moyenne": "Note/20",
|
||||
"coef": "Coef.",
|
||||
"_coef_pdf": Paragraph("<para align=right><i>Coef.</i></para>"),
|
||||
"_css_row_class": "note_bold",
|
||||
"_pdf_row_markup": ["b"],
|
||||
"_pdf_style": [
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
("BOTTOMPADDING", (0, 0), (-1, 0), 7),
|
||||
(
|
||||
"LINEBELOW",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
blue,
|
||||
),
|
||||
],
|
||||
}
|
||||
for ue_acro in ue_acros:
|
||||
t[ue_acro] = Paragraph(
|
||||
f"<para align=right fontSize={self.small_fontsize}><i>{ue_acro}</i></para>"
|
||||
)
|
||||
rows = [t]
|
||||
for mod_code, mod in self.infos[mod_type].items():
|
||||
# 1er ligne titre module
|
||||
t = {
|
||||
"titre": f"{mod_code} - {mod['titre']}",
|
||||
"_titre_colspan": 2 + len(ue_acros),
|
||||
"_css_row_class": "note_bold",
|
||||
"_pdf_row_markup": ["b"],
|
||||
"_pdf_style": [
|
||||
(
|
||||
"LINEABOVE",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
self.PDF_LINECOLOR,
|
||||
),
|
||||
("BACKGROUND", (0, 0), (-1, 0), title_bg),
|
||||
("BOTTOMPADDING", (0, 0), (-1, 0), 7),
|
||||
],
|
||||
}
|
||||
rows.append(t)
|
||||
# Evaluations:
|
||||
self.evaluations_rows(rows, mod["evaluations"], ue_acros)
|
||||
|
||||
# Global pdf style commands:
|
||||
pdf_style = [
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
("BOX", (0, 0), (-1, -1), 0.4, blue), # ajoute cadre extérieur bleu:
|
||||
]
|
||||
return col_keys, rows, pdf_style, col_widths
|
||||
|
||||
def evaluations_rows(self, rows, evaluations, ue_acros=()):
|
||||
"lignes des évaluations"
|
||||
for e in evaluations:
|
||||
t = {
|
||||
"titre": f"{e['description']}",
|
||||
"moyenne": e["note"]["value"],
|
||||
"_moyenne_pdf": Paragraph(
|
||||
f"""<para align=right>{e["note"]["value"]}</para>"""
|
||||
),
|
||||
"coef": e["coef"],
|
||||
"_coef_pdf": Paragraph(
|
||||
f"<para align=right fontSize={self.small_fontsize}><i>{e['coef']}</i></para>"
|
||||
),
|
||||
"_pdf_style": [
|
||||
(
|
||||
"LINEBELOW",
|
||||
(0, 0),
|
||||
(-1, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
(0.7, 0.7, 0.7), # gris clair
|
||||
)
|
||||
],
|
||||
}
|
||||
col_idx = 1 # 1ere col. poids
|
||||
for ue_acro in ue_acros:
|
||||
t[ue_acro] = Paragraph(
|
||||
f"""<para align=right fontSize={self.small_fontsize}><i>{
|
||||
e["poids"].get(ue_acro, "") or ""}</i></para>"""
|
||||
)
|
||||
t["_pdf_style"].append(
|
||||
(
|
||||
"BOX",
|
||||
(col_idx, 0),
|
||||
(col_idx, 0),
|
||||
self.PDF_LINEWIDTH,
|
||||
(0.7, 0.7, 0.7), # gris clair
|
||||
),
|
||||
)
|
||||
col_idx += 1
|
||||
rows.append(t)
|
|
@ -69,10 +69,11 @@ def bulletin_but_xml_compat(
|
|||
% (formsemestre_id, etudid)
|
||||
)
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
etud = Identite.query.get_or_404(etudid)
|
||||
etud: Identite = Identite.query.get_or_404(etudid)
|
||||
results = bulletin_but.ResultatsSemestreBUT(formsemestre)
|
||||
nb_inscrits = len(results.etuds)
|
||||
etat_inscription = etud.etat_inscription(formsemestre.id)
|
||||
nb_inscrits = results.get_inscriptions_counts()[scu.INSCRIT]
|
||||
# etat_inscription = etud.inscription_etat(formsemestre.id)
|
||||
etat_inscription = results.formsemestre.etuds_inscriptions[etudid].etat
|
||||
if (not formsemestre.bul_hide_xml) or force_publishing:
|
||||
published = 1
|
||||
else:
|
||||
|
@ -109,8 +110,8 @@ def bulletin_but_xml_compat(
|
|||
code_ine=etud.code_ine or "",
|
||||
nom=scu.quote_xml_attr(etud.nom),
|
||||
prenom=scu.quote_xml_attr(etud.prenom),
|
||||
civilite=scu.quote_xml_attr(etud.civilite_str()),
|
||||
sexe=scu.quote_xml_attr(etud.civilite_str()), # compat
|
||||
civilite=scu.quote_xml_attr(etud.civilite_str),
|
||||
sexe=scu.quote_xml_attr(etud.civilite_str), # compat
|
||||
photo_url=scu.quote_xml_attr(sco_photos.get_etud_photo_url(etud.id)),
|
||||
email=scu.quote_xml_attr(etud.get_first_email() or ""),
|
||||
emailperso=scu.quote_xml_attr(etud.get_first_email("emailperso") or ""),
|
||||
|
@ -133,14 +134,18 @@ def bulletin_but_xml_compat(
|
|||
moy=scu.fmt_note(results.etud_moy_gen.mean()), # moyenne des moy. gen.
|
||||
)
|
||||
)
|
||||
rang = 0 # XXX TODO rang de l'étduiant selon la moy gen indicative
|
||||
bonus = 0 # XXX TODO valeur du bonus sport
|
||||
rang = 0 # XXX TODO rang de l'étudiant selon la moy gen indicative
|
||||
# valeur du bonus sport
|
||||
if results.bonus is not None:
|
||||
bonus = results.bonus[etud.id]
|
||||
else:
|
||||
bonus = 0
|
||||
doc.append(Element("rang", value=str(rang), ninscrits=str(nb_inscrits)))
|
||||
# XXX TODO: ajouter "rang_group" : rangs dans les partitions
|
||||
doc.append(Element("note_max", value="20")) # notes toujours sur 20
|
||||
doc.append(Element("bonus_sport_culture", value=str(bonus)))
|
||||
# Liste les UE / modules /evals
|
||||
for ue in results.ues:
|
||||
for ue in results.ues: # avec bonus
|
||||
rang_ue = 0 # XXX TODO rang de l'étudiant dans cette UE
|
||||
nb_inscrits_ue = (
|
||||
nb_inscrits # approx: compliqué de définir le "nb d'inscrit à une UE"
|
||||
|
@ -156,25 +161,31 @@ def bulletin_but_xml_compat(
|
|||
doc.append(x_ue)
|
||||
if ue.type != sco_codes_parcours.UE_SPORT:
|
||||
v = results.etud_moy_ue[ue.id][etud.id]
|
||||
vmin = results.etud_moy_ue[ue.id].min()
|
||||
vmax = results.etud_moy_ue[ue.id].max()
|
||||
else:
|
||||
v = 0 # XXX TODO valeur bonus sport pour cet étudiant
|
||||
v = results.bonus or 0.0
|
||||
vmin = vmax = 0.0
|
||||
x_ue.append(
|
||||
Element(
|
||||
"note",
|
||||
value=scu.fmt_note(v),
|
||||
min=scu.fmt_note(results.etud_moy_ue[ue.id].min()),
|
||||
max=scu.fmt_note(results.etud_moy_ue[ue.id].max()),
|
||||
min=scu.fmt_note(vmin),
|
||||
max=scu.fmt_note(vmax),
|
||||
)
|
||||
)
|
||||
x_ue.append(Element("ects", value=str(ue.ects if ue.ects else 0)))
|
||||
x_ue.append(Element("rang", value=str(rang_ue)))
|
||||
x_ue.append(Element("effectif", value=str(nb_inscrits_ue)))
|
||||
# Liste les modules rattachés à cette UE
|
||||
for modimpl in results.modimpls:
|
||||
for modimpl in results.formsemestre.modimpls:
|
||||
# Liste ici uniquement les modules rattachés à cette UE
|
||||
if modimpl.module.ue.id == ue.id:
|
||||
mod_moy = scu.fmt_note(results.etud_moy_ue[ue.id][etud.id])
|
||||
coef = results.modimpl_coefs_df[modimpl.id][ue.id]
|
||||
# mod_moy = scu.fmt_note(results.etud_moy_ue[ue.id][etud.id])
|
||||
try:
|
||||
coef = results.modimpl_coefs_df[modimpl.id][ue.id]
|
||||
except KeyError:
|
||||
coef = 0.0
|
||||
x_mod = Element(
|
||||
"module",
|
||||
id=str(modimpl.id),
|
||||
|
@ -187,16 +198,6 @@ def bulletin_but_xml_compat(
|
|||
modimpl.module.code_apogee or ""
|
||||
),
|
||||
)
|
||||
x_ue.append(x_mod)
|
||||
x_mod.append(
|
||||
Element(
|
||||
"note",
|
||||
value=mod_moy,
|
||||
min=scu.fmt_note(results.etud_moy_ue[ue.id].min()),
|
||||
max=scu.fmt_note(results.etud_moy_ue[ue.id].max()),
|
||||
moy=scu.fmt_note(results.etud_moy_ue[ue.id].mean()),
|
||||
)
|
||||
)
|
||||
# XXX TODO rangs et effectifs
|
||||
# --- notes de chaque eval:
|
||||
if version != "short":
|
||||
|
@ -219,17 +220,23 @@ def bulletin_but_xml_compat(
|
|||
note_max_origin=str(e.note_max),
|
||||
)
|
||||
x_mod.append(x_eval)
|
||||
x_eval.append(
|
||||
Element(
|
||||
"note",
|
||||
value=scu.fmt_note(
|
||||
results.modimpls_evals_notes[
|
||||
e.moduleimpl_id
|
||||
][e.id][etud.id],
|
||||
note_max=e.note_max,
|
||||
),
|
||||
try:
|
||||
x_eval.append(
|
||||
Element(
|
||||
"note",
|
||||
value=scu.fmt_note(
|
||||
results.modimpls_results[
|
||||
e.moduleimpl_id
|
||||
].evals_notes[e.id][etud.id],
|
||||
note_max=e.note_max,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
except KeyError:
|
||||
x_eval.append(
|
||||
Element("note", value="", note_max="")
|
||||
)
|
||||
|
||||
# XXX TODO: Evaluations incomplètes ou futures: XXX
|
||||
# XXX TODO UE capitalisee (listee seulement si meilleure que l'UE courante)
|
||||
|
||||
|
@ -322,13 +329,3 @@ def bulletin_but_xml_compat(
|
|||
return None
|
||||
else:
|
||||
return sco_xml.XML_HEADER + ElementTree.tostring(doc).decode(scu.SCO_ENCODING)
|
||||
|
||||
|
||||
"""
|
||||
formsemestre_id=718
|
||||
etudid=12496
|
||||
from app.but.bulletin_but import *
|
||||
mapp.set_sco_dept("RT")
|
||||
sem = FormSemestre.query.get(formsemestre_id)
|
||||
r = ResultatsSemestreBUT(sem)
|
||||
"""
|
||||
|
|
|
@ -19,10 +19,12 @@ class FormationRefCompForm(FlaskForm):
|
|||
|
||||
|
||||
class RefCompLoadForm(FlaskForm):
|
||||
referentiel_standard = SelectField(
|
||||
"Choisir un référentiel de compétences officiel BUT"
|
||||
)
|
||||
upload = FileField(
|
||||
label="Sélectionner un fichier XML Orébut",
|
||||
label="Ou bien sélectionner un fichier XML au format Orébut",
|
||||
validators=[
|
||||
FileRequired(),
|
||||
FileAllowed(
|
||||
[
|
||||
"xml",
|
||||
|
@ -33,3 +35,13 @@ class RefCompLoadForm(FlaskForm):
|
|||
)
|
||||
submit = SubmitField("Valider")
|
||||
cancel = SubmitField("Annuler")
|
||||
|
||||
def validate(self):
|
||||
if not super().validate():
|
||||
return False
|
||||
if (self.referentiel_standard.data == "0") == (not self.upload.data):
|
||||
self.referentiel_standard.errors.append(
|
||||
"Choisir soit un référentiel, soit un fichier xml"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
|
|
@ -6,6 +6,8 @@
|
|||
from xml.etree import ElementTree
|
||||
from typing import TextIO
|
||||
|
||||
import sqlalchemy
|
||||
|
||||
from app import db
|
||||
|
||||
from app.models.but_refcomp import (
|
||||
|
@ -19,7 +21,7 @@ from app.models.but_refcomp import (
|
|||
ApcAnneeParcours,
|
||||
ApcParcoursNiveauCompetence,
|
||||
)
|
||||
from app.scodoc.sco_exceptions import ScoFormatError
|
||||
from app.scodoc.sco_exceptions import ScoFormatError, ScoValueError
|
||||
|
||||
|
||||
def orebut_import_refcomp(xml_data: str, dept_id: int, orig_filename=None):
|
||||
|
@ -27,10 +29,20 @@ def orebut_import_refcomp(xml_data: str, dept_id: int, orig_filename=None):
|
|||
peut lever TypeError ou ScoFormatError
|
||||
Résultat: instance de ApcReferentielCompetences
|
||||
"""
|
||||
# Vérifie que le même fichier n'a pas déjà été chargé:
|
||||
if ApcReferentielCompetences.query.filter_by(
|
||||
scodoc_orig_filename=orig_filename, dept_id=dept_id
|
||||
).count():
|
||||
raise ScoValueError(
|
||||
f"""Un référentiel a déjà été chargé d'un fichier de même nom.
|
||||
({orig_filename})
|
||||
Supprimez-le ou changer le nom du fichier."""
|
||||
)
|
||||
|
||||
try:
|
||||
root = ElementTree.XML(xml_data)
|
||||
except ElementTree.ParseError:
|
||||
raise ScoFormatError("fichier XML Orébut invalide")
|
||||
except ElementTree.ParseError as exc:
|
||||
raise ScoFormatError(f"fichier XML Orébut invalide (2): {exc.args}")
|
||||
if root.tag != "referentiel_competence":
|
||||
raise ScoFormatError("élément racine 'referentiel_competence' manquant")
|
||||
args = ApcReferentielCompetences.attr_from_xml(root.attrib)
|
||||
|
@ -42,7 +54,16 @@ def orebut_import_refcomp(xml_data: str, dept_id: int, orig_filename=None):
|
|||
if not competences:
|
||||
raise ScoFormatError("élément 'competences' manquant")
|
||||
for competence in competences.findall("competence"):
|
||||
c = ApcCompetence(**ApcCompetence.attr_from_xml(competence.attrib))
|
||||
try:
|
||||
c = ApcCompetence(**ApcCompetence.attr_from_xml(competence.attrib))
|
||||
db.session.flush()
|
||||
except sqlalchemy.exc.IntegrityError:
|
||||
# ne devrait plus se produire car pas d'unicité de l'id: donc inutile
|
||||
db.session.rollback()
|
||||
raise ScoValueError(
|
||||
f"""Un référentiel a déjà été chargé avec les mêmes compétences ! ({competence.attrib["id"]})
|
||||
"""
|
||||
)
|
||||
ref.competences.append(c)
|
||||
# --- SITUATIONS
|
||||
situations = competence.find("situations")
|
||||
|
@ -54,8 +75,8 @@ def orebut_import_refcomp(xml_data: str, dept_id: int, orig_filename=None):
|
|||
composantes = competence.find("composantes_essentielles")
|
||||
for composante in composantes:
|
||||
libelle = "".join(composante.itertext()).strip()
|
||||
ce = ApcComposanteEssentielle(libelle=libelle)
|
||||
c.composantes_essentielles.append(ce)
|
||||
compo_ess = ApcComposanteEssentielle(libelle=libelle)
|
||||
c.composantes_essentielles.append(compo_ess)
|
||||
# --- NIVEAUX (années)
|
||||
niveaux = competence.find("niveaux")
|
||||
for niveau in niveaux:
|
||||
|
@ -77,16 +98,14 @@ def orebut_import_refcomp(xml_data: str, dept_id: int, orig_filename=None):
|
|||
a = ApcAnneeParcours(**ApcAnneeParcours.attr_from_xml(annee.attrib))
|
||||
parc.annees.append(a)
|
||||
for competence in annee.findall("competence"):
|
||||
nom = competence.attrib["nom"]
|
||||
comp_id_orebut = competence.attrib["id"]
|
||||
niveau = int(competence.attrib["niveau"])
|
||||
# Retrouve la competence
|
||||
comp = ref.competences.filter_by(titre=nom).all()
|
||||
if len(comp) == 0:
|
||||
raise ScoFormatError(f"competence {nom} référencée mais on définie")
|
||||
elif len(comp) > 1:
|
||||
raise ScoFormatError(f"competence {nom} ambigüe")
|
||||
comp = ref.competences.filter_by(id_orebut=comp_id_orebut).first()
|
||||
if comp is None:
|
||||
raise ScoFormatError(f"competence {comp_id_orebut} non définie")
|
||||
ass = ApcParcoursNiveauCompetence(
|
||||
niveau=niveau, annee_parcours=a, competence=comp[0]
|
||||
niveau=niveau, annee_parcours=a, competence=comp
|
||||
)
|
||||
db.session.add(ass)
|
||||
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
# empty but required for pylint
|
|
@ -0,0 +1,44 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Quelques classes auxiliaires pour les calculs des notes
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class StatsMoyenne:
|
||||
"""Une moyenne d'un ensemble étudiants sur quelque chose
|
||||
(moyenne générale d'un semestre, d'un module, d'un groupe...)
|
||||
et les statistiques associées: min, max, moy, effectif
|
||||
"""
|
||||
|
||||
def __init__(self, vals):
|
||||
"""Calcul les statistiques.
|
||||
Les valeurs NAN ou non numériques sont toujours enlevées.
|
||||
Si vals is None, renvoie des zéros (utilisé pour UE bonus)
|
||||
"""
|
||||
try:
|
||||
if vals is None or len(vals) == 0 or np.isnan(vals).all():
|
||||
self.moy = self.min = self.max = self.size = self.nb_vals = 0
|
||||
else:
|
||||
self.moy = np.nanmean(vals)
|
||||
self.min = np.nanmin(vals)
|
||||
self.max = np.nanmax(vals)
|
||||
self.size = len(vals)
|
||||
self.nb_vals = self.size - np.count_nonzero(np.isnan(vals))
|
||||
except TypeError: # que des NaN dans un array d'objets, ou ce genre de choses exotiques...
|
||||
self.moy = self.min = self.max = self.size = self.nb_vals = 0
|
||||
|
||||
def to_dict(self):
|
||||
"Tous les attributs dans un dict"
|
||||
return {
|
||||
"min": self.min,
|
||||
"max": self.max,
|
||||
"moy": self.moy,
|
||||
"size": self.size,
|
||||
"nb_vals": self.nb_vals,
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -43,7 +43,7 @@ class ModuleCoefsCache(sco_cache.ScoDocCache):
|
|||
class EvaluationsPoidsCache(sco_cache.ScoDocCache):
|
||||
"""Cache for poids evals
|
||||
Clé: moduleimpl_id
|
||||
Valeur: DataFrame (df_load_evaluations_poids)
|
||||
Valeur: DataFrame (load_evaluations_poids)
|
||||
"""
|
||||
|
||||
prefix = "EPC"
|
||||
|
|
|
@ -3,11 +3,9 @@
|
|||
|
||||
"""Matrices d'inscription aux modules d'un semestre
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from app import db
|
||||
from app import models
|
||||
|
||||
#
|
||||
# Le chargement des inscriptions est long: matrice nb_module x nb_etuds
|
||||
|
@ -16,13 +14,13 @@ from app import models
|
|||
#
|
||||
def df_load_modimpl_inscr(formsemestre) -> pd.DataFrame:
|
||||
"""Charge la matrice des inscriptions aux modules du semestre
|
||||
rows: etudid
|
||||
columns: moduleimpl_id (en chaîne)
|
||||
rows: etudid (inscrits au semestre, avec DEM et DEF)
|
||||
columns: moduleimpl_id
|
||||
value: bool (0/1 inscrit ou pas)
|
||||
"""
|
||||
# méthode la moins lente: une requete par module, merge les dataframes
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls]
|
||||
etudids = [i.etudid for i in formsemestre.get_inscrits(include_dem=False)]
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls_sorted]
|
||||
etudids = [inscr.etudid for inscr in formsemestre.inscriptions]
|
||||
df = pd.DataFrame(index=etudids, dtype=int)
|
||||
for moduleimpl_id in moduleimpl_ids:
|
||||
ins_df = pd.read_sql_query(
|
||||
|
@ -35,6 +33,8 @@ def df_load_modimpl_inscr(formsemestre) -> pd.DataFrame:
|
|||
dtype=int,
|
||||
)
|
||||
df = df.merge(ins_df, how="left", left_index=True, right_index=True)
|
||||
# Force columns names to integers (moduleimpl ids)
|
||||
df.columns = pd.Int64Index([int(x) for x in df.columns], dtype="int")
|
||||
# les colonnes de df sont en float (Nan) quand il n'y a
|
||||
# aucun inscrit au module.
|
||||
df.fillna(0, inplace=True) # les non-inscrits
|
||||
|
@ -47,10 +47,10 @@ def df_load_modimpl_inscr(formsemestre) -> pd.DataFrame:
|
|||
|
||||
def df_load_modimpl_inscr_v0(formsemestre):
|
||||
# methode 0, pur SQL Alchemy, 1.5 à 2 fois plus lente
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls]
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls_sorted]
|
||||
etudids = [i.etudid for i in formsemestre.inscriptions]
|
||||
df = pd.DataFrame(False, columns=moduleimpl_ids, index=etudids, dtype=bool)
|
||||
for modimpl in formsemestre.modimpls:
|
||||
for modimpl in formsemestre.modimpls_sorted:
|
||||
ins_mod = df[modimpl.id]
|
||||
for inscr in modimpl.inscriptions:
|
||||
ins_mod[inscr.etudid] = True
|
||||
|
@ -58,7 +58,7 @@ def df_load_modimpl_inscr_v0(formsemestre):
|
|||
|
||||
|
||||
def df_load_modimpl_inscr_v2(formsemestre):
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls]
|
||||
moduleimpl_ids = [m.id for m in formsemestre.modimpls_sorted]
|
||||
etudids = [i.etudid for i in formsemestre.inscriptions]
|
||||
df = pd.DataFrame(False, columns=moduleimpl_ids, index=etudids, dtype=bool)
|
||||
cursor = db.engine.execute(
|
||||
|
|
|
@ -0,0 +1,154 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Stockage des décisions de jury
|
||||
"""
|
||||
import pandas as pd
|
||||
|
||||
from app import db
|
||||
from app.models import FormSemestre, ScolarFormSemestreValidation
|
||||
from app.comp.res_cache import ResultatsCache
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_codes_parcours
|
||||
|
||||
|
||||
class ValidationsSemestre(ResultatsCache):
|
||||
"""Les décisions de jury pour un semestre"""
|
||||
|
||||
_cached_attrs = (
|
||||
"decisions_jury",
|
||||
"decisions_jury_ues",
|
||||
"ue_capitalisees",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre: FormSemestre):
|
||||
super().__init__(formsemestre, sco_cache.ValidationsSemestreCache)
|
||||
|
||||
self.decisions_jury = {}
|
||||
"""Décisions prises dans ce semestre:
|
||||
{ etudid : { 'code' : None|ATT|..., 'assidu' : 0|1 }}"""
|
||||
self.decisions_jury_ues = {}
|
||||
"""Décisions sur des UEs dans ce semestre:
|
||||
{ etudid : { ue_id : { 'code' : Note|ADM|CMP, 'event_date' }}}
|
||||
"""
|
||||
self.ue_capitalisees: pd.DataFrame = None
|
||||
"""DataFrame, index etudid
|
||||
formsemestre_id : origine de l'UE capitalisée
|
||||
is_external : vrai si validation effectuée dans un semestre extérieur
|
||||
ue_id : dans le semestre origine (pas toujours de la même formation)
|
||||
ue_code : code de l'UE, moy_ue : note enregistrée,
|
||||
event_date : date de la validation (jury)."""
|
||||
|
||||
if not self.load_cached():
|
||||
self.compute()
|
||||
self.store()
|
||||
|
||||
def compute(self):
|
||||
"Charge les résultats de jury et UEs capitalisées"
|
||||
self.ue_capitalisees = formsemestre_get_ue_capitalisees(self.formsemestre)
|
||||
self.comp_decisions_jury()
|
||||
|
||||
def comp_decisions_jury(self):
|
||||
"""Cherche les decisions du jury pour le semestre (pas les UE).
|
||||
Calcule les attributs:
|
||||
decisions_jury = { etudid : { 'code' : None|ATT|..., 'assidu' : 0|1 }}
|
||||
decision_jury_ues={ etudid : { ue_id : { 'code' : Note|ADM|CMP, 'event_date' }}}
|
||||
Si la décision n'a pas été prise, la clé etudid n'est pas présente.
|
||||
Si l'étudiant est défaillant, pas de décisions d'UE.
|
||||
"""
|
||||
# repris de NotesTable.comp_decisions_jury pour la compatibilité
|
||||
decisions_jury_q = ScolarFormSemestreValidation.query.filter_by(
|
||||
formsemestre_id=self.formsemestre.id
|
||||
)
|
||||
decisions_jury = {}
|
||||
for decision in decisions_jury_q.filter(
|
||||
ScolarFormSemestreValidation.ue_id == None # slt dec. sem.
|
||||
):
|
||||
decisions_jury[decision.etudid] = {
|
||||
"code": decision.code,
|
||||
"assidu": decision.assidu,
|
||||
"compense_formsemestre_id": decision.compense_formsemestre_id,
|
||||
"event_date": decision.event_date.strftime("%d/%m/%Y"),
|
||||
}
|
||||
self.decisions_jury = decisions_jury
|
||||
|
||||
# UEs:
|
||||
decisions_jury_ues = {}
|
||||
for decision in decisions_jury_q.filter(
|
||||
ScolarFormSemestreValidation.ue_id != None # slt dec. sem.
|
||||
):
|
||||
if decision.etudid not in decisions_jury_ues:
|
||||
decisions_jury_ues[decision.etudid] = {}
|
||||
# Calcul des ECTS associés à cette UE:
|
||||
if sco_codes_parcours.code_ue_validant(decision.code):
|
||||
ects = decision.ue.ects or 0.0 # 0 if None
|
||||
else:
|
||||
ects = 0.0
|
||||
|
||||
decisions_jury_ues[decision.etudid][decision.ue.id] = {
|
||||
"code": decision.code,
|
||||
"ects": ects, # 0. si UE non validée
|
||||
"event_date": decision.event_date.strftime("%d/%m/%Y"),
|
||||
}
|
||||
|
||||
self.decisions_jury_ues = decisions_jury_ues
|
||||
|
||||
|
||||
def formsemestre_get_ue_capitalisees(formsemestre: FormSemestre) -> pd.DataFrame:
|
||||
"""Liste des UE capitalisées (ADM) utilisables dans ce formsemestre
|
||||
|
||||
Recherche dans les semestres des formations de même code, avec le même semestre_id
|
||||
et une date de début antérieure que celle du formsemestre.
|
||||
Prend aussi les UE externes validées.
|
||||
|
||||
Attention: fonction très coûteuse, cacher le résultat.
|
||||
|
||||
Résultat: DataFrame avec
|
||||
etudid (index)
|
||||
formsemestre_id : origine de l'UE capitalisée
|
||||
is_external : vrai si validation effectuée dans un semestre extérieur
|
||||
ue_id : dans le semestre origine (pas toujours de la même formation)
|
||||
ue_code : code de l'UE
|
||||
moy_ue :
|
||||
event_date :
|
||||
} ]
|
||||
"""
|
||||
query = """
|
||||
SELECT DISTINCT SFV.*, ue.ue_code
|
||||
FROM
|
||||
notes_ue ue,
|
||||
notes_formations nf,
|
||||
notes_formations nf2,
|
||||
scolar_formsemestre_validation SFV,
|
||||
notes_formsemestre sem,
|
||||
notes_formsemestre_inscription ins
|
||||
|
||||
WHERE ue.formation_id = nf.id
|
||||
and nf.formation_code = nf2.formation_code
|
||||
and nf2.id=%(formation_id)s
|
||||
and ins.etudid = SFV.etudid
|
||||
and ins.formsemestre_id = %(formsemestre_id)s
|
||||
|
||||
and SFV.ue_id = ue.id
|
||||
and SFV.code = 'ADM'
|
||||
|
||||
and ( (sem.id = SFV.formsemestre_id
|
||||
and sem.date_debut < %(date_debut)s
|
||||
and sem.semestre_id = %(semestre_id)s )
|
||||
or (
|
||||
((SFV.formsemestre_id is NULL) OR (SFV.is_external)) -- les UE externes ou "anterieures"
|
||||
AND (SFV.semestre_id is NULL OR SFV.semestre_id=%(semestre_id)s)
|
||||
) )
|
||||
"""
|
||||
params = {
|
||||
"formation_id": formsemestre.formation.id,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"semestre_id": formsemestre.semestre_id,
|
||||
"date_debut": formsemestre.date_debut,
|
||||
}
|
||||
|
||||
df = pd.read_sql_query(query, db.engine, params=params, index_col="etudid")
|
||||
return df
|
|
@ -0,0 +1,50 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Calcul des moyennes de matières
|
||||
"""
|
||||
|
||||
# C'est un recalcul (optionnel) effectué _après_ le calcul standard.
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from app.comp import moy_ue
|
||||
from app.models.formsemestre import FormSemestre
|
||||
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
def compute_mat_moys_classic(
|
||||
formsemestre: FormSemestre,
|
||||
sem_matrix: np.array,
|
||||
ues: list,
|
||||
modimpl_inscr_df: pd.DataFrame,
|
||||
modimpl_coefs: np.array,
|
||||
) -> dict:
|
||||
"""Calcul des moyennes par matières.
|
||||
Result: dict, { matiere_id : Series, index etudid }
|
||||
"""
|
||||
modimpls_std = [
|
||||
m
|
||||
for m in formsemestre.modimpls_sorted
|
||||
if (m.module.module_type == ModuleType.STANDARD)
|
||||
and (m.module.ue.type != UE_SPORT)
|
||||
]
|
||||
matiere_ids = {m.module.matiere.id for m in modimpls_std}
|
||||
matiere_moy = {} # { matiere_id : moy pd.Series, index etudid }
|
||||
for matiere_id in matiere_ids:
|
||||
modimpl_mask = np.array(
|
||||
[m.module.matiere.id == matiere_id for m in formsemestre.modimpls_sorted]
|
||||
)
|
||||
etud_moy_mat = moy_ue.compute_mat_moys_classic(
|
||||
sem_matrix=sem_matrix,
|
||||
modimpl_inscr_df=modimpl_inscr_df,
|
||||
modimpl_coefs=modimpl_coefs,
|
||||
modimpl_mask=modimpl_mask,
|
||||
)
|
||||
matiere_moy[matiere_id] = etud_moy_mat
|
||||
return matiere_moy
|
|
@ -27,128 +27,160 @@
|
|||
|
||||
"""Fonctions de calcul des moyennes de modules (modules, ressources ou SAÉ)
|
||||
|
||||
Pour les formations classiques et le BUT
|
||||
|
||||
Rappel: pour éviter les confusions, on appelera *poids* les coefficients d'une
|
||||
évaluation dans un module, et *coefficients* ceux utilisés pour le calcul de la
|
||||
moyenne générale d'une UE.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas.core.frame import DataFrame
|
||||
|
||||
from app import db
|
||||
from app import log
|
||||
from app import models
|
||||
from app.models import ModuleImpl, Evaluation, EvaluationUEPoids
|
||||
from app.scodoc import sco_utils as scu
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
def df_load_evaluations_poids(
|
||||
moduleimpl_id: int, default_poids=1.0
|
||||
) -> tuple[pd.DataFrame, list]:
|
||||
"""Charge poids des évaluations d'un module et retourne un dataframe
|
||||
rows = evaluations, columns = UE, value = poids (float).
|
||||
Les valeurs manquantes (évaluations sans coef vers des UE) sont
|
||||
remplies par default_poids.
|
||||
Résultat: (evals_poids, liste de UE du semestre)
|
||||
@dataclass
|
||||
class EvaluationEtat:
|
||||
"""Classe pour stocker quelques infos sur les résultats d'une évaluation"""
|
||||
|
||||
evaluation_id: int
|
||||
nb_attente: int
|
||||
is_complete: bool
|
||||
|
||||
|
||||
class ModuleImplResults:
|
||||
"""Classe commune à toutes les formations (standard et APC).
|
||||
Les notes des étudiants d'un moduleimpl.
|
||||
Les poids des évals sont à part car on en a besoin sans les notes pour les
|
||||
tableaux de bord.
|
||||
Les attributs sont tous des objets simples cachables dans Redis;
|
||||
les caches sont gérés par ResultatsSemestre.
|
||||
"""
|
||||
modimpl = ModuleImpl.query.get(moduleimpl_id)
|
||||
evaluations = Evaluation.query.filter_by(moduleimpl_id=moduleimpl_id).all()
|
||||
ues = modimpl.formsemestre.query_ues(with_sport=False).all()
|
||||
ue_ids = [ue.id for ue in ues]
|
||||
evaluation_ids = [evaluation.id for evaluation in evaluations]
|
||||
df = pd.DataFrame(columns=ue_ids, index=evaluation_ids, dtype=float)
|
||||
for eval_poids in EvaluationUEPoids.query.join(
|
||||
EvaluationUEPoids.evaluation
|
||||
).filter_by(moduleimpl_id=moduleimpl_id):
|
||||
try:
|
||||
df[eval_poids.ue_id][eval_poids.evaluation_id] = eval_poids.poids
|
||||
except KeyError as exc:
|
||||
pass # poids vers des UE qui n'existent plus ou sont dans un autre semestre...
|
||||
if default_poids is not None:
|
||||
df.fillna(value=default_poids, inplace=True)
|
||||
return df, ues
|
||||
|
||||
def __init__(self, moduleimpl: ModuleImpl):
|
||||
self.moduleimpl_id = moduleimpl.id
|
||||
self.module_id = moduleimpl.module.id
|
||||
self.etudids = None
|
||||
"liste des étudiants inscrits au SEMESTRE (incluant dem et def)"
|
||||
|
||||
def check_moduleimpl_conformity(
|
||||
moduleimpl, evals_poids: pd.DataFrame, modules_coefficients: pd.DataFrame
|
||||
) -> bool:
|
||||
"""Vérifie que les évaluations de ce moduleimpl sont bien conformes
|
||||
au PN.
|
||||
Un module est dit *conforme* si et seulement si la somme des poids de ses
|
||||
évaluations vers une UE de coefficient non nul est non nulle.
|
||||
"""
|
||||
nb_evals, nb_ues = evals_poids.shape
|
||||
if nb_evals == 0:
|
||||
return True # modules vides conformes
|
||||
if nb_ues == 0:
|
||||
return False # situation absurde (pas d'UE)
|
||||
if len(modules_coefficients) != nb_ues:
|
||||
# bug ?
|
||||
log(
|
||||
"check_moduleimpl_conformity: nb ue incoherent (moduleimpl.id={moduleimpl.id})"
|
||||
)
|
||||
return False
|
||||
module_evals_poids = evals_poids.transpose().sum(axis=1).to_numpy() != 0
|
||||
check = all(
|
||||
(modules_coefficients[moduleimpl.module.id].to_numpy() != 0)
|
||||
== module_evals_poids
|
||||
)
|
||||
return check
|
||||
self.nb_inscrits_module = None
|
||||
"nombre d'inscrits (non DEM) à ce module"
|
||||
self.evaluations_completes = []
|
||||
"séquence de booléens, indiquant les évals à prendre en compte."
|
||||
self.evaluations_completes_dict = {}
|
||||
"{ evaluation.id : bool } indique si à prendre en compte ou non."
|
||||
self.evaluations_etat = {}
|
||||
"{ evaluation_id: EvaluationEtat }"
|
||||
self.en_attente = False
|
||||
"Vrai si au moins une évaluation a une note en attente"
|
||||
#
|
||||
self.evals_notes = None
|
||||
"""DataFrame, colonnes: EVALS, Lignes: etudid (inscrits au SEMESTRE)
|
||||
valeur: notes brutes, float ou NOTES_ATTENTE, NOTES_NEUTRALISE,
|
||||
NOTES_ABSENCE.
|
||||
Les NaN désignent les notes manquantes (non saisies).
|
||||
"""
|
||||
self.etuds_moy_module = None
|
||||
"""DataFrame, colonnes UE, lignes etud
|
||||
= la note de l'étudiant dans chaque UE pour ce module.
|
||||
ou NaN si les évaluations (dans lesquelles l'étudiant a des notes)
|
||||
ne donnent pas de coef vers cette UE.
|
||||
"""
|
||||
self.load_notes()
|
||||
self.etuds_use_session2 = pd.Series(False, index=self.evals_notes.index)
|
||||
"""1 bool par etud, indique si sa moyenne de module vient de la session2"""
|
||||
self.etuds_use_rattrapage = pd.Series(False, index=self.evals_notes.index)
|
||||
"""1 bool par etud, indique si sa moyenne de module utilise la note de rattrapage"""
|
||||
|
||||
def load_notes(self): # ré-écriture de df_load_modimpl_notes
|
||||
"""Charge toutes les notes de toutes les évaluations du module.
|
||||
Dataframe evals_notes
|
||||
colonnes: le nom de la colonne est l'evaluation_id (int)
|
||||
index (lignes): etudid (int)
|
||||
|
||||
def df_load_modimpl_notes(moduleimpl_id: int) -> tuple:
|
||||
"""Construit un dataframe avec toutes les notes de toutes les évaluations du module.
|
||||
colonnes: le nom de la colonne est l'evaluation_id (int)
|
||||
index (lignes): etudid (int)
|
||||
L'ensemble des étudiants est celui des inscrits au SEMESTRE.
|
||||
|
||||
Résultat: (evals_notes, liste de évaluations du moduleimpl,
|
||||
liste de booleens indiquant si l'évaluation est "complete")
|
||||
Les notes sont "brutes" (séries de floats) et peuvent prendre les valeurs:
|
||||
note : float (valeur enregistrée brute, NON normalisée sur 20)
|
||||
pas de note: NaN (rien en bd, ou étudiant non inscrit au module)
|
||||
absent: NOTES_ABSENCE (NULL en bd)
|
||||
excusé: NOTES_NEUTRALISE (voir sco_utils)
|
||||
attente: NOTES_ATTENTE
|
||||
|
||||
L'ensemble des étudiants est celui des inscrits au SEMESTRE.
|
||||
Évaluation "complete" (prise en compte dans les calculs) si:
|
||||
- soit tous les étudiants inscrits au module ont des notes
|
||||
- soit elle a été déclarée "à prise en compte immédiate" (publish_incomplete)
|
||||
|
||||
Les notes renvoyées sont "brutes" (séries de floats) et peuvent prendre les valeurs:
|
||||
note : float (valeur enregistrée brute, non normalisée sur 20)
|
||||
pas de note: NaN (rien en bd, ou étudiant non inscrit au module)
|
||||
absent: NOTES_ABSENCE (NULL en bd)
|
||||
excusé: NOTES_NEUTRALISE (voir sco_utils)
|
||||
attente: NOTES_ATTENTE
|
||||
Évaluation "attente" (prise en compte dans les calculs, mais il y
|
||||
manque des notes) ssi il y a des étudiants inscrits au semestre et au module
|
||||
qui ont des notes ATT.
|
||||
"""
|
||||
moduleimpl = ModuleImpl.query.get(self.moduleimpl_id)
|
||||
self.etudids = self._etudids()
|
||||
|
||||
L'évaluation "complete" (prise en compte dans les calculs) si:
|
||||
- soit tous les étudiants inscrits au module ont des notes
|
||||
- soit elle a été déclarée "à prise ne compte immédiate" (publish_incomplete)
|
||||
|
||||
N'utilise pas de cache ScoDoc.
|
||||
"""
|
||||
# L'index du dataframe est la liste des étudiants inscrits au semestre,
|
||||
# sans les démissionnaires
|
||||
etudids = [
|
||||
e.etudid
|
||||
for e in ModuleImpl.query.get(moduleimpl_id).formsemestre.get_inscrits(
|
||||
include_dem=False
|
||||
)
|
||||
]
|
||||
evaluations = Evaluation.query.filter_by(moduleimpl_id=moduleimpl_id).all()
|
||||
# --- Calcul nombre d'inscrits pour détermnier si évaluation "complete":
|
||||
if evaluations:
|
||||
# --- Calcul nombre d'inscrits pour déterminer les évaluations "completes":
|
||||
# on prend les inscrits au module ET au semestre (donc sans démissionnaires)
|
||||
inscrits_module = {
|
||||
ins.etud.id for ins in evaluations[0].moduleimpl.inscriptions
|
||||
}.intersection(etudids)
|
||||
nb_inscrits_module = len(inscrits_module)
|
||||
else:
|
||||
nb_inscrits_module = 0
|
||||
# empty df with all students:
|
||||
evals_notes = pd.DataFrame(index=etudids, dtype=float)
|
||||
evaluations_completes = []
|
||||
for evaluation in evaluations:
|
||||
inscrits_module = {ins.etud.id for ins in moduleimpl.inscriptions}.intersection(
|
||||
moduleimpl.formsemestre.etudids_actifs
|
||||
)
|
||||
self.nb_inscrits_module = len(inscrits_module)
|
||||
|
||||
# dataFrame vide, index = tous les inscrits au SEMESTRE
|
||||
evals_notes = pd.DataFrame(index=self.etudids, dtype=float)
|
||||
self.evaluations_completes = []
|
||||
self.evaluations_completes_dict = {}
|
||||
self.en_attente = False
|
||||
for evaluation in moduleimpl.evaluations:
|
||||
eval_df = self._load_evaluation_notes(evaluation)
|
||||
# is_complete ssi tous les inscrits (non dem) au semestre ont une note
|
||||
# ou évaluation déclarée "à prise en compte immédiate"
|
||||
# Les évaluations de rattrapage et 2eme session sont toujours incomplètes
|
||||
# car on calcule leur moyenne à part.
|
||||
is_complete = (evaluation.evaluation_type == scu.EVALUATION_NORMALE) and (
|
||||
evaluation.publish_incomplete
|
||||
or (not (inscrits_module - set(eval_df.index)))
|
||||
)
|
||||
self.evaluations_completes.append(is_complete)
|
||||
self.evaluations_completes_dict[evaluation.id] = is_complete
|
||||
|
||||
# NULL en base => ABS (= -999)
|
||||
eval_df.fillna(scu.NOTES_ABSENCE, inplace=True)
|
||||
# Ce merge ne garde que les étudiants inscrits au module
|
||||
# et met à NULL les notes non présentes
|
||||
# (notes non saisies ou etuds non inscrits au module):
|
||||
evals_notes = evals_notes.merge(
|
||||
eval_df, how="left", left_index=True, right_index=True
|
||||
)
|
||||
# Notes en attente: (on prend dans evals_notes pour ne pas avoir les dem.)
|
||||
nb_att = sum(evals_notes[str(evaluation.id)] == scu.NOTES_ATTENTE)
|
||||
self.evaluations_etat[evaluation.id] = EvaluationEtat(
|
||||
evaluation_id=evaluation.id, nb_attente=nb_att, is_complete=is_complete
|
||||
)
|
||||
if nb_att > 0:
|
||||
self.en_attente = True
|
||||
|
||||
# Force columns names to integers (evaluation ids)
|
||||
evals_notes.columns = pd.Int64Index(
|
||||
[int(x) for x in evals_notes.columns], dtype="int"
|
||||
)
|
||||
self.evals_notes = evals_notes
|
||||
|
||||
def _load_evaluation_notes(self, evaluation: Evaluation) -> pd.DataFrame:
|
||||
"""Charge les notes de l'évaluation
|
||||
Resultat: dataframe, index: etudid ayant une note, valeur: note brute.
|
||||
"""
|
||||
eval_df = pd.read_sql_query(
|
||||
"""SELECT n.etudid, n.value AS "%(evaluation_id)s"
|
||||
FROM notes_notes n, notes_moduleimpl_inscription i
|
||||
WHERE evaluation_id=%(evaluation_id)s
|
||||
AND n.etudid = i.etudid
|
||||
AND i.moduleimpl_id = %(moduleimpl_id)s
|
||||
ORDER BY n.etudid
|
||||
""",
|
||||
db.engine,
|
||||
params={
|
||||
|
@ -158,90 +190,316 @@ def df_load_modimpl_notes(moduleimpl_id: int) -> tuple:
|
|||
index_col="etudid",
|
||||
)
|
||||
eval_df[str(evaluation.id)] = pd.to_numeric(eval_df[str(evaluation.id)])
|
||||
# is_complete ssi tous les inscrits (non dem) au semestre ont une note
|
||||
is_complete = (
|
||||
len(set(eval_df.index).intersection(etudids)) == nb_inscrits_module
|
||||
) or evaluation.publish_incomplete
|
||||
evaluations_completes.append(is_complete)
|
||||
# NULL en base => ABS (= -999)
|
||||
eval_df.fillna(scu.NOTES_ABSENCE, inplace=True)
|
||||
# Ce merge met à NULL les élements non présents
|
||||
# (notes non saisies ou etuds non inscrits au module):
|
||||
evals_notes = evals_notes.merge(
|
||||
eval_df, how="left", left_index=True, right_index=True
|
||||
return eval_df
|
||||
|
||||
def _etudids(self):
|
||||
"""L'index du dataframe est la liste de tous les étudiants inscrits au semestre"""
|
||||
return [
|
||||
inscr.etudid
|
||||
for inscr in ModuleImpl.query.get(
|
||||
self.moduleimpl_id
|
||||
).formsemestre.inscriptions
|
||||
]
|
||||
|
||||
def get_evaluations_coefs(self, moduleimpl: ModuleImpl) -> np.array:
|
||||
"""Coefficients des évaluations, met à zéro ceux des évals incomplètes.
|
||||
Résultat: 2d-array of floats, shape (nb_evals, 1)
|
||||
"""
|
||||
return (
|
||||
np.array(
|
||||
[e.coefficient for e in moduleimpl.evaluations],
|
||||
dtype=float,
|
||||
)
|
||||
* self.evaluations_completes
|
||||
).reshape(-1, 1)
|
||||
|
||||
# was _list_notes_evals_titles
|
||||
def get_evaluations_completes(self, moduleimpl: ModuleImpl) -> list:
|
||||
"Liste des évaluations complètes"
|
||||
return [
|
||||
e for e in moduleimpl.evaluations if self.evaluations_completes_dict[e.id]
|
||||
]
|
||||
|
||||
def get_eval_notes_sur_20(self, moduleimpl: ModuleImpl) -> np.array:
|
||||
"""Les notes des évaluations,
|
||||
remplace les ATT, EXC, ABS, NaN par zéro et mets les notes sur 20.
|
||||
Résultat: 2d array of floats, shape nb_etuds x nb_evaluations
|
||||
"""
|
||||
return np.where(
|
||||
self.evals_notes.values > scu.NOTES_ABSENCE, self.evals_notes.values, 0.0
|
||||
) / [e.note_max / 20.0 for e in moduleimpl.evaluations]
|
||||
|
||||
def get_evaluation_rattrapage(self, moduleimpl: ModuleImpl):
|
||||
"""L'évaluation de rattrapage de ce module, ou None s'il n'en a pas.
|
||||
Rattrapage: la moyenne du module est la meilleure note entre moyenne
|
||||
des autres évals et la note eval rattrapage.
|
||||
"""
|
||||
eval_list = [
|
||||
e
|
||||
for e in moduleimpl.evaluations
|
||||
if e.evaluation_type == scu.EVALUATION_RATTRAPAGE
|
||||
]
|
||||
if eval_list:
|
||||
return eval_list[0]
|
||||
return None
|
||||
|
||||
def get_evaluation_session2(self, moduleimpl: ModuleImpl):
|
||||
"""L'évaluation de deuxième session de ce module, ou None s'il n'en a pas.
|
||||
Session 2: remplace la note de moyenne des autres évals.
|
||||
"""
|
||||
eval_list = [
|
||||
e
|
||||
for e in moduleimpl.evaluations
|
||||
if e.evaluation_type == scu.EVALUATION_SESSION2
|
||||
]
|
||||
if eval_list:
|
||||
return eval_list[0]
|
||||
return None
|
||||
|
||||
|
||||
class ModuleImplResultsAPC(ModuleImplResults):
|
||||
"Calcul des moyennes de modules à la mode BUT"
|
||||
|
||||
def compute_module_moy(
|
||||
self,
|
||||
evals_poids_df: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""Calcule les moyennes des étudiants dans ce module
|
||||
|
||||
Argument: evals_poids: DataFrame, colonnes: UEs, Lignes: EVALs
|
||||
|
||||
Résultat: DataFrame, colonnes UE, lignes etud
|
||||
= la note de l'étudiant dans chaque UE pour ce module.
|
||||
ou NaN si les évaluations (dans lesquelles l'étudiant a des notes)
|
||||
ne donnent pas de coef vers cette UE.
|
||||
"""
|
||||
modimpl = ModuleImpl.query.get(self.moduleimpl_id)
|
||||
nb_etuds, nb_evals = self.evals_notes.shape
|
||||
nb_ues = evals_poids_df.shape[1]
|
||||
assert evals_poids_df.shape[0] == nb_evals # compat notes/poids
|
||||
if nb_etuds == 0:
|
||||
return pd.DataFrame(index=[], columns=evals_poids_df.columns)
|
||||
if nb_ues == 0:
|
||||
return pd.DataFrame(index=self.evals_notes.index, columns=[])
|
||||
evals_coefs = self.get_evaluations_coefs(modimpl)
|
||||
evals_poids = evals_poids_df.values * evals_coefs
|
||||
# -> evals_poids shape : (nb_evals, nb_ues)
|
||||
assert evals_poids.shape == (nb_evals, nb_ues)
|
||||
evals_notes_20 = self.get_eval_notes_sur_20(modimpl)
|
||||
|
||||
# Les poids des évals pour chaque étudiant: là où il a des notes
|
||||
# non neutralisées
|
||||
# (ABS n'est pas neutralisée, mais ATTENTE et NEUTRALISE oui)
|
||||
# Note: les NaN sont remplacés par des 0 dans evals_notes
|
||||
# et dans dans evals_poids_etuds
|
||||
# (rappel: la comparaison est toujours false face à un NaN)
|
||||
# shape: (nb_etuds, nb_evals, nb_ues)
|
||||
poids_stacked = np.stack([evals_poids] * nb_etuds)
|
||||
evals_poids_etuds = np.where(
|
||||
np.stack([self.evals_notes.values] * nb_ues, axis=2) > scu.NOTES_NEUTRALISE,
|
||||
poids_stacked,
|
||||
0,
|
||||
)
|
||||
# Force columns names to integers (evaluation ids)
|
||||
evals_notes.columns = pd.Int64Index(
|
||||
[int(x) for x in evals_notes.columns], dtype="int64"
|
||||
)
|
||||
return evals_notes, evaluations, evaluations_completes
|
||||
# Calcule la moyenne pondérée sur les notes disponibles:
|
||||
evals_notes_stacked = np.stack([evals_notes_20] * nb_ues, axis=2)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etuds_moy_module = np.sum(
|
||||
evals_poids_etuds * evals_notes_stacked, axis=1
|
||||
) / np.sum(evals_poids_etuds, axis=1)
|
||||
|
||||
# Session2 : quand elle existe, remplace la note de module
|
||||
eval_session2 = self.get_evaluation_session2(modimpl)
|
||||
if eval_session2:
|
||||
notes_session2 = self.evals_notes[eval_session2.id].values
|
||||
# n'utilise que les notes valides (pas ATT, EXC, ABS, NaN)
|
||||
etuds_use_session2 = notes_session2 > scu.NOTES_ABSENCE
|
||||
etuds_moy_module = np.where(
|
||||
etuds_use_session2[:, np.newaxis],
|
||||
np.tile(
|
||||
(notes_session2 / (eval_session2.note_max / 20.0))[:, np.newaxis],
|
||||
nb_ues,
|
||||
),
|
||||
etuds_moy_module,
|
||||
)
|
||||
self.etuds_use_session2 = pd.Series(
|
||||
etuds_use_session2, index=self.evals_notes.index
|
||||
)
|
||||
else:
|
||||
# Rattrapage: remplace la note de module ssi elle est supérieure
|
||||
eval_rat = self.get_evaluation_rattrapage(modimpl)
|
||||
if eval_rat:
|
||||
notes_rat = self.evals_notes[eval_rat.id].values
|
||||
# remplace les notes invalides (ATT, EXC...) par des NaN
|
||||
notes_rat = np.where(
|
||||
notes_rat > scu.NOTES_ABSENCE,
|
||||
notes_rat / (eval_rat.note_max / 20.0),
|
||||
np.nan,
|
||||
)
|
||||
# "Étend" le rattrapage sur les UE: la note de rattrapage est la même
|
||||
# pour toutes les UE mais ne remplace que là où elle est supérieure
|
||||
notes_rat_ues = np.stack([notes_rat] * nb_ues, axis=1)
|
||||
# prend le max
|
||||
etuds_use_rattrapage = notes_rat_ues > etuds_moy_module
|
||||
etuds_moy_module = np.where(
|
||||
etuds_use_rattrapage, notes_rat_ues, etuds_moy_module
|
||||
)
|
||||
# Serie indiquant que l'étudiant utilise une note de rattarage sur l'une des UE:
|
||||
self.etuds_use_rattrapage = pd.Series(
|
||||
etuds_use_rattrapage.any(axis=1), index=self.evals_notes.index
|
||||
)
|
||||
self.etuds_moy_module = pd.DataFrame(
|
||||
etuds_moy_module,
|
||||
index=self.evals_notes.index,
|
||||
columns=evals_poids_df.columns,
|
||||
)
|
||||
return self.etuds_moy_module
|
||||
|
||||
|
||||
def compute_module_moy(
|
||||
evals_notes_df: pd.DataFrame,
|
||||
evals_poids_df: pd.DataFrame,
|
||||
evaluations: list,
|
||||
evaluations_completes: list,
|
||||
) -> pd.DataFrame:
|
||||
"""Calcule les moyennes des étudiants dans ce module
|
||||
def load_evaluations_poids(moduleimpl_id: int) -> tuple[pd.DataFrame, list]:
|
||||
"""Charge poids des évaluations d'un module et retourne un dataframe
|
||||
rows = evaluations, columns = UE, value = poids (float).
|
||||
Les valeurs manquantes (évaluations sans coef vers des UE) sont
|
||||
remplies: 1 si le coef de ce module dans l'UE est non nul, zéro sinon
|
||||
(sauf pour module bonus, defaut à 1)
|
||||
|
||||
- evals_notes : DataFrame, colonnes: EVALS, Lignes: etudid
|
||||
valeur: notes brutes, float ou NOTES_ATTENTE, NOTES_NEUTRALISE,
|
||||
NOTES_ABSENCE.
|
||||
Les NaN désignent les notes manquantes (non saisies).
|
||||
Si le module n'est pas une ressource ou une SAE, ne charge pas de poids
|
||||
et renvoie toujours les poids par défaut.
|
||||
|
||||
- evals_poids: DataFrame, colonnes: UEs, Lignes: EVALs
|
||||
|
||||
- evaluations: séquence d'évaluations (utilisées pour le coef et
|
||||
le barème)
|
||||
|
||||
- evaluations_completes: séquence de booléens indiquant les
|
||||
évals à prendre en compte.
|
||||
|
||||
Résultat: DataFrame, colonnes UE, lignes etud
|
||||
= la note de l'étudiant dans chaque UE pour ce module.
|
||||
ou NaN si les évaluations (dans lesquelles l'étudiant à des notes)
|
||||
ne donnent pas de coef vers cette UE.
|
||||
Résultat: (evals_poids, liste de UEs du semestre sauf le sport)
|
||||
"""
|
||||
nb_etuds, nb_evals = evals_notes_df.shape
|
||||
nb_ues = evals_poids_df.shape[1]
|
||||
assert evals_poids_df.shape[0] == nb_evals # compat notes/poids
|
||||
if nb_etuds == 0:
|
||||
return pd.DataFrame(index=[], columns=evals_poids_df.columns)
|
||||
# Coefficients des évaluations, met à zéro ceux des évals incomplètes:
|
||||
evals_coefs = (
|
||||
np.array(
|
||||
[e.coefficient for e in evaluations],
|
||||
dtype=float,
|
||||
modimpl: ModuleImpl = ModuleImpl.query.get(moduleimpl_id)
|
||||
evaluations = Evaluation.query.filter_by(moduleimpl_id=moduleimpl_id).all()
|
||||
ues = modimpl.formsemestre.query_ues(with_sport=False).all()
|
||||
ue_ids = [ue.id for ue in ues]
|
||||
evaluation_ids = [evaluation.id for evaluation in evaluations]
|
||||
evals_poids = pd.DataFrame(columns=ue_ids, index=evaluation_ids, dtype=float)
|
||||
if (
|
||||
modimpl.module.module_type == ModuleType.RESSOURCE
|
||||
or modimpl.module.module_type == ModuleType.SAE
|
||||
):
|
||||
for ue_poids in EvaluationUEPoids.query.join(
|
||||
EvaluationUEPoids.evaluation
|
||||
).filter_by(moduleimpl_id=moduleimpl_id):
|
||||
try:
|
||||
evals_poids[ue_poids.ue_id][ue_poids.evaluation_id] = ue_poids.poids
|
||||
except KeyError as exc:
|
||||
pass # poids vers des UE qui n'existent plus ou sont dans un autre semestre...
|
||||
|
||||
# Initialise poids non enregistrés:
|
||||
default_poids = (
|
||||
1.0
|
||||
if modimpl.module.ue.type == UE_SPORT
|
||||
or modimpl.module.module_type == ModuleType.MALUS
|
||||
else 0.0
|
||||
)
|
||||
|
||||
if np.isnan(evals_poids.values.flat).any():
|
||||
ue_coefs = modimpl.module.get_ue_coef_dict()
|
||||
for ue in ues:
|
||||
evals_poids[ue.id][evals_poids[ue.id].isna()] = (
|
||||
1 if ue_coefs.get(ue.id, default_poids) > 0 else 0
|
||||
)
|
||||
|
||||
return evals_poids, ues
|
||||
|
||||
|
||||
def moduleimpl_is_conforme(
|
||||
moduleimpl, evals_poids: pd.DataFrame, modules_coefficients: pd.DataFrame
|
||||
) -> bool:
|
||||
"""Vérifie que les évaluations de ce moduleimpl sont bien conformes
|
||||
au PN.
|
||||
Un module est dit *conforme* si et seulement si la somme des poids de ses
|
||||
évaluations vers une UE de coefficient non nul est non nulle.
|
||||
|
||||
Argument: evals_poids: DataFrame, colonnes: UEs, Lignes: EVALs
|
||||
NB: les UEs dans evals_poids sont sans le bonus sport
|
||||
"""
|
||||
nb_evals, nb_ues = evals_poids.shape
|
||||
if nb_evals == 0:
|
||||
return True # modules vides conformes
|
||||
if nb_ues == 0:
|
||||
return False # situation absurde (pas d'UE)
|
||||
if len(modules_coefficients) != nb_ues:
|
||||
raise ValueError("moduleimpl_is_conforme: nb ue incoherent")
|
||||
module_evals_poids = evals_poids.transpose().sum(axis=1).to_numpy() != 0
|
||||
check = all(
|
||||
(modules_coefficients[moduleimpl.module_id].to_numpy() != 0)
|
||||
== module_evals_poids
|
||||
)
|
||||
return check
|
||||
|
||||
|
||||
class ModuleImplResultsClassic(ModuleImplResults):
|
||||
"Calcul des moyennes de modules des formations classiques"
|
||||
|
||||
def compute_module_moy(self) -> pd.Series:
|
||||
"""Calcule les moyennes des étudiants dans ce module
|
||||
|
||||
Résultat: Series, lignes etud
|
||||
= la note (moyenne) de l'étudiant pour ce module.
|
||||
ou NaN si les évaluations (dans lesquelles l'étudiant a des notes)
|
||||
ne donnent pas de coef.
|
||||
"""
|
||||
modimpl = ModuleImpl.query.get(self.moduleimpl_id)
|
||||
nb_etuds, nb_evals = self.evals_notes.shape
|
||||
if nb_etuds == 0:
|
||||
return pd.Series()
|
||||
evals_coefs = self.get_evaluations_coefs(modimpl).reshape(-1)
|
||||
assert evals_coefs.shape == (nb_evals,)
|
||||
evals_notes_20 = self.get_eval_notes_sur_20(modimpl)
|
||||
# Les coefs des évals pour chaque étudiant: là où il a des notes
|
||||
# non neutralisées
|
||||
# (ABS n'est pas neutralisée, mais ATTENTE et NEUTRALISE oui)
|
||||
# Note: les NaN sont remplacés par des 0 dans evals_notes
|
||||
# et dans dans evals_poids_etuds
|
||||
# (rappel: la comparaison est toujours False face à un NaN)
|
||||
# shape: (nb_etuds, nb_evals)
|
||||
coefs_stacked = np.stack([evals_coefs] * nb_etuds)
|
||||
evals_coefs_etuds = np.where(
|
||||
self.evals_notes.values > scu.NOTES_NEUTRALISE, coefs_stacked, 0
|
||||
)
|
||||
* evaluations_completes
|
||||
).reshape(-1, 1)
|
||||
evals_poids = evals_poids_df.values * evals_coefs
|
||||
# -> evals_poids shape : (nb_evals, nb_ues)
|
||||
assert evals_poids.shape == (nb_evals, nb_ues)
|
||||
# Remplace les notes ATT, EXC, ABS, NaN par zéro et mets les notes sur 20:
|
||||
evals_notes = np.where(
|
||||
evals_notes_df.values > scu.NOTES_ABSENCE, evals_notes_df.values, 0.0
|
||||
) / [e.note_max / 20.0 for e in evaluations]
|
||||
# Les poids des évals pour les étudiant: là où il a des notes non neutralisées
|
||||
# (ABS n'est pas neutralisée, mais ATTENTE et NEUTRALISE oui)
|
||||
# Note: les NaN sont remplacés par des 0 dans evals_notes
|
||||
# et dans dans evals_poids_etuds
|
||||
# (rappel: la comparaison est toujours false face à un NaN)
|
||||
# shape: (nb_etuds, nb_evals, nb_ues)
|
||||
poids_stacked = np.stack([evals_poids] * nb_etuds)
|
||||
evals_poids_etuds = np.where(
|
||||
np.stack([evals_notes_df.values] * nb_ues, axis=2) > scu.NOTES_NEUTRALISE,
|
||||
poids_stacked,
|
||||
0,
|
||||
)
|
||||
# Calcule la moyenne pondérée sur les notes disponibles:
|
||||
evals_notes_stacked = np.stack([evals_notes] * nb_ues, axis=2)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etuds_moy_module = np.sum(
|
||||
evals_poids_etuds * evals_notes_stacked, axis=1
|
||||
) / np.sum(evals_poids_etuds, axis=1)
|
||||
etuds_moy_module_df = pd.DataFrame(
|
||||
etuds_moy_module, index=evals_notes_df.index, columns=evals_poids_df.columns
|
||||
)
|
||||
return etuds_moy_module_df
|
||||
# Calcule la moyenne pondérée sur les notes disponibles:
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etuds_moy_module = np.sum(
|
||||
evals_coefs_etuds * evals_notes_20, axis=1
|
||||
) / np.sum(evals_coefs_etuds, axis=1)
|
||||
|
||||
# Session2 : quand elle existe, remplace la note de module
|
||||
eval_session2 = self.get_evaluation_session2(modimpl)
|
||||
if eval_session2:
|
||||
notes_session2 = self.evals_notes[eval_session2.id].values
|
||||
# n'utilise que les notes valides (pas ATT, EXC, ABS, NaN)
|
||||
etuds_use_session2 = notes_session2 > scu.NOTES_ABSENCE
|
||||
etuds_moy_module = np.where(
|
||||
etuds_use_session2,
|
||||
notes_session2 / (eval_session2.note_max / 20.0),
|
||||
etuds_moy_module,
|
||||
)
|
||||
self.etuds_use_session2 = pd.Series(
|
||||
etuds_use_session2, index=self.evals_notes.index
|
||||
)
|
||||
else:
|
||||
# Rattrapage: remplace la note de module ssi elle est supérieure
|
||||
eval_rat = self.get_evaluation_rattrapage(modimpl)
|
||||
if eval_rat:
|
||||
notes_rat = self.evals_notes[eval_rat.id].values
|
||||
# remplace les notes invalides (ATT, EXC...) par des NaN
|
||||
notes_rat = np.where(
|
||||
notes_rat > scu.NOTES_ABSENCE,
|
||||
notes_rat / (eval_rat.note_max / 20.0),
|
||||
np.nan,
|
||||
)
|
||||
# prend le max
|
||||
etuds_use_rattrapage = notes_rat > etuds_moy_module
|
||||
etuds_moy_module = np.where(
|
||||
etuds_use_rattrapage, notes_rat, etuds_moy_module
|
||||
)
|
||||
self.etuds_use_rattrapage = pd.Series(
|
||||
etuds_use_rattrapage, index=self.evals_notes.index
|
||||
)
|
||||
self.etuds_moy_module = pd.Series(
|
||||
etuds_moy_module,
|
||||
index=self.evals_notes.index,
|
||||
)
|
||||
|
||||
return self.etuds_moy_module
|
||||
|
|
|
@ -30,13 +30,18 @@
|
|||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from flask import flash, g, Markup, url_for
|
||||
from app.models.formations import Formation
|
||||
|
||||
def compute_sem_moys(etud_moy_ue_df, modimpl_coefs_df):
|
||||
"""Calcule la moyenne générale indicative
|
||||
|
||||
def compute_sem_moys_apc_using_coefs(
|
||||
etud_moy_ue_df: pd.DataFrame, modimpl_coefs_df: pd.DataFrame
|
||||
) -> pd.Series:
|
||||
"""Calcule les moyennes générales indicatives de tous les étudiants
|
||||
= moyenne des moyennes d'UE, pondérée par la somme de leurs coefs
|
||||
|
||||
etud_moy_ue_df: DataFrame, colonnes ue_id, lignes etudid
|
||||
modimpl_coefs_df: DataFrame, colonnes moduleimpl_id, lignes UE
|
||||
modimpl_coefs_df: DataFrame, colonnes moduleimpl_id, lignes UE (sans ue bonus)
|
||||
|
||||
Result: panda Series, index etudid, valeur float (moyenne générale)
|
||||
"""
|
||||
|
@ -46,13 +51,57 @@ def compute_sem_moys(etud_moy_ue_df, modimpl_coefs_df):
|
|||
return moy_gen
|
||||
|
||||
|
||||
def comp_ranks_series(notes: pd.Series):
|
||||
"""Calcul rangs à partir d'une séries ("vecteur") de notes (index etudid, valeur numérique)
|
||||
en tenant compte des ex-aequos
|
||||
Le resultat est: { etudid : rang } où rang est une chaine decrivant le rang
|
||||
def compute_sem_moys_apc_using_ects(
|
||||
etud_moy_ue_df: pd.DataFrame, ects: list, formation_id=None, skip_empty_ues=False
|
||||
) -> pd.Series:
|
||||
"""Calcule les moyennes générales indicatives de tous les étudiants
|
||||
= moyenne des moyennes d'UE, pondérée par leurs ECTS.
|
||||
|
||||
etud_moy_ue_df: DataFrame, colonnes ue_id, lignes etudid
|
||||
ects: liste de floats ou None, 1 par UE
|
||||
|
||||
Si skip_empty_ues: ne compte pas les UE non notées.
|
||||
Sinon (par défaut), une UE non notée compte comme zéro.
|
||||
|
||||
Result: panda Series, index etudid, valeur float (moyenne générale)
|
||||
"""
|
||||
try:
|
||||
if skip_empty_ues:
|
||||
# annule les coefs des UE sans notes (NaN)
|
||||
ects = np.where(etud_moy_ue_df.isna(), 0.0, np.array(ects, dtype=float))
|
||||
# ects est devenu nb_etuds x nb_ues
|
||||
moy_gen = (etud_moy_ue_df * ects).sum(axis=1) / ects.sum(axis=1)
|
||||
else:
|
||||
moy_gen = (etud_moy_ue_df * ects).sum(axis=1) / sum(ects)
|
||||
except TypeError:
|
||||
if None in ects:
|
||||
formation = Formation.query.get(formation_id)
|
||||
flash(
|
||||
Markup(
|
||||
f"""Calcul moyenne générale impossible: ECTS des UE manquants !<br>
|
||||
(formation: <a href="{url_for("notes.ue_table",
|
||||
scodoc_dept=g.scodoc_dept, formation_id=formation_id)}">{formation.get_titre_version()}</a>)"""
|
||||
)
|
||||
)
|
||||
moy_gen = pd.Series(np.NaN, index=etud_moy_ue_df.index)
|
||||
else:
|
||||
raise
|
||||
return moy_gen
|
||||
|
||||
|
||||
def comp_ranks_series(notes: pd.Series) -> (pd.Series, pd.Series):
|
||||
"""Calcul rangs à partir d'une séries ("vecteur") de notes (index etudid, valeur
|
||||
numérique) en tenant compte des ex-aequos.
|
||||
|
||||
Result: couple (tuple)
|
||||
Series { etudid : rang:str } où rang est une chaine decrivant le rang,
|
||||
Series { etudid : rang:int } le rang comme un nombre
|
||||
"""
|
||||
if (notes is None) or (len(notes) == 0):
|
||||
return (pd.Series([], dtype=object), pd.Series([], dtype=int))
|
||||
notes = notes.sort_values(ascending=False) # Serie, tri par ordre décroissant
|
||||
rangs = pd.Series(index=notes.index, dtype=str) # le rang est une chaîne
|
||||
rangs_str = pd.Series(index=notes.index, dtype=str) # le rang est une chaîne
|
||||
rangs_int = pd.Series(index=notes.index, dtype=int) # le rang numérique pour tris
|
||||
N = len(notes)
|
||||
nb_ex = 0 # nb d'ex-aequo consécutifs en cours
|
||||
notes_i = notes.iat
|
||||
|
@ -64,6 +113,7 @@ def comp_ranks_series(notes: pd.Series):
|
|||
next = None
|
||||
val = notes_i[i]
|
||||
if nb_ex:
|
||||
rangs_int[etudid] = i + 1 - nb_ex
|
||||
srang = "%d ex" % (i + 1 - nb_ex)
|
||||
if val == next:
|
||||
nb_ex += 1
|
||||
|
@ -71,9 +121,11 @@ def comp_ranks_series(notes: pd.Series):
|
|||
nb_ex = 0
|
||||
else:
|
||||
if val == next:
|
||||
rangs_int[etudid] = i + 1 - nb_ex
|
||||
srang = "%d ex" % (i + 1 - nb_ex)
|
||||
nb_ex = 1
|
||||
else:
|
||||
rangs_int[etudid] = i + 1
|
||||
srang = "%d" % (i + 1)
|
||||
rangs[etudid] = srang
|
||||
return rangs
|
||||
rangs_str[etudid] = srang
|
||||
return rangs_str, rangs_int
|
||||
|
|
|
@ -25,7 +25,7 @@
|
|||
#
|
||||
##############################################################################
|
||||
|
||||
"""Fonctions de calcul des moyennes d'UE
|
||||
"""Fonctions de calcul des moyennes d'UE (classiques ou BUT)
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
@ -36,17 +36,20 @@ from app.models import UniteEns, Module, ModuleImpl, ModuleUECoef
|
|||
from app.comp import moy_mod
|
||||
from app.models.formsemestre import FormSemestre
|
||||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
def df_load_module_coefs(formation_id: int, semestre_idx: int = None) -> pd.DataFrame:
|
||||
"""Charge les coefs des modules de la formation pour le semestre indiqué.
|
||||
"""Charge les coefs APC des modules de la formation pour le semestre indiqué.
|
||||
|
||||
Ces coefs lient les modules à chaque UE.
|
||||
En APC, ces coefs lient les modules à chaque UE.
|
||||
|
||||
Résultat: (module_coefs_df, ues, modules)
|
||||
Résultat: (module_coefs_df, ues_no_bonus, modules)
|
||||
DataFrame rows = UEs, columns = modules, value = coef.
|
||||
|
||||
Considère toutes les UE (sauf sport) et modules du semestre.
|
||||
Considère toutes les UE sauf bonus et tous les modules du semestre.
|
||||
Les coefs non définis (pas en base) sont mis à zéro.
|
||||
|
||||
Si semestre_idx None, prend toutes les UE de la formation.
|
||||
|
@ -56,8 +59,19 @@ def df_load_module_coefs(formation_id: int, semestre_idx: int = None) -> pd.Data
|
|||
.filter(UniteEns.type != sco_codes_parcours.UE_SPORT)
|
||||
.order_by(UniteEns.semestre_idx, UniteEns.numero, UniteEns.acronyme)
|
||||
)
|
||||
modules = Module.query.filter_by(formation_id=formation_id).order_by(
|
||||
Module.semestre_id, Module.module_type.desc(), Module.numero, Module.code
|
||||
modules = (
|
||||
Module.query.filter_by(formation_id=formation_id)
|
||||
.filter(
|
||||
(Module.module_type == ModuleType.RESSOURCE)
|
||||
| (Module.module_type == ModuleType.SAE)
|
||||
| (
|
||||
(Module.ue_id == UniteEns.id)
|
||||
& (UniteEns.type == sco_codes_parcours.UE_SPORT)
|
||||
)
|
||||
)
|
||||
.order_by(
|
||||
Module.semestre_id, Module.module_type.desc(), Module.numero, Module.code
|
||||
)
|
||||
)
|
||||
if semestre_idx is not None:
|
||||
ues = ues.filter_by(semestre_idx=semestre_idx)
|
||||
|
@ -76,9 +90,21 @@ def df_load_module_coefs(formation_id: int, semestre_idx: int = None) -> pd.Data
|
|||
query = query.filter(UniteEns.semestre_idx == semestre_idx)
|
||||
|
||||
for mod_coef in query:
|
||||
module_coefs_df[mod_coef.module_id][mod_coef.ue_id] = mod_coef.coef
|
||||
if mod_coef.module_id in module_coefs_df:
|
||||
module_coefs_df[mod_coef.module_id][mod_coef.ue_id] = mod_coef.coef
|
||||
# silently ignore coefs associated to other modules (ie when module_type is changed)
|
||||
|
||||
module_coefs_df.fillna(value=0, inplace=True)
|
||||
# Initialisation des poids non fixés:
|
||||
# 0 pour modules normaux, 1. pour bonus (car par défaut, on veut qu'un bonus agisse
|
||||
# sur toutes les UE)
|
||||
default_poids = {
|
||||
mod.id: 1.0
|
||||
if (mod.module_type == ModuleType.STANDARD) and (mod.ue.type == UE_SPORT)
|
||||
else 0.0
|
||||
for mod in modules
|
||||
}
|
||||
|
||||
module_coefs_df.fillna(value=default_poids, inplace=True)
|
||||
|
||||
return module_coefs_df, ues, modules
|
||||
|
||||
|
@ -86,19 +112,19 @@ def df_load_module_coefs(formation_id: int, semestre_idx: int = None) -> pd.Data
|
|||
def df_load_modimpl_coefs(
|
||||
formsemestre: models.FormSemestre, ues=None, modimpls=None
|
||||
) -> pd.DataFrame:
|
||||
"""Charge les coefs des modules du formsemestre indiqué.
|
||||
"""Charge les coefs APC des modules du formsemestre indiqué.
|
||||
|
||||
Comme df_load_module_coefs mais prend seulement les UE
|
||||
et modules du formsemestre.
|
||||
Si ues et modimpls sont None, prend tous ceux du formsemestre.
|
||||
Si ues et modimpls sont None, prend tous ceux du formsemestre (sauf ue bonus).
|
||||
Résultat: (module_coefs_df, ues, modules)
|
||||
DataFrame rows = UEs, columns = modimpl, value = coef.
|
||||
DataFrame rows = UEs (sans bonus), columns = modimpl, value = coef.
|
||||
"""
|
||||
if ues is None:
|
||||
ues = formsemestre.query_ues().all()
|
||||
ue_ids = [x.id for x in ues]
|
||||
if modimpls is None:
|
||||
modimpls = formsemestre.modimpls.all()
|
||||
modimpls = formsemestre.modimpls_sorted
|
||||
modimpl_ids = [x.id for x in modimpls]
|
||||
mod2impl = {m.module.id: m.id for m in modimpls}
|
||||
modimpl_coefs_df = pd.DataFrame(columns=modimpl_ids, index=ue_ids, dtype=float)
|
||||
|
@ -109,8 +135,25 @@ def df_load_modimpl_coefs(
|
|||
)
|
||||
|
||||
for mod_coef in mod_coefs:
|
||||
modimpl_coefs_df[mod2impl[mod_coef.module_id]][mod_coef.ue_id] = mod_coef.coef
|
||||
modimpl_coefs_df.fillna(value=0, inplace=True)
|
||||
try:
|
||||
modimpl_coefs_df[mod2impl[mod_coef.module_id]][
|
||||
mod_coef.ue_id
|
||||
] = mod_coef.coef
|
||||
except IndexError:
|
||||
# il peut y avoir en base des coefs sur des modules ou UE qui ont depuis été retirés de la formation
|
||||
pass
|
||||
# Initialisation des poids non fixés:
|
||||
# 0 pour modules normaux, 1. pour bonus (car par défaut, on veut qu'un bonus agisse
|
||||
# sur toutes les UE)
|
||||
default_poids = {
|
||||
modimpl.id: 1.0
|
||||
if (modimpl.module.module_type == ModuleType.STANDARD)
|
||||
and (modimpl.module.ue.type == UE_SPORT)
|
||||
else 0.0
|
||||
for modimpl in formsemestre.modimpls_sorted
|
||||
}
|
||||
|
||||
modimpl_coefs_df.fillna(value=default_poids, inplace=True)
|
||||
return modimpl_coefs_df, ues, modimpls
|
||||
|
||||
|
||||
|
@ -124,38 +167,37 @@ def notes_sem_assemble_cube(modimpls_notes: list[pd.DataFrame]) -> np.ndarray:
|
|||
assert len(modimpls_notes)
|
||||
modimpls_notes_arr = [df.values for df in modimpls_notes]
|
||||
modimpls_notes = np.stack(modimpls_notes_arr)
|
||||
# passe de (mod x etud x ue) à (etud x mod x UE)
|
||||
# passe de (mod x etud x ue) à (etud x mod x ue)
|
||||
return modimpls_notes.swapaxes(0, 1)
|
||||
|
||||
|
||||
def notes_sem_load_cube(formsemestre):
|
||||
"""Calcule le cube des notes du semestre
|
||||
(charge toutes les notes, calcule les moyenne des modules
|
||||
et assemble le cube)
|
||||
Resultat:
|
||||
def notes_sem_load_cube(formsemestre: FormSemestre) -> tuple:
|
||||
"""Construit le "cube" (tenseur) des notes du semestre.
|
||||
Charge toutes les notes (sql), calcule les moyennes des modules
|
||||
et assemble le cube.
|
||||
|
||||
etuds: tous les inscrits au semestre (avec dem. et def.)
|
||||
modimpls: _tous_ les modimpls de ce semestre (y compris bonus sport)
|
||||
UEs: toutes les UE du semestre (même si pas d'inscrits) SAUF le sport.
|
||||
|
||||
Attention: la liste des modimpls inclut les modules des UE sport, mais
|
||||
elles ne sont pas dans la troisième dimension car elles n'ont pas de
|
||||
"moyenne d'UE".
|
||||
|
||||
Résultat:
|
||||
sem_cube : ndarray (etuds x modimpls x UEs)
|
||||
modimpls_evals_poids dict { modimpl.id : evals_poids }
|
||||
modimpls_evals_notes dict { modimpl.id : evals_notes }
|
||||
modimpls_evaluations dict { modimpl.id : liste des évaluations }
|
||||
modimpls_evaluations_complete: {modimpl_id : liste de booleens (complete/non)}
|
||||
modimpls_results dict { modimpl.id : ModuleImplResultsAPC }
|
||||
"""
|
||||
modimpls_results = {}
|
||||
modimpls_evals_poids = {}
|
||||
modimpls_evals_notes = {}
|
||||
modimpls_evaluations = {}
|
||||
modimpls_evaluations_complete = {}
|
||||
modimpls_notes = []
|
||||
for modimpl in formsemestre.modimpls:
|
||||
evals_notes, evaluations, evaluations_completes = moy_mod.df_load_modimpl_notes(
|
||||
modimpl.id
|
||||
)
|
||||
evals_poids, ues = moy_mod.df_load_evaluations_poids(modimpl.id)
|
||||
etuds_moy_module = moy_mod.compute_module_moy(
|
||||
evals_notes, evals_poids, evaluations, evaluations_completes
|
||||
)
|
||||
for modimpl in formsemestre.modimpls_sorted:
|
||||
mod_results = moy_mod.ModuleImplResultsAPC(modimpl)
|
||||
evals_poids, _ = moy_mod.load_evaluations_poids(modimpl.id)
|
||||
etuds_moy_module = mod_results.compute_module_moy(evals_poids)
|
||||
modimpls_results[modimpl.id] = mod_results
|
||||
modimpls_evals_poids[modimpl.id] = evals_poids
|
||||
modimpls_evals_notes[modimpl.id] = evals_notes
|
||||
modimpls_evaluations[modimpl.id] = evaluations
|
||||
modimpls_evaluations_complete[modimpl.id] = evaluations_completes
|
||||
modimpls_notes.append(etuds_moy_module)
|
||||
if len(modimpls_notes):
|
||||
cube = notes_sem_assemble_cube(modimpls_notes)
|
||||
|
@ -165,53 +207,57 @@ def notes_sem_load_cube(formsemestre):
|
|||
return (
|
||||
cube,
|
||||
modimpls_evals_poids,
|
||||
modimpls_evals_notes,
|
||||
modimpls_evaluations,
|
||||
modimpls_evaluations_complete,
|
||||
modimpls_results,
|
||||
)
|
||||
|
||||
|
||||
def compute_ue_moys(
|
||||
def compute_ue_moys_apc(
|
||||
sem_cube: np.array,
|
||||
etuds: list,
|
||||
modimpls: list,
|
||||
ues: list,
|
||||
modimpl_inscr_df: pd.DataFrame,
|
||||
modimpl_coefs_df: pd.DataFrame,
|
||||
modimpl_mask: np.array,
|
||||
) -> pd.DataFrame:
|
||||
"""Calcul de la moyenne d'UE
|
||||
"""Calcul de la moyenne d'UE en mode APC (BUT).
|
||||
La moyenne d'UE est un nombre (note/20), ou NI ou NA ou ERR
|
||||
NI non inscrit à (au moins un) module de cette UE
|
||||
NA pas de notes disponibles
|
||||
ERR erreur dans une formule utilisateur. [XXX pas encore gérées ici]
|
||||
NI non inscrit à (au moins un) module de cette UE
|
||||
NA pas de notes disponibles
|
||||
ERR erreur dans une formule utilisateurs (pas gérées ici).
|
||||
|
||||
sem_cube: notes moyennes aux modules
|
||||
ndarray (etuds x modimpls x UEs)
|
||||
(floats avec des NaN)
|
||||
etuds : lites des étudiants (dim. 0 du cube)
|
||||
modimpls : liste des modules à considérer (dim. 1 du cube)
|
||||
etuds : liste des étudiants (dim. 0 du cube)
|
||||
modimpls : liste des module_impl (dim. 1 du cube)
|
||||
ues : liste des UE (dim. 2 du cube)
|
||||
module_inscr_df: matrice d'inscription du semestre (etud x modimpl)
|
||||
module_coefs_df: matrice coefficients (UE x modimpl)
|
||||
modimpl_inscr_df: matrice d'inscription du semestre (etud x modimpl)
|
||||
modimpl_coefs_df: matrice coefficients (UE x modimpl), sans UEs bonus sport
|
||||
modimpl_mask: liste de booléens, indiquants le module doit être pris ou pas.
|
||||
(utilisé pour éliminer les bonus, et pourra servir à cacluler
|
||||
sur des sous-ensembles de modules)
|
||||
|
||||
Resultat: DataFrame columns UE, rows etudid
|
||||
Résultat: DataFrame columns UE (sans bonus), rows etudid
|
||||
"""
|
||||
nb_etuds, nb_modules, nb_ues = sem_cube.shape
|
||||
nb_etuds, nb_modules, nb_ues_no_bonus = sem_cube.shape
|
||||
nb_ues_tot = len(ues)
|
||||
assert len(modimpls) == nb_modules
|
||||
if nb_modules == 0 or nb_etuds == 0:
|
||||
if nb_modules == 0 or nb_etuds == 0 or nb_ues_no_bonus == 0:
|
||||
return pd.DataFrame(
|
||||
index=modimpl_inscr_df.index, columns=modimpl_coefs_df.index
|
||||
)
|
||||
assert len(etuds) == nb_etuds
|
||||
assert len(ues) == nb_ues
|
||||
assert modimpl_inscr_df.shape[0] == nb_etuds
|
||||
assert modimpl_inscr_df.shape[1] == nb_modules
|
||||
assert modimpl_coefs_df.shape[0] == nb_ues
|
||||
assert modimpl_coefs_df.shape[0] == nb_ues_no_bonus
|
||||
assert modimpl_coefs_df.shape[1] == nb_modules
|
||||
modimpl_inscr = modimpl_inscr_df.values
|
||||
modimpl_coefs = modimpl_coefs_df.values
|
||||
# Duplique les inscriptions sur les UEs:
|
||||
modimpl_inscr_stacked = np.stack([modimpl_inscr] * nb_ues, axis=2)
|
||||
# Met à zéro tous les coefs des modules non sélectionnés dans le masque:
|
||||
modimpl_coefs = np.where(modimpl_mask, modimpl_coefs_df.values, 0.0)
|
||||
|
||||
# Duplique les inscriptions sur les UEs non bonus:
|
||||
modimpl_inscr_stacked = np.stack([modimpl_inscr] * nb_ues_no_bonus, axis=2)
|
||||
# Enlève les NaN du numérateur:
|
||||
# si on veut prendre en compte les modules avec notes neutralisées ?
|
||||
sem_cube_no_nan = np.nan_to_num(sem_cube, nan=0.0)
|
||||
|
@ -225,12 +271,243 @@ def compute_ue_moys(
|
|||
)
|
||||
# Annule les coefs des modules NaN
|
||||
modimpl_coefs_etuds_no_nan = np.where(np.isnan(sem_cube), 0.0, modimpl_coefs_etuds)
|
||||
if modimpl_coefs_etuds_no_nan.dtype == np.object: # arrive sur des tableaux vides
|
||||
modimpl_coefs_etuds_no_nan = modimpl_coefs_etuds_no_nan.astype(np.float)
|
||||
#
|
||||
# Version vectorisée
|
||||
#
|
||||
etud_moy_ue = np.sum(
|
||||
modimpl_coefs_etuds_no_nan * sem_cube_inscrits, axis=1
|
||||
) / np.sum(modimpl_coefs_etuds_no_nan, axis=1)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etud_moy_ue = np.sum(
|
||||
modimpl_coefs_etuds_no_nan * sem_cube_inscrits, axis=1
|
||||
) / np.sum(modimpl_coefs_etuds_no_nan, axis=1)
|
||||
return pd.DataFrame(
|
||||
etud_moy_ue, index=modimpl_inscr_df.index, columns=modimpl_coefs_df.index
|
||||
etud_moy_ue,
|
||||
index=modimpl_inscr_df.index, # les etudids
|
||||
columns=modimpl_coefs_df.index, # les UE sans les UE bonus sport
|
||||
)
|
||||
|
||||
|
||||
def compute_ue_moys_classic(
|
||||
formsemestre: FormSemestre,
|
||||
sem_matrix: np.array,
|
||||
ues: list,
|
||||
modimpl_inscr_df: pd.DataFrame,
|
||||
modimpl_coefs: np.array,
|
||||
modimpl_mask: np.array,
|
||||
) -> tuple[pd.Series, pd.DataFrame, pd.DataFrame]:
|
||||
"""Calcul de la moyenne d'UE et de la moy. générale en mode classique (DUT, LMD, ...).
|
||||
|
||||
La moyenne d'UE est un nombre (note/20), ou NI ou NA ou ERR
|
||||
NI non inscrit à (au moins un) module de cette UE
|
||||
NA pas de notes disponibles
|
||||
ERR erreur dans une formule utilisateur. [XXX pas encore gérées ici]
|
||||
|
||||
L'éventuel bonus sport n'est PAS appliqué ici.
|
||||
|
||||
Le masque modimpl_mask est un tableau de booléens (un par modimpl) qui
|
||||
permet de sélectionner un sous-ensemble de modules (SAEs, tout sauf sport, ...).
|
||||
|
||||
sem_matrix: notes moyennes aux modules (tous les étuds x tous les modimpls)
|
||||
ndarray (etuds x modimpls)
|
||||
(floats avec des NaN)
|
||||
etuds : listes des étudiants (dim. 0 de la matrice)
|
||||
ues : liste des UE du semestre
|
||||
modimpl_inscr_df: matrice d'inscription du semestre (etud x modimpl)
|
||||
modimpl_coefs: vecteur des coefficients de modules
|
||||
modimpl_mask: masque des modimpls à prendre en compte
|
||||
|
||||
Résultat:
|
||||
- moyennes générales: pd.Series, index etudid
|
||||
- moyennes d'UE: DataFrame columns UE, rows etudid
|
||||
- coefficients d'UE: DataFrame, columns UE, rows etudid
|
||||
les coefficients effectifs de chaque UE pour chaque étudiant
|
||||
(sommes de coefs de modules pris en compte)
|
||||
"""
|
||||
if (not len(modimpl_mask)) or (
|
||||
sem_matrix.shape[0] == 0
|
||||
): # aucun module ou aucun étudiant
|
||||
# etud_moy_gen_s, etud_moy_ue_df, etud_coef_ue_df
|
||||
return (
|
||||
pd.Series(
|
||||
[0.0] * len(modimpl_inscr_df.index), index=modimpl_inscr_df.index
|
||||
),
|
||||
pd.DataFrame(columns=[ue.id for ue in ues], index=modimpl_inscr_df.index),
|
||||
pd.DataFrame(columns=[ue.id for ue in ues], index=modimpl_inscr_df.index),
|
||||
)
|
||||
# Restreint aux modules sélectionnés:
|
||||
sem_matrix = sem_matrix[:, modimpl_mask]
|
||||
modimpl_inscr = modimpl_inscr_df.values[:, modimpl_mask]
|
||||
modimpl_coefs = modimpl_coefs[modimpl_mask]
|
||||
|
||||
nb_etuds, nb_modules = sem_matrix.shape
|
||||
assert len(modimpl_coefs) == nb_modules
|
||||
nb_ues = len(ues) # en comptant bonus
|
||||
|
||||
# Enlève les NaN du numérateur:
|
||||
sem_matrix_no_nan = np.nan_to_num(sem_matrix, nan=0.0)
|
||||
# Ne prend pas en compte les notes des étudiants non inscrits au module:
|
||||
# Annule les notes:
|
||||
sem_matrix_inscrits = np.where(modimpl_inscr, sem_matrix_no_nan, 0.0)
|
||||
# Annule les coefs des modules où l'étudiant n'est pas inscrit:
|
||||
modimpl_coefs_etuds = np.where(
|
||||
modimpl_inscr, np.stack([modimpl_coefs.T] * nb_etuds), 0.0
|
||||
)
|
||||
# Annule les coefs des modules NaN (nb_etuds x nb_mods)
|
||||
modimpl_coefs_etuds_no_nan = np.where(
|
||||
np.isnan(sem_matrix), 0.0, modimpl_coefs_etuds
|
||||
)
|
||||
if modimpl_coefs_etuds_no_nan.dtype == np.object: # arrive sur des tableaux vides
|
||||
modimpl_coefs_etuds_no_nan = modimpl_coefs_etuds_no_nan.astype(np.float)
|
||||
# --------------------- Calcul des moyennes d'UE
|
||||
ue_modules = np.array(
|
||||
[[m.module.ue == ue for m in formsemestre.modimpls_sorted] for ue in ues]
|
||||
)[..., np.newaxis][:, modimpl_mask, :]
|
||||
modimpl_coefs_etuds_no_nan_stacked = np.stack(
|
||||
[modimpl_coefs_etuds_no_nan.T] * nb_ues
|
||||
)
|
||||
# nb_ue x nb_etuds x nb_mods : coefs prenant en compte NaN et inscriptions:
|
||||
coefs = (modimpl_coefs_etuds_no_nan_stacked * ue_modules).swapaxes(1, 2)
|
||||
if coefs.dtype == np.object: # arrive sur des tableaux vides
|
||||
coefs = coefs.astype(np.float)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etud_moy_ue = (
|
||||
np.sum(coefs * sem_matrix_inscrits, axis=2) / np.sum(coefs, axis=2)
|
||||
).T
|
||||
etud_moy_ue_df = pd.DataFrame(
|
||||
etud_moy_ue, index=modimpl_inscr_df.index, columns=[ue.id for ue in ues]
|
||||
)
|
||||
|
||||
# --------------------- Calcul des moyennes générales
|
||||
if sco_preferences.get_preference("use_ue_coefs", formsemestre.id):
|
||||
# Cas avec coefficients d'UE forcés: (on met à zéro l'UE bonus)
|
||||
etud_coef_ue_df = pd.DataFrame(
|
||||
{ue.id: ue.coefficient if ue.type != UE_SPORT else 0.0 for ue in ues},
|
||||
index=modimpl_inscr_df.index,
|
||||
columns=[ue.id for ue in ues],
|
||||
)
|
||||
# remplace NaN par zéros dans les moyennes d'UE
|
||||
etud_moy_ue_df_no_nan = etud_moy_ue_df.fillna(0.0, inplace=False)
|
||||
# Si on voulait annuler les coef d'UE dont la moyenne d'UE est NaN
|
||||
# etud_coef_ue_df_no_nan = etud_coef_ue_df.where(etud_moy_ue_df.notna(), 0.0)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etud_moy_gen_s = (etud_coef_ue_df * etud_moy_ue_df_no_nan).sum(
|
||||
axis=1
|
||||
) / etud_coef_ue_df.sum(axis=1)
|
||||
else:
|
||||
# Cas normal: pondère directement les modules
|
||||
etud_coef_ue_df = pd.DataFrame(
|
||||
coefs.sum(axis=2).T,
|
||||
index=modimpl_inscr_df.index, # etudids
|
||||
columns=[ue.id for ue in ues],
|
||||
)
|
||||
with np.errstate(invalid="ignore"): # ignore les 0/0 (-> NaN)
|
||||
etud_moy_gen = np.sum(
|
||||
modimpl_coefs_etuds_no_nan * sem_matrix_inscrits, axis=1
|
||||
) / np.sum(modimpl_coefs_etuds_no_nan, axis=1)
|
||||
|
||||
etud_moy_gen_s = pd.Series(etud_moy_gen, index=modimpl_inscr_df.index)
|
||||
|
||||
return etud_moy_gen_s, etud_moy_ue_df, etud_coef_ue_df
|
||||
|
||||
|
||||
def compute_mat_moys_classic(
|
||||
sem_matrix: np.array,
|
||||
modimpl_inscr_df: pd.DataFrame,
|
||||
modimpl_coefs: np.array,
|
||||
modimpl_mask: np.array,
|
||||
) -> pd.Series:
|
||||
"""Calcul de la moyenne sur un sous-enemble de modules en formation CLASSIQUE
|
||||
|
||||
La moyenne est un nombre (note/20 ou NaN.
|
||||
|
||||
Le masque modimpl_mask est un tableau de booléens (un par modimpl) qui
|
||||
permet de sélectionner un sous-ensemble de modules (ceux de la matière d'intérêt).
|
||||
|
||||
sem_matrix: notes moyennes aux modules (tous les étuds x tous les modimpls)
|
||||
ndarray (etuds x modimpls)
|
||||
(floats avec des NaN)
|
||||
etuds : listes des étudiants (dim. 0 de la matrice)
|
||||
modimpl_inscr_df: matrice d'inscription du semestre (etud x modimpl)
|
||||
modimpl_coefs: vecteur des coefficients de modules
|
||||
modimpl_mask: masque des modimpls à prendre en compte
|
||||
|
||||
Résultat:
|
||||
- moyennes: pd.Series, index etudid
|
||||
"""
|
||||
if (not len(modimpl_mask)) or (
|
||||
sem_matrix.shape[0] == 0
|
||||
): # aucun module ou aucun étudiant
|
||||
# etud_moy_gen_s, etud_moy_ue_df, etud_coef_ue_df
|
||||
return pd.Series(
|
||||
[0.0] * len(modimpl_inscr_df.index), index=modimpl_inscr_df.index
|
||||
)
|
||||
# Restreint aux modules sélectionnés:
|
||||
sem_matrix = sem_matrix[:, modimpl_mask]
|
||||
modimpl_inscr = modimpl_inscr_df.values[:, modimpl_mask]
|
||||
modimpl_coefs = modimpl_coefs[modimpl_mask]
|
||||
|
||||
nb_etuds, nb_modules = sem_matrix.shape
|
||||
assert len(modimpl_coefs) == nb_modules
|
||||
|
||||
# Enlève les NaN du numérateur:
|
||||
sem_matrix_no_nan = np.nan_to_num(sem_matrix, nan=0.0)
|
||||
# Ne prend pas en compte les notes des étudiants non inscrits au module:
|
||||
# Annule les notes:
|
||||
sem_matrix_inscrits = np.where(modimpl_inscr, sem_matrix_no_nan, 0.0)
|
||||
# Annule les coefs des modules où l'étudiant n'est pas inscrit:
|
||||
modimpl_coefs_etuds = np.where(
|
||||
modimpl_inscr, np.stack([modimpl_coefs.T] * nb_etuds), 0.0
|
||||
)
|
||||
# Annule les coefs des modules NaN (nb_etuds x nb_mods)
|
||||
modimpl_coefs_etuds_no_nan = np.where(
|
||||
np.isnan(sem_matrix), 0.0, modimpl_coefs_etuds
|
||||
)
|
||||
if modimpl_coefs_etuds_no_nan.dtype == np.object: # arrive sur des tableaux vides
|
||||
modimpl_coefs_etuds_no_nan = modimpl_coefs_etuds_no_nan.astype(np.float)
|
||||
|
||||
etud_moy_mat = (modimpl_coefs_etuds_no_nan * sem_matrix_inscrits).sum(
|
||||
axis=1
|
||||
) / modimpl_coefs_etuds_no_nan.sum(axis=1)
|
||||
|
||||
return pd.Series(etud_moy_mat, index=modimpl_inscr_df.index)
|
||||
|
||||
|
||||
def compute_malus(
|
||||
formsemestre: FormSemestre,
|
||||
sem_modimpl_moys: np.array,
|
||||
ues: list[UniteEns],
|
||||
modimpl_inscr_df: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""Calcul le malus sur les UE
|
||||
Dans chaque UE, on peut avoir un ou plusieurs modules de MALUS.
|
||||
Leurs notes sont positives ou négatives.
|
||||
La somme des notes de malus somme est _soustraite_ à la moyenne de chaque UE.
|
||||
|
||||
Arguments:
|
||||
- sem_modimpl_moys :
|
||||
notes moyennes aux modules (tous les étuds x tous les modimpls)
|
||||
floats avec des NaN.
|
||||
En classique: sem_matrix, ndarray (etuds x modimpls)
|
||||
En APC: sem_cube, ndarray (etuds x modimpls x UEs non bonus)
|
||||
- ues: les ues du semestre (incluant le bonus sport)
|
||||
- modimpl_inscr_df: matrice d'inscription aux modules du semestre (etud x modimpl)
|
||||
|
||||
Résultat: DataFrame de float, index etudid, columns: ue.id (sans NaN)
|
||||
"""
|
||||
ues_idx = [ue.id for ue in ues]
|
||||
malus = pd.DataFrame(index=modimpl_inscr_df.index, columns=ues_idx, dtype=float)
|
||||
for ue in ues:
|
||||
if ue.type != UE_SPORT:
|
||||
modimpl_mask = np.array(
|
||||
[
|
||||
(m.module.module_type == ModuleType.MALUS)
|
||||
and (m.module.ue.id == ue.id)
|
||||
for m in formsemestre.modimpls_sorted
|
||||
]
|
||||
)
|
||||
if len(modimpl_mask):
|
||||
malus_moys = sem_modimpl_moys[:, modimpl_mask].sum(axis=1)
|
||||
malus[ue.id] = malus_moys
|
||||
|
||||
malus.fillna(0.0, inplace=True)
|
||||
return malus
|
||||
|
|
|
@ -0,0 +1,177 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Résultats semestres BUT
|
||||
"""
|
||||
import time
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from app import log
|
||||
from app.comp import moy_ue, moy_sem, inscr_mod
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.comp.bonus_spo import BonusSport
|
||||
from app.models import ScoDocSiteConfig
|
||||
from app.models.moduleimpls import ModuleImpl
|
||||
from app.models.ues import UniteEns
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
|
||||
class ResultatsSemestreBUT(NotesTableCompat):
|
||||
"""Résultats BUT: organisation des calculs"""
|
||||
|
||||
_cached_attrs = NotesTableCompat._cached_attrs + (
|
||||
"modimpl_coefs_df",
|
||||
"modimpls_evals_poids",
|
||||
"sem_cube",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre):
|
||||
super().__init__(formsemestre)
|
||||
|
||||
self.sem_cube = None
|
||||
"""ndarray (etuds x modimpl x ue)"""
|
||||
|
||||
if not self.load_cached():
|
||||
t0 = time.time()
|
||||
self.compute()
|
||||
t1 = time.time()
|
||||
self.store()
|
||||
t2 = time.time()
|
||||
log(
|
||||
f"""ResultatsSemestreBUT: cached formsemestre_id={formsemestre.id
|
||||
} ({(t1-t0):g}s +{(t2-t1):g}s)"""
|
||||
)
|
||||
|
||||
def compute(self):
|
||||
"Charge les notes et inscriptions et calcule les moyennes d'UE et gen."
|
||||
(
|
||||
self.sem_cube,
|
||||
self.modimpls_evals_poids,
|
||||
self.modimpls_results,
|
||||
) = moy_ue.notes_sem_load_cube(self.formsemestre)
|
||||
self.modimpl_inscr_df = inscr_mod.df_load_modimpl_inscr(self.formsemestre)
|
||||
self.modimpl_coefs_df, _, _ = moy_ue.df_load_modimpl_coefs(
|
||||
self.formsemestre, modimpls=self.formsemestre.modimpls_sorted
|
||||
)
|
||||
# l'idx de la colonne du mod modimpl.id est
|
||||
# modimpl_coefs_df.columns.get_loc(modimpl.id)
|
||||
# idx de l'UE: modimpl_coefs_df.index.get_loc(ue.id)
|
||||
|
||||
# Masque de tous les modules _sauf_ les bonus (sport)
|
||||
modimpls_mask = [
|
||||
modimpl.module.ue.type != UE_SPORT
|
||||
for modimpl in self.formsemestre.modimpls_sorted
|
||||
]
|
||||
|
||||
self.etud_moy_ue = moy_ue.compute_ue_moys_apc(
|
||||
self.sem_cube,
|
||||
self.etuds,
|
||||
self.formsemestre.modimpls_sorted,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs_df,
|
||||
modimpls_mask,
|
||||
)
|
||||
# Les coefficients d'UE ne sont pas utilisés en APC
|
||||
self.etud_coef_ue_df = pd.DataFrame(
|
||||
0.0, index=self.etud_moy_ue.index, columns=self.etud_moy_ue.columns
|
||||
)
|
||||
|
||||
# --- Modules de MALUS sur les UEs
|
||||
self.malus = moy_ue.compute_malus(
|
||||
self.formsemestre, self.sem_cube, self.ues, self.modimpl_inscr_df
|
||||
)
|
||||
self.etud_moy_ue -= self.malus
|
||||
|
||||
# --- Bonus Sport & Culture
|
||||
if not all(modimpls_mask): # au moins un module bonus
|
||||
bonus_class = ScoDocSiteConfig.get_bonus_sport_class()
|
||||
if bonus_class is not None:
|
||||
bonus: BonusSport = bonus_class(
|
||||
self.formsemestre,
|
||||
self.sem_cube,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs_df.transpose(),
|
||||
self.etud_moy_gen,
|
||||
self.etud_moy_ue,
|
||||
)
|
||||
self.bonus_ues = bonus.get_bonus_ues()
|
||||
if self.bonus_ues is not None:
|
||||
self.etud_moy_ue += self.bonus_ues # somme les dataframes
|
||||
|
||||
# Clippe toutes les moyennes d'UE dans [0,20]
|
||||
self.etud_moy_ue.clip(lower=0.0, upper=20.0, inplace=True)
|
||||
|
||||
# Moyenne générale indicative:
|
||||
# (note: le bonus sport a déjà été appliqué aux moyennes d'UE, et impacte
|
||||
# donc la moyenne indicative)
|
||||
# self.etud_moy_gen = moy_sem.compute_sem_moys_apc_using_coefs(
|
||||
# self.etud_moy_ue, self.modimpl_coefs_df
|
||||
# )
|
||||
self.etud_moy_gen = moy_sem.compute_sem_moys_apc_using_ects(
|
||||
self.etud_moy_ue,
|
||||
[ue.ects for ue in self.ues if ue.type != UE_SPORT],
|
||||
formation_id=self.formsemestre.formation_id,
|
||||
skip_empty_ues=sco_preferences.get_preference(
|
||||
"but_moy_skip_empty_ues", self.formsemestre.id
|
||||
),
|
||||
)
|
||||
# --- UE capitalisées
|
||||
self.apply_capitalisation()
|
||||
|
||||
# --- Classements:
|
||||
self.compute_rangs()
|
||||
|
||||
def get_etud_mod_moy(self, moduleimpl_id: int, etudid: int) -> float:
|
||||
"""La moyenne de l'étudiant dans le moduleimpl
|
||||
En APC, il s'agit d'une moyenne indicative sans valeur.
|
||||
Result: valeur float (peut être naN) ou chaîne "NI" (non inscrit ou DEM)
|
||||
"""
|
||||
mod_idx = self.modimpl_coefs_df.columns.get_loc(moduleimpl_id)
|
||||
etud_idx = self.etud_index[etudid]
|
||||
# moyenne sur les UE:
|
||||
if len(self.sem_cube[etud_idx, mod_idx]):
|
||||
return np.nanmean(self.sem_cube[etud_idx, mod_idx])
|
||||
return np.nan
|
||||
|
||||
def compute_etud_ue_coef(self, etudid: int, ue: UniteEns) -> float:
|
||||
"""Détermine le coefficient de l'UE pour cet étudiant.
|
||||
N'est utilisé que pour l'injection des UE capitalisées dans la
|
||||
moyenne générale.
|
||||
En BUT, c'est simple: Coef = somme des coefs des modules vers cette UE.
|
||||
(ne dépend pas des modules auxquels est inscrit l'étudiant, ).
|
||||
"""
|
||||
return self.modimpl_coefs_df.loc[ue.id].sum()
|
||||
|
||||
def modimpls_in_ue(self, ue_id, etudid, with_bonus=True) -> list[ModuleImpl]:
|
||||
"""Liste des modimpl ayant des coefs non nuls vers cette UE
|
||||
et auxquels l'étudiant est inscrit. Inclus modules bonus le cas échéant.
|
||||
"""
|
||||
# sert pour l'affichage ou non de l'UE sur le bulletin et la table recap
|
||||
coefs = self.modimpl_coefs_df # row UE, cols modimpl
|
||||
modimpls = [
|
||||
modimpl
|
||||
for modimpl in self.formsemestre.modimpls_sorted
|
||||
if (coefs[modimpl.id][ue_id] != 0)
|
||||
and self.modimpl_inscr_df[modimpl.id][etudid]
|
||||
]
|
||||
if not with_bonus:
|
||||
return [
|
||||
modimpl for modimpl in modimpls if modimpl.module.ue.type != UE_SPORT
|
||||
]
|
||||
return modimpls
|
||||
|
||||
def modimpl_notes(self, modimpl_id: int, ue_id: int) -> np.ndarray:
|
||||
"""Les notes moyennes des étudiants du sem. à ce modimpl dans cette ue.
|
||||
Utile pour stats bottom tableau recap.
|
||||
Résultat: 1d array of float
|
||||
"""
|
||||
i = self.modimpl_coefs_df.columns.get_loc(modimpl_id)
|
||||
j = self.modimpl_coefs_df.index.get_loc(ue_id)
|
||||
return self.sem_cube[:, i, j]
|
|
@ -0,0 +1,42 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Cache pour résultats (super classe)
|
||||
"""
|
||||
|
||||
from app.models import FormSemestre
|
||||
|
||||
|
||||
class ResultatsCache:
|
||||
"""Résultats cachés (via redis)
|
||||
L'attribut _cached_attrs donne la liste des noms des attributs à cacher
|
||||
(doivent être sérialisables facilement, se limiter à des types simples)
|
||||
|
||||
store() enregistre les attributs dans le cache, et
|
||||
load_cached() les recharge.
|
||||
"""
|
||||
|
||||
_cached_attrs = () # virtual
|
||||
|
||||
def __init__(self, formsemestre: FormSemestre, cache_class=None):
|
||||
self.formsemestre: FormSemestre = formsemestre
|
||||
self.cache_class = cache_class
|
||||
|
||||
def load_cached(self) -> bool:
|
||||
"Load cached dataframes, returns False si pas en cache"
|
||||
data = self.cache_class.get(self.formsemestre.id)
|
||||
if not data:
|
||||
return False
|
||||
for attr in self._cached_attrs:
|
||||
setattr(self, attr, data[attr])
|
||||
return True
|
||||
|
||||
def store(self):
|
||||
"Cache our data"
|
||||
self.cache_class.set(
|
||||
self.formsemestre.id,
|
||||
{attr: getattr(self, attr) for attr in self._cached_attrs},
|
||||
)
|
|
@ -0,0 +1,307 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Résultats semestres classiques (non APC)
|
||||
"""
|
||||
import time
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
from flask import g, url_for
|
||||
|
||||
from app import db
|
||||
from app import log
|
||||
from app.comp import moy_mat, moy_mod, moy_sem, moy_ue, inscr_mod
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.comp.bonus_spo import BonusSport
|
||||
from app.models import ScoDocSiteConfig
|
||||
from app.models.etudiants import Identite
|
||||
from app.models.formsemestre import FormSemestre
|
||||
from app.models.ues import UniteEns
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
class ResultatsSemestreClassic(NotesTableCompat):
|
||||
"""Résultats du semestre (formation classique): organisation des calculs."""
|
||||
|
||||
_cached_attrs = NotesTableCompat._cached_attrs + (
|
||||
"modimpl_coefs",
|
||||
"modimpl_idx",
|
||||
"sem_matrix",
|
||||
"mod_rangs",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre):
|
||||
super().__init__(formsemestre)
|
||||
self.sem_matrix: np.ndarray = None
|
||||
"sem_matrix : 2d-array (etuds x modimpls)"
|
||||
|
||||
if not self.load_cached():
|
||||
t0 = time.time()
|
||||
self.compute()
|
||||
t1 = time.time()
|
||||
self.store()
|
||||
t2 = time.time()
|
||||
log(
|
||||
f"""ResultatsSemestreClassic: cached formsemestre_id={
|
||||
formsemestre.id} ({(t1-t0):g}s +{(t2-t1):g}s)"""
|
||||
)
|
||||
# recalculé (aussi rapide que de les cacher)
|
||||
self.moy_min = self.etud_moy_gen.min()
|
||||
self.moy_max = self.etud_moy_gen.max()
|
||||
self.moy_moy = self.etud_moy_gen.mean()
|
||||
|
||||
def compute(self):
|
||||
"Charge les notes et inscriptions et calcule les moyennes d'UE et gen."
|
||||
self.sem_matrix, self.modimpls_results = notes_sem_load_matrix(
|
||||
self.formsemestre
|
||||
)
|
||||
self.modimpl_inscr_df = inscr_mod.df_load_modimpl_inscr(self.formsemestre)
|
||||
self.modimpl_coefs = np.array(
|
||||
[m.module.coefficient or 0.0 for m in self.formsemestre.modimpls_sorted]
|
||||
)
|
||||
self.modimpl_idx = {
|
||||
m.id: i for i, m in enumerate(self.formsemestre.modimpls_sorted)
|
||||
}
|
||||
"l'idx de la colonne du mod modimpl.id est modimpl_idx[modimpl.id]"
|
||||
|
||||
modimpl_standards_mask = np.array(
|
||||
[
|
||||
(m.module.module_type == ModuleType.STANDARD)
|
||||
and (m.module.ue.type != UE_SPORT)
|
||||
for m in self.formsemestre.modimpls_sorted
|
||||
]
|
||||
)
|
||||
(
|
||||
self.etud_moy_gen,
|
||||
self.etud_moy_ue,
|
||||
self.etud_coef_ue_df,
|
||||
) = moy_ue.compute_ue_moys_classic(
|
||||
self.formsemestre,
|
||||
self.sem_matrix,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs,
|
||||
modimpl_standards_mask,
|
||||
)
|
||||
# --- Modules de MALUS sur les UEs et la moyenne générale
|
||||
self.malus = moy_ue.compute_malus(
|
||||
self.formsemestre, self.sem_matrix, self.ues, self.modimpl_inscr_df
|
||||
)
|
||||
self.etud_moy_ue -= self.malus
|
||||
# ajuste la moyenne générale (à l'aide des coefs d'UE)
|
||||
self.etud_moy_gen -= (self.etud_coef_ue_df * self.malus).sum(
|
||||
axis=1
|
||||
) / self.etud_coef_ue_df.sum(axis=1)
|
||||
|
||||
# --- Bonus Sport & Culture
|
||||
bonus_class = ScoDocSiteConfig.get_bonus_sport_class()
|
||||
if bonus_class is not None:
|
||||
bonus: BonusSport = bonus_class(
|
||||
self.formsemestre,
|
||||
self.sem_matrix,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs,
|
||||
self.etud_moy_gen,
|
||||
self.etud_moy_ue,
|
||||
)
|
||||
self.bonus_ues = bonus.get_bonus_ues()
|
||||
if self.bonus_ues is not None:
|
||||
self.etud_moy_ue += self.bonus_ues # somme les dataframes
|
||||
self.etud_moy_ue.clip(lower=0.0, upper=20.0, inplace=True)
|
||||
bonus_mg = bonus.get_bonus_moy_gen()
|
||||
if bonus_mg is None and self.bonus_ues is not None:
|
||||
# pas de bonus explicite sur la moyenne générale
|
||||
# on l'ajuste pour refléter les modifs d'UE, à l'aide des coefs d'UE.
|
||||
bonus_mg = (self.etud_coef_ue_df * self.bonus_ues).sum(
|
||||
axis=1
|
||||
) / self.etud_coef_ue_df.sum(axis=1)
|
||||
self.etud_moy_gen += bonus_mg
|
||||
elif bonus_mg is not None:
|
||||
# Applique le bonus moyenne générale renvoyé
|
||||
self.etud_moy_gen += bonus_mg
|
||||
|
||||
# compat nt, utilisé pour l'afficher sur les bulletins:
|
||||
self.bonus = bonus_mg
|
||||
|
||||
# --- UE capitalisées
|
||||
self.apply_capitalisation()
|
||||
|
||||
# Clippe toutes les moyennes dans [0,20]
|
||||
self.etud_moy_ue.clip(lower=0.0, upper=20.0, inplace=True)
|
||||
self.etud_moy_gen.clip(lower=0.0, upper=20.0, inplace=True)
|
||||
|
||||
# --- Classements:
|
||||
self.compute_rangs()
|
||||
|
||||
# --- En option, moyennes par matières
|
||||
if sco_preferences.get_preference("bul_show_matieres", self.formsemestre.id):
|
||||
self.compute_moyennes_matieres()
|
||||
|
||||
def compute_rangs(self):
|
||||
"""Calcul des rangs (classements) dans le semestre (moy. gen.), les UE
|
||||
et les modules.
|
||||
"""
|
||||
# rangs moy gen et UEs sont calculées par la méthode commune à toutes les formations:
|
||||
super().compute_rangs()
|
||||
# les rangs des modules n'existent que dans les formations classiques:
|
||||
self.mod_rangs = {}
|
||||
for modimpl_result in self.modimpls_results.values():
|
||||
# ne prend que les rangs sous forme de chaines:
|
||||
rangs = moy_sem.comp_ranks_series(modimpl_result.etuds_moy_module)[0]
|
||||
self.mod_rangs[modimpl_result.moduleimpl_id] = (
|
||||
rangs,
|
||||
modimpl_result.nb_inscrits_module,
|
||||
)
|
||||
|
||||
def get_etud_mod_moy(self, moduleimpl_id: int, etudid: int) -> float:
|
||||
"""La moyenne de l'étudiant dans le moduleimpl
|
||||
Result: valeur float (peut être NaN) ou chaîne "NI" (non inscrit ou DEM)
|
||||
"""
|
||||
try:
|
||||
if self.modimpl_inscr_df[moduleimpl_id][etudid]:
|
||||
return self.modimpls_results[moduleimpl_id].etuds_moy_module[etudid]
|
||||
except KeyError:
|
||||
pass
|
||||
return "NI"
|
||||
|
||||
def get_mod_stats(self, moduleimpl_id: int) -> dict:
|
||||
"""Stats sur les notes obtenues dans un modimpl"""
|
||||
notes_series: pd.Series = self.modimpls_results[moduleimpl_id].etuds_moy_module
|
||||
nb_notes = len(notes_series)
|
||||
if not nb_notes:
|
||||
super().get_mod_stats(moduleimpl_id)
|
||||
return {
|
||||
# Series: Statistical methods from ndarray have been overridden to automatically
|
||||
# exclude missing data (currently represented as NaN)
|
||||
"moy": notes_series.mean(), # donc sans prendre en compte les NaN
|
||||
"max": notes_series.max(),
|
||||
"min": notes_series.min(),
|
||||
"nb_notes": nb_notes,
|
||||
"nb_missing": sum(notes_series.isna()),
|
||||
"nb_valid_evals": sum(
|
||||
self.modimpls_results[moduleimpl_id].evaluations_completes
|
||||
),
|
||||
}
|
||||
|
||||
def modimpl_notes(
|
||||
self,
|
||||
modimpl_id: int,
|
||||
ue_id: int = None,
|
||||
) -> np.ndarray:
|
||||
"""Les notes moyennes des étudiants du sem. à ce modimpl dans cette ue.
|
||||
Utile pour stats bottom tableau recap.
|
||||
ue_id n'est pas utilisé ici (formations classiques)
|
||||
Résultat: 1d array of float
|
||||
"""
|
||||
i = self.modimpl_idx[modimpl_id]
|
||||
return self.sem_matrix[:, i]
|
||||
|
||||
def compute_moyennes_matieres(self):
|
||||
"""Calcul les moyennes par matière. Doit être appelée au besoin, en fin de compute."""
|
||||
self.moyennes_matieres = moy_mat.compute_mat_moys_classic(
|
||||
self.formsemestre,
|
||||
self.sem_matrix,
|
||||
self.ues,
|
||||
self.modimpl_inscr_df,
|
||||
self.modimpl_coefs,
|
||||
)
|
||||
|
||||
def compute_etud_ue_coef(self, etudid: int, ue: UniteEns) -> float:
|
||||
"""Détermine le coefficient de l'UE pour cet étudiant.
|
||||
N'est utilisé que pour l'injection des UE capitalisées dans la
|
||||
moyenne générale.
|
||||
Coef = somme des coefs des modules de l'UE auxquels il est inscrit
|
||||
"""
|
||||
coef = comp_etud_sum_coef_modules_ue(self.formsemestre.id, etudid, ue["ue_id"])
|
||||
if coef is not None: # inscrit à au moins un module de cette UE
|
||||
return coef
|
||||
# arfff: aucun moyen de déterminer le coefficient de façon sûre
|
||||
log(
|
||||
f"""* oups: calcul coef UE impossible\nformsemestre_id='{self.formsemestre.id
|
||||
}'\netudid='{etudid}'\nue={ue}"""
|
||||
)
|
||||
etud: Identite = Identite.query.get(etudid)
|
||||
raise ScoValueError(
|
||||
f"""<div class="scovalueerror"><p>Coefficient de l'UE capitalisée {ue.acronyme}
|
||||
impossible à déterminer pour l'étudiant <a href="{
|
||||
url_for("scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=etudid)
|
||||
}" class="discretelink">{etud.nom_disp()}</a></p>
|
||||
<p>Il faut <a href="{
|
||||
url_for("notes.formsemestre_edit_uecoefs", scodoc_dept=g.scodoc_dept,
|
||||
formsemestre_id=self.formsemestre.id, err_ue_id=ue["ue_id"],
|
||||
)
|
||||
}">saisir le coefficient de cette UE avant de continuer</a></p>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def notes_sem_load_matrix(formsemestre: FormSemestre) -> tuple[np.ndarray, dict]:
|
||||
"""Calcule la matrice des notes du semestre
|
||||
(charge toutes les notes, calcule les moyennes des modules
|
||||
et assemble la matrice)
|
||||
Resultat:
|
||||
sem_matrix : 2d-array (etuds x modimpls)
|
||||
modimpls_results dict { modimpl.id : ModuleImplResultsClassic }
|
||||
"""
|
||||
modimpls_results = {}
|
||||
modimpls_notes = []
|
||||
for modimpl in formsemestre.modimpls_sorted:
|
||||
mod_results = moy_mod.ModuleImplResultsClassic(modimpl)
|
||||
etuds_moy_module = mod_results.compute_module_moy()
|
||||
modimpls_results[modimpl.id] = mod_results
|
||||
modimpls_notes.append(etuds_moy_module)
|
||||
return (
|
||||
notes_sem_assemble_matrix(modimpls_notes),
|
||||
modimpls_results,
|
||||
)
|
||||
|
||||
|
||||
def notes_sem_assemble_matrix(modimpls_notes: list[pd.Series]) -> np.ndarray:
|
||||
"""Réuni les notes moyennes des modules du semestre en une matrice
|
||||
|
||||
modimpls_notes : liste des moyennes de module
|
||||
(Series rendus par compute_module_moy, index: etud)
|
||||
Resultat: ndarray (etud x module)
|
||||
"""
|
||||
if not modimpls_notes:
|
||||
return np.zeros((0, 0), dtype=float)
|
||||
modimpls_notes_arr = [s.values for s in modimpls_notes]
|
||||
modimpls_notes = np.stack(modimpls_notes_arr)
|
||||
# passe de (mod x etud) à (etud x mod)
|
||||
return modimpls_notes.T
|
||||
|
||||
|
||||
def comp_etud_sum_coef_modules_ue(formsemestre_id, etudid, ue_id):
|
||||
"""Somme des coefficients des modules de l'UE dans lesquels cet étudiant est inscrit
|
||||
ou None s'il n'y a aucun module.
|
||||
"""
|
||||
# comme l'ancien notes_table.comp_etud_sum_coef_modules_ue
|
||||
# mais en raw sqlalchemy et la somme en SQL
|
||||
sql = text(
|
||||
"""
|
||||
SELECT sum(mod.coefficient)
|
||||
FROM notes_modules mod, notes_moduleimpl mi, notes_moduleimpl_inscription ins
|
||||
WHERE mod.id = mi.module_id
|
||||
and ins.etudid = :etudid
|
||||
and ins.moduleimpl_id = mi.id
|
||||
and mi.formsemestre_id = :formsemestre_id
|
||||
and mod.ue_id = :ue_id
|
||||
"""
|
||||
)
|
||||
cursor = db.session.execute(
|
||||
sql, {"etudid": etudid, "formsemestre_id": formsemestre_id, "ue_id": ue_id}
|
||||
)
|
||||
r = cursor.fetchone()
|
||||
if r is None:
|
||||
return None
|
||||
return r[0]
|
|
@ -0,0 +1,874 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Résultats semestre: méthodes communes aux formations classiques et APC
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from functools import cached_property
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from flask import g, url_for
|
||||
|
||||
from app.auth.models import User
|
||||
from app.comp.res_cache import ResultatsCache
|
||||
from app.comp import res_sem
|
||||
from app.comp.moy_mod import ModuleImplResults
|
||||
from app.models import FormSemestre, FormSemestreUECoef
|
||||
from app.models import Identite
|
||||
from app.models import ModuleImpl, ModuleImplInscription
|
||||
from app.models.ues import UniteEns
|
||||
from app.scodoc.sco_cache import ResultatsSemestreCache
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT, DEF, DEM
|
||||
from app.scodoc import sco_evaluation_db
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
from app.scodoc import sco_groups
|
||||
from app.scodoc import sco_utils as scu
|
||||
|
||||
# Il faut bien distinguer
|
||||
# - ce qui est caché de façon persistente (via redis):
|
||||
# ce sont les attributs listés dans `_cached_attrs`
|
||||
# le stockage et l'invalidation sont gérés dans sco_cache.py
|
||||
#
|
||||
# - les valeurs cachées durant le temps d'une requête
|
||||
# (durée de vie de l'instance de ResultatsSemestre)
|
||||
# qui sont notamment les attributs décorés par `@cached_property``
|
||||
#
|
||||
class ResultatsSemestre(ResultatsCache):
|
||||
"""Les résultats (notes, ...) d'un formsemestre
|
||||
Classe commune à toutes les formations (classiques, BUT)
|
||||
"""
|
||||
|
||||
_cached_attrs = (
|
||||
"bonus",
|
||||
"bonus_ues",
|
||||
"etud_moy_gen_ranks",
|
||||
"etud_moy_gen",
|
||||
"etud_moy_ue",
|
||||
"modimpl_inscr_df",
|
||||
"modimpls_results",
|
||||
"etud_coef_ue_df",
|
||||
"moyennes_matieres",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre: FormSemestre):
|
||||
super().__init__(formsemestre, ResultatsSemestreCache)
|
||||
# BUT ou standard ? (apc == "approche par compétences")
|
||||
self.is_apc = formsemestre.formation.is_apc()
|
||||
# Attributs "virtuels", définis dans les sous-classes
|
||||
self.bonus: pd.Series = None # virtuel
|
||||
"Bonus sur moy. gen. Series de float, index etudid"
|
||||
self.bonus_ues: pd.DataFrame = None # virtuel
|
||||
"DataFrame de float, index etudid, columns: ue.id"
|
||||
# ResultatsSemestreBUT ou ResultatsSemestreClassic
|
||||
self.etud_moy_ue = {}
|
||||
"etud_moy_ue: DataFrame columns UE, rows etudid"
|
||||
self.etud_moy_gen: pd.Series = None
|
||||
self.etud_moy_gen_ranks = {}
|
||||
self.etud_moy_gen_ranks_int = {}
|
||||
self.modimpl_inscr_df: pd.DataFrame = None
|
||||
"Inscriptions: row etudid, col modimlpl_id"
|
||||
self.modimpls_results: ModuleImplResults = None
|
||||
"Résultats de chaque modimpl: dict { modimpl.id : ModuleImplResults(Classique ou BUT) }"
|
||||
self.etud_coef_ue_df = None
|
||||
"""coefs d'UE effectifs pour chaque étudiant (pour form. classiques)"""
|
||||
self.modimpl_coefs_df: pd.DataFrame = None
|
||||
"""Coefs APC: rows = UEs (sans bonus), columns = modimpl, value = coef."""
|
||||
|
||||
self.validations = None
|
||||
self.moyennes_matieres = {}
|
||||
"""Moyennes de matières, si calculées. { matiere_id : Series, index etudid }"""
|
||||
|
||||
def __repr__(self):
|
||||
return f"<{self.__class__.__name__}(formsemestre='{self.formsemestre}')>"
|
||||
|
||||
def compute(self):
|
||||
"Charge les notes et inscriptions et calcule toutes les moyennes"
|
||||
# voir ce qui est chargé / calculé ici et dans les sous-classes
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_inscriptions_counts(self) -> Counter:
|
||||
"""Nombre d'inscrits, défaillants, démissionnaires.
|
||||
|
||||
Exemple: res.get_inscriptions_counts()[scu.INSCRIT]
|
||||
|
||||
Result: a collections.Counter instance
|
||||
"""
|
||||
return Counter(ins.etat for ins in self.formsemestre.inscriptions)
|
||||
|
||||
@cached_property
|
||||
def etuds(self) -> list[Identite]:
|
||||
"Liste des inscrits au semestre, avec les démissionnaires et les défaillants"
|
||||
# nb: si la liste des inscrits change, ResultatsSemestre devient invalide
|
||||
return self.formsemestre.get_inscrits(include_demdef=True)
|
||||
|
||||
@cached_property
|
||||
def etud_index(self) -> dict[int, int]:
|
||||
"dict { etudid : indice dans les inscrits }"
|
||||
return {e.id: idx for idx, e in enumerate(self.etuds)}
|
||||
|
||||
def modimpl_notes(self, modimpl_id: int, ue_id: int) -> np.ndarray:
|
||||
"""Les notes moyennes des étudiants du sem. à ce modimpl dans cette ue.
|
||||
Utile pour stats bottom tableau recap.
|
||||
Résultat: 1d array of float
|
||||
"""
|
||||
# différent en BUT et classique: virtuelle
|
||||
raise NotImplementedError
|
||||
|
||||
@cached_property
|
||||
def etuds_dict(self) -> dict[int, Identite]:
|
||||
"""dict { etudid : Identite } inscrits au semestre,
|
||||
avec les démissionnaires et defs."""
|
||||
return {etud.id: etud for etud in self.etuds}
|
||||
|
||||
@cached_property
|
||||
def ues(self) -> list[UniteEns]:
|
||||
"""Liste des UEs du semestre (avec les UE bonus sport)
|
||||
(indices des DataFrames).
|
||||
Note: un étudiant n'est pas nécessairement inscrit dans toutes ces UEs.
|
||||
"""
|
||||
return self.formsemestre.query_ues(with_sport=True).all()
|
||||
|
||||
@cached_property
|
||||
def ressources(self):
|
||||
"Liste des ressources du semestre, triées par numéro de module"
|
||||
return [
|
||||
m
|
||||
for m in self.formsemestre.modimpls_sorted
|
||||
if m.module.module_type == scu.ModuleType.RESSOURCE
|
||||
]
|
||||
|
||||
@cached_property
|
||||
def saes(self):
|
||||
"Liste des SAÉs du semestre, triées par numéro de module"
|
||||
return [
|
||||
m
|
||||
for m in self.formsemestre.modimpls_sorted
|
||||
if m.module.module_type == scu.ModuleType.SAE
|
||||
]
|
||||
|
||||
def get_etud_ue_validables(self, etudid: int) -> list[UniteEns]:
|
||||
"""Liste des UEs du semestre qui doivent être validées
|
||||
|
||||
Rappel: l'étudiant est inscrit à des modimpls et non à des UEs.
|
||||
|
||||
- En BUT: on considère que l'étudiant va (ou non) valider toutes les UEs des modules
|
||||
du parcours. XXX notion à implémenter, pour l'instant toutes les UE du semestre.
|
||||
|
||||
- En classique: toutes les UEs des modimpls auxquels l'étudiant est inscrit sont
|
||||
susceptibles d'être validées.
|
||||
|
||||
Les UE "bonus" (sport) ne sont jamais "validables".
|
||||
"""
|
||||
if self.is_apc:
|
||||
# TODO: introduire la notion de parcours (#sco93)
|
||||
return self.formsemestre.query_ues().filter(UniteEns.type != UE_SPORT).all()
|
||||
else:
|
||||
# restreint aux UE auxquelles l'étudiant est inscrit (dans l'un des modimpls)
|
||||
ues = {
|
||||
modimpl.module.ue
|
||||
for modimpl in self.formsemestre.modimpls_sorted
|
||||
if self.modimpl_inscr_df[modimpl.id][etudid]
|
||||
}
|
||||
ues = sorted(list(ues), key=lambda x: x.numero or 0)
|
||||
return ues
|
||||
|
||||
def modimpls_in_ue(self, ue_id, etudid, with_bonus=True) -> list[ModuleImpl]:
|
||||
"""Liste des modimpl de cette UE auxquels l'étudiant est inscrit.
|
||||
Utile en formations classiques, surchargée pour le BUT.
|
||||
Inclus modules bonus le cas échéant.
|
||||
"""
|
||||
# sert pour l'affichage ou non de l'UE sur le bulletin
|
||||
# Méthode surchargée en BUT
|
||||
modimpls = [
|
||||
modimpl
|
||||
for modimpl in self.formsemestre.modimpls_sorted
|
||||
if modimpl.module.ue.id == ue_id
|
||||
and self.modimpl_inscr_df[modimpl.id][etudid]
|
||||
]
|
||||
if not with_bonus:
|
||||
return [
|
||||
modimpl for modimpl in modimpls if modimpl.module.ue.type != UE_SPORT
|
||||
]
|
||||
return modimpls
|
||||
|
||||
@cached_property
|
||||
def ue_au_dessus(self, seuil=10.0) -> pd.DataFrame:
|
||||
"""DataFrame columns UE, rows etudid, valeurs: bool
|
||||
Par exemple, pour avoir le nombre d'UE au dessus de 10 pour l'étudiant etudid
|
||||
nb_ues_ok = sum(res.ue_au_dessus().loc[etudid])
|
||||
"""
|
||||
return self.etud_moy_ue > (seuil - scu.NOTES_TOLERANCE)
|
||||
|
||||
def apply_capitalisation(self):
|
||||
"""Recalcule la moyenne générale pour prendre en compte d'éventuelles
|
||||
UE capitalisées.
|
||||
"""
|
||||
# Supposant qu'il y a peu d'UE capitalisées,
|
||||
# on va soustraire la moyenne d'UE et ajouter celle de l'UE capitalisée.
|
||||
if not self.validations:
|
||||
self.validations = res_sem.load_formsemestre_validations(self.formsemestre)
|
||||
ue_capitalisees = self.validations.ue_capitalisees
|
||||
for etudid in ue_capitalisees.index:
|
||||
recompute_mg = False
|
||||
# ue_codes = set(ue_capitalisees.loc[etudid]["ue_code"])
|
||||
# for ue_code in ue_codes:
|
||||
# ue = ue_by_code.get(ue_code)
|
||||
# if ue is None:
|
||||
# ue = self.formsemestre.query_ues.filter_by(ue_code=ue_code)
|
||||
# ue_by_code[ue_code] = ue
|
||||
|
||||
# Quand il y a une capitalisation, vérifie toutes les UEs
|
||||
sum_notes_ue = 0.0
|
||||
sum_coefs_ue = 0.0
|
||||
for ue in self.formsemestre.query_ues():
|
||||
ue_cap = self.get_etud_ue_status(etudid, ue.id)
|
||||
if ue_cap is None:
|
||||
continue
|
||||
if ue_cap["is_capitalized"]:
|
||||
recompute_mg = True
|
||||
coef = ue_cap["coef_ue"]
|
||||
if not np.isnan(ue_cap["moy"]) and coef:
|
||||
sum_notes_ue += ue_cap["moy"] * coef
|
||||
sum_coefs_ue += coef
|
||||
|
||||
if recompute_mg and sum_coefs_ue > 0.0:
|
||||
# On doit prendre en compte une ou plusieurs UE capitalisées
|
||||
# et donc recalculer la moyenne générale
|
||||
self.etud_moy_gen[etudid] = sum_notes_ue / sum_coefs_ue
|
||||
# Ajoute le bonus sport
|
||||
if self.bonus is not None and self.bonus[etudid]:
|
||||
self.etud_moy_gen[etudid] += self.bonus[etudid]
|
||||
self.etud_moy_gen[etudid] = max(
|
||||
0.0, min(self.etud_moy_gen[etudid], 20.0)
|
||||
)
|
||||
|
||||
def get_etud_etat(self, etudid: int) -> str:
|
||||
"Etat de l'etudiant: 'I', 'D', DEF ou '' (si pas connu dans ce semestre)"
|
||||
ins = self.formsemestre.etuds_inscriptions.get(etudid, None)
|
||||
if ins is None:
|
||||
return ""
|
||||
return ins.etat
|
||||
|
||||
def _get_etud_ue_cap(self, etudid: int, ue: UniteEns) -> dict:
|
||||
"""Donne les informations sur la capitalisation de l'UE ue pour cet étudiant.
|
||||
Résultat:
|
||||
Si pas capitalisée: None
|
||||
Si capitalisée: un dict, avec les colonnes de validation.
|
||||
"""
|
||||
capitalisations = self.validations.ue_capitalisees.loc[etudid]
|
||||
if isinstance(capitalisations, pd.DataFrame):
|
||||
ue_cap = capitalisations[capitalisations["ue_code"] == ue.ue_code]
|
||||
if ue_cap.empty:
|
||||
return None
|
||||
if isinstance(ue_cap, pd.DataFrame):
|
||||
# si plusieurs fois capitalisée, prend le max
|
||||
cap_idx = ue_cap["moy_ue"].values.argmax()
|
||||
ue_cap = ue_cap.iloc[cap_idx]
|
||||
else:
|
||||
if capitalisations["ue_code"] == ue.ue_code:
|
||||
ue_cap = capitalisations
|
||||
else:
|
||||
return None
|
||||
# converti la Series en dict, afin que les np.int64 reviennent en int
|
||||
return ue_cap.to_dict()
|
||||
|
||||
def get_etud_ue_status(self, etudid: int, ue_id: int) -> dict:
|
||||
"""L'état de l'UE pour cet étudiant.
|
||||
Result: dict, ou None si l'UE n'est pas dans ce semestre.
|
||||
"""
|
||||
ue = UniteEns.query.get(ue_id) # TODO cacher nos UEs ?
|
||||
if ue.type == UE_SPORT:
|
||||
return {
|
||||
"is_capitalized": False,
|
||||
"was_capitalized": False,
|
||||
"is_external": False,
|
||||
"coef_ue": 0.0,
|
||||
"cur_moy_ue": 0.0,
|
||||
"moy": 0.0,
|
||||
"event_date": None,
|
||||
"ue": ue.to_dict(),
|
||||
"formsemestre_id": None,
|
||||
"capitalized_ue_id": None,
|
||||
"ects_pot": 0.0,
|
||||
}
|
||||
if not ue_id in self.etud_moy_ue:
|
||||
return None
|
||||
if not self.validations:
|
||||
self.validations = res_sem.load_formsemestre_validations(self.formsemestre)
|
||||
cur_moy_ue = self.etud_moy_ue[ue_id][etudid]
|
||||
moy_ue = cur_moy_ue
|
||||
is_capitalized = False # si l'UE prise en compte est une UE capitalisée
|
||||
# s'il y a precedemment une UE capitalisée (pas forcement meilleure):
|
||||
was_capitalized = False
|
||||
if etudid in self.validations.ue_capitalisees.index:
|
||||
ue_cap = self._get_etud_ue_cap(etudid, ue)
|
||||
if ue_cap and not np.isnan(ue_cap["moy_ue"]):
|
||||
was_capitalized = True
|
||||
if ue_cap["moy_ue"] > cur_moy_ue or np.isnan(cur_moy_ue):
|
||||
moy_ue = ue_cap["moy_ue"]
|
||||
is_capitalized = True
|
||||
|
||||
# Coef l'UE dans le semestre courant:
|
||||
if self.is_apc:
|
||||
# utilise les ECTS comme coef.
|
||||
coef_ue = ue.ects
|
||||
else:
|
||||
# formations classiques
|
||||
coef_ue = self.etud_coef_ue_df[ue_id][etudid]
|
||||
if (not coef_ue) and is_capitalized: # étudiant non inscrit dans l'UE courante
|
||||
if self.is_apc:
|
||||
# Coefs de l'UE capitalisée en formation APC: donné par ses ECTS
|
||||
ue_capitalized = UniteEns.query.get(ue_cap["ue_id"])
|
||||
coef_ue = ue_capitalized.ects
|
||||
if coef_ue is None:
|
||||
orig_sem = FormSemestre.query.get(ue_cap["formsemestre_id"])
|
||||
raise ScoValueError(
|
||||
f"""L'UE capitalisée {ue_capitalized.acronyme}
|
||||
du semestre {orig_sem.titre_annee()}
|
||||
n'a pas d'indication d'ECTS.
|
||||
Corrigez ou faite corriger le programme
|
||||
<a href="{url_for('notes.ue_table', scodoc_dept=g.scodoc_dept,
|
||||
formation_id=ue_capitalized.formation_id)}">via cette page</a>.
|
||||
"""
|
||||
)
|
||||
else:
|
||||
# Coefs de l'UE capitalisée en formation classique:
|
||||
# va chercher le coef dans le semestre d'origine
|
||||
coef_ue = ModuleImplInscription.sum_coefs_modimpl_ue(
|
||||
ue_cap["formsemestre_id"], etudid, ue_cap["ue_id"]
|
||||
)
|
||||
|
||||
return {
|
||||
"is_capitalized": is_capitalized,
|
||||
"was_capitalized": was_capitalized,
|
||||
"is_external": ue_cap["is_external"] if is_capitalized else ue.is_external,
|
||||
"coef_ue": coef_ue,
|
||||
"ects_pot": ue.ects or 0.0,
|
||||
"cur_moy_ue": cur_moy_ue,
|
||||
"moy": moy_ue,
|
||||
"event_date": ue_cap["event_date"] if is_capitalized else None,
|
||||
"ue": ue.to_dict(),
|
||||
"formsemestre_id": ue_cap["formsemestre_id"] if is_capitalized else None,
|
||||
"capitalized_ue_id": ue_cap["ue_id"] if is_capitalized else None,
|
||||
}
|
||||
|
||||
def compute_etud_ue_coef(self, etudid: int, ue: UniteEns) -> float:
|
||||
"Détermine le coefficient de l'UE pour cet étudiant."
|
||||
# calcul différent en classqiue et BUT
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_etud_ue_cap_coef(self, etudid, ue, ue_cap):
|
||||
"""Calcule le coefficient d'une UE capitalisée, pour cet étudiant,
|
||||
injectée dans le semestre courant.
|
||||
|
||||
ue : ue du semestre courant
|
||||
|
||||
ue_cap = resultat de formsemestre_get_etud_capitalisation
|
||||
{ 'ue_id' (dans le semestre source),
|
||||
'ue_code', 'moy', 'event_date','formsemestre_id' }
|
||||
"""
|
||||
# 1- Coefficient explicitement déclaré dans le semestre courant pour cette UE ?
|
||||
ue_coef_db = FormSemestreUECoef.query.filter_by(
|
||||
formsemestre_id=self.formsemestre.id, ue_id=ue.id
|
||||
).first()
|
||||
if ue_coef_db is not None:
|
||||
return ue_coef_db.coefficient
|
||||
|
||||
# En APC: somme des coefs des modules vers cette UE
|
||||
# En classique: Capitalisation UE externe: quel coef appliquer ?
|
||||
# En ScoDoc 7, calculait la somme des coefs dans l'UE du semestre d'origine
|
||||
# ici si l'étudiant est inscrit dans le semestre courant,
|
||||
# somme des coefs des modules de l'UE auxquels il est inscrit
|
||||
return self.compute_etud_ue_coef(etudid, ue)
|
||||
|
||||
# --- TABLEAU RECAP
|
||||
|
||||
def get_table_recap(self, convert_values=False, include_evaluations=False):
|
||||
"""Result: tuple avec
|
||||
- rows: liste de dicts { column_id : value }
|
||||
- titles: { column_id : title }
|
||||
- columns_ids: (liste des id de colonnes)
|
||||
|
||||
. Si convert_values, transforme les notes en chaines ("12.34").
|
||||
Les colonnes générées sont:
|
||||
etudid
|
||||
rang : rang indicatif (basé sur moy gen)
|
||||
moy_gen : moy gen indicative
|
||||
moy_ue_<ue_id>, ..., les moyennes d'UE
|
||||
moy_res_<modimpl_id>_<ue_id>, ... les moyennes de ressources dans l'UE
|
||||
moy_sae_<modimpl_id>_<ue_id>, ... les moyennes de SAE dans l'UE
|
||||
|
||||
On ajoute aussi des attributs:
|
||||
- pour les lignes:
|
||||
_css_row_class (inutilisé pour le monent)
|
||||
_<column_id>_class classe css:
|
||||
- la moyenne générale a la classe col_moy_gen
|
||||
- les colonnes SAE ont la classe col_sae
|
||||
- les colonnes Resources ont la classe col_res
|
||||
- les colonnes d'UE ont la classe col_ue
|
||||
- les colonnes de modules (SAE ou res.) d'une UE ont la classe mod_ue_<ue_id>
|
||||
_<column_id>_order : clé de tri
|
||||
"""
|
||||
if convert_values:
|
||||
fmt_note = scu.fmt_note
|
||||
else:
|
||||
fmt_note = lambda x: x
|
||||
|
||||
parcours = self.formsemestre.formation.get_parcours()
|
||||
barre_moy = parcours.BARRE_MOY - scu.NOTES_TOLERANCE
|
||||
barre_valid_ue = parcours.NOTES_BARRE_VALID_UE
|
||||
barre_warning_ue = parcours.BARRE_UE_DISPLAY_WARNING
|
||||
NO_NOTE = "-" # contenu des cellules sans notes
|
||||
rows = []
|
||||
# column_id : title
|
||||
titles = {}
|
||||
# les titres en footer: les mêmes, mais avec des bulles et liens:
|
||||
titles_bot = {}
|
||||
dict_nom_res = {} # cache uid : nomcomplet
|
||||
|
||||
def add_cell(
|
||||
row: dict,
|
||||
col_id: str,
|
||||
title: str,
|
||||
content: str,
|
||||
classes: str = "",
|
||||
idx: int = 100,
|
||||
):
|
||||
"Add a row to our table. classes is a list of css class names"
|
||||
row[col_id] = content
|
||||
if classes:
|
||||
row[f"_{col_id}_class"] = classes + f" c{idx}"
|
||||
if not col_id in titles:
|
||||
titles[col_id] = title
|
||||
titles[f"_{col_id}_col_order"] = idx
|
||||
if classes:
|
||||
titles[f"_{col_id}_class"] = classes
|
||||
return idx + 1
|
||||
|
||||
etuds_inscriptions = self.formsemestre.etuds_inscriptions
|
||||
ues = self.formsemestre.query_ues(with_sport=True) # avec bonus
|
||||
ues_sans_bonus = [ue for ue in ues if ue.type != UE_SPORT]
|
||||
modimpl_ids = set() # modimpl effectivement présents dans la table
|
||||
for etudid in etuds_inscriptions:
|
||||
idx = 0 # index de la colonne
|
||||
etud = Identite.query.get(etudid)
|
||||
row = {"etudid": etudid}
|
||||
# --- Codes (seront cachés, mais exportés en excel)
|
||||
idx = add_cell(row, "etudid", "etudid", etudid, "codes", idx)
|
||||
idx = add_cell(
|
||||
row, "code_nip", "code_nip", etud.code_nip or "", "codes", idx
|
||||
)
|
||||
# --- Rang
|
||||
idx = add_cell(
|
||||
row, "rang", "Rg", self.etud_moy_gen_ranks[etudid], "rang", idx
|
||||
)
|
||||
row["_rang_order"] = f"{self.etud_moy_gen_ranks_int[etudid]:05d}"
|
||||
# --- Identité étudiant
|
||||
idx = add_cell(
|
||||
row, "civilite_str", "Civ.", etud.civilite_str, "identite_detail", idx
|
||||
)
|
||||
idx = add_cell(
|
||||
row, "nom_disp", "Nom", etud.nom_disp(), "identite_detail", idx
|
||||
)
|
||||
row["_nom_disp_order"] = etud.sort_key
|
||||
idx = add_cell(row, "prenom", "Prénom", etud.prenom, "identite_detail", idx)
|
||||
idx = add_cell(
|
||||
row, "nom_short", "Nom", etud.nom_short, "identite_court", idx
|
||||
)
|
||||
row["_nom_short_order"] = etud.sort_key
|
||||
row["_nom_short_target"] = url_for(
|
||||
"notes.formsemestre_bulletinetud",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formsemestre_id=self.formsemestre.id,
|
||||
etudid=etudid,
|
||||
)
|
||||
row["_nom_short_target_attrs"] = f'class="etudinfo" id="{etudid}"'
|
||||
row["_nom_disp_target"] = row["_nom_short_target"]
|
||||
row["_nom_disp_target_attrs"] = row["_nom_short_target_attrs"]
|
||||
|
||||
idx = 30 # début des colonnes de notes
|
||||
# --- Moyenne générale
|
||||
moy_gen = self.etud_moy_gen.get(etudid, False)
|
||||
note_class = ""
|
||||
if moy_gen is False:
|
||||
moy_gen = NO_NOTE
|
||||
elif isinstance(moy_gen, float) and moy_gen < barre_moy:
|
||||
note_class = " moy_ue_warning" # en rouge
|
||||
idx = add_cell(
|
||||
row,
|
||||
"moy_gen",
|
||||
"Moy",
|
||||
fmt_note(moy_gen),
|
||||
"col_moy_gen" + note_class,
|
||||
idx,
|
||||
)
|
||||
titles_bot["_moy_gen_target_attrs"] = (
|
||||
'title="moyenne indicative"' if self.is_apc else ""
|
||||
)
|
||||
# --- Moyenne d'UE
|
||||
nb_ues_validables, nb_ues_warning = 0, 0
|
||||
for ue in ues_sans_bonus:
|
||||
ue_status = self.get_etud_ue_status(etudid, ue.id)
|
||||
if ue_status is not None:
|
||||
col_id = f"moy_ue_{ue.id}"
|
||||
val = ue_status["moy"]
|
||||
note_class = ""
|
||||
if isinstance(val, float):
|
||||
if val < barre_moy:
|
||||
note_class = " moy_inf"
|
||||
elif val >= barre_valid_ue:
|
||||
note_class = " moy_ue_valid"
|
||||
nb_ues_validables += 1
|
||||
if val < barre_warning_ue:
|
||||
note_class = " moy_ue_warning" # notes très basses
|
||||
nb_ues_warning += 1
|
||||
idx = add_cell(
|
||||
row,
|
||||
col_id,
|
||||
ue.acronyme,
|
||||
fmt_note(val),
|
||||
"col_ue" + note_class,
|
||||
idx,
|
||||
)
|
||||
titles_bot[
|
||||
f"_{col_id}_target_attrs"
|
||||
] = f"""title="{ue.titre} S{ue.semestre_idx or '?'}" """
|
||||
# Bonus (sport) dans cette UE ?
|
||||
# Le bonus sport appliqué sur cette UE
|
||||
if (self.bonus_ues is not None) and (ue.id in self.bonus_ues):
|
||||
val = self.bonus_ues[ue.id][etud.id] or ""
|
||||
val_fmt = fmt_note(val)
|
||||
if val:
|
||||
val_fmt = f'<span class="green-arrow-up"></span><span class="sp2l">{val_fmt}</span>'
|
||||
idx = add_cell(
|
||||
row,
|
||||
f"bonus_ue_{ue.id}",
|
||||
f"Bonus {ue.acronyme}",
|
||||
val_fmt,
|
||||
"col_ue_bonus",
|
||||
idx,
|
||||
)
|
||||
# Les moyennes des modules (ou ressources et SAÉs) dans cette UE
|
||||
idx_malus = idx # place pour colonne malus à gauche des modules
|
||||
idx += 1
|
||||
for modimpl in self.modimpls_in_ue(ue.id, etudid, with_bonus=False):
|
||||
if ue_status["is_capitalized"]:
|
||||
val = "-c-"
|
||||
else:
|
||||
modimpl_results = self.modimpls_results.get(modimpl.id)
|
||||
if modimpl_results: # pas bonus
|
||||
if self.is_apc: # BUT
|
||||
moys_vers_ue = modimpl_results.etuds_moy_module.get(
|
||||
ue.id
|
||||
)
|
||||
val = (
|
||||
moys_vers_ue.get(etudid, "?")
|
||||
if moys_vers_ue is not None
|
||||
else ""
|
||||
)
|
||||
else: # classique: Series indépendante de l'UE
|
||||
val = modimpl_results.etuds_moy_module.get(
|
||||
etudid, "?"
|
||||
)
|
||||
else:
|
||||
val = ""
|
||||
|
||||
col_id = (
|
||||
f"moy_{modimpl.module.type_abbrv()}_{modimpl.id}_{ue.id}"
|
||||
)
|
||||
val_fmt = fmt_note(val)
|
||||
if modimpl.module.module_type == scu.ModuleType.MALUS:
|
||||
val_fmt = (
|
||||
(scu.EMO_RED_TRIANGLE_DOWN + val_fmt) if val else ""
|
||||
)
|
||||
idx = add_cell(
|
||||
row,
|
||||
col_id,
|
||||
modimpl.module.code,
|
||||
val_fmt,
|
||||
# class col_res mod_ue_123
|
||||
f"col_{modimpl.module.type_abbrv()} mod_ue_{ue.id}",
|
||||
idx,
|
||||
)
|
||||
if modimpl.module.module_type == scu.ModuleType.MALUS:
|
||||
titles[f"_{col_id}_col_order"] = idx_malus
|
||||
titles_bot[f"_{col_id}_target"] = url_for(
|
||||
"notes.moduleimpl_status",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
moduleimpl_id=modimpl.id,
|
||||
)
|
||||
nom_resp = dict_nom_res.get(modimpl.responsable_id)
|
||||
if nom_resp is None:
|
||||
user = User.query.get(modimpl.responsable_id)
|
||||
nom_resp = user.get_nomcomplet() if user else ""
|
||||
dict_nom_res[modimpl.responsable_id] = nom_resp
|
||||
titles_bot[
|
||||
f"_{col_id}_target_attrs"
|
||||
] = f""" title="{modimpl.module.titre} ({nom_resp})" """
|
||||
modimpl_ids.add(modimpl.id)
|
||||
ue_valid_txt = f"{nb_ues_validables}/{len(ues_sans_bonus)}"
|
||||
if nb_ues_warning:
|
||||
ue_valid_txt += " " + scu.EMO_WARNING
|
||||
add_cell(
|
||||
row,
|
||||
"ues_validables",
|
||||
"UEs",
|
||||
ue_valid_txt,
|
||||
"col_ue col_ues_validables",
|
||||
29, # juste avant moy. gen.
|
||||
)
|
||||
if nb_ues_warning:
|
||||
row["_ues_validables_class"] += " moy_ue_warning"
|
||||
elif nb_ues_validables < len(ues_sans_bonus):
|
||||
row["_ues_validables_class"] += " moy_inf"
|
||||
row["_ues_validables_order"] = nb_ues_validables # pour tri
|
||||
rows.append(row)
|
||||
|
||||
self._recap_add_partitions(rows, titles)
|
||||
self._recap_add_admissions(rows, titles)
|
||||
|
||||
# tri par rang croissant
|
||||
rows.sort(key=lambda e: e["_rang_order"])
|
||||
|
||||
# INFOS POUR FOOTER
|
||||
bottom_infos = self._recap_bottom_infos(ues_sans_bonus, modimpl_ids, fmt_note)
|
||||
if include_evaluations:
|
||||
self._recap_add_evaluations(rows, titles, bottom_infos)
|
||||
|
||||
# Ajoute style "col_empty" aux colonnes de modules vides
|
||||
for col_id in titles:
|
||||
c_class = f"_{col_id}_class"
|
||||
if "col_empty" in bottom_infos["moy"].get(c_class, ""):
|
||||
for row in rows:
|
||||
row[c_class] = row.get(c_class, "") + " col_empty"
|
||||
titles[c_class] += " col_empty"
|
||||
for row in bottom_infos.values():
|
||||
row[c_class] = row.get(c_class, "") + " col_empty"
|
||||
|
||||
# --- TABLE FOOTER: ECTS, moyennes, min, max...
|
||||
footer_rows = []
|
||||
for (bottom_line, row) in bottom_infos.items():
|
||||
# Cases vides à styler:
|
||||
row["moy_gen"] = row.get("moy_gen", "")
|
||||
row["_moy_gen_class"] = "col_moy_gen"
|
||||
# titre de la ligne:
|
||||
row["prenom"] = row["nom_short"] = (
|
||||
row.get(f"_title", "") or bottom_line.capitalize()
|
||||
)
|
||||
row["_tr_class"] = bottom_line.lower() + (
|
||||
(" " + row["_tr_class"]) if "_tr_class" in row else ""
|
||||
)
|
||||
footer_rows.append(row)
|
||||
titles_bot.update(titles)
|
||||
footer_rows.append(titles_bot)
|
||||
column_ids = [title for title in titles if not title.startswith("_")]
|
||||
column_ids.sort(
|
||||
key=lambda col_id: titles.get("_" + col_id + "_col_order", 1000)
|
||||
)
|
||||
return (rows, footer_rows, titles, column_ids)
|
||||
|
||||
def _recap_bottom_infos(self, ues, modimpl_ids: set, fmt_note) -> dict:
|
||||
"""Les informations à mettre en bas de la table: min, max, moy, ECTS"""
|
||||
row_min, row_max, row_moy, row_coef, row_ects, row_apo = (
|
||||
{"_tr_class": "bottom_info", "_title": "Min."},
|
||||
{"_tr_class": "bottom_info"},
|
||||
{"_tr_class": "bottom_info"},
|
||||
{"_tr_class": "bottom_info"},
|
||||
{"_tr_class": "bottom_info"},
|
||||
{"_tr_class": "bottom_info", "_title": "Code Apogée"},
|
||||
)
|
||||
# --- ECTS
|
||||
for ue in ues:
|
||||
colid = f"moy_ue_{ue.id}"
|
||||
row_ects[colid] = ue.ects
|
||||
row_ects[f"_{colid}_class"] = "col_ue"
|
||||
# style cases vides pour borders verticales
|
||||
row_coef[colid] = ""
|
||||
row_coef[f"_{colid}_class"] = "col_ue"
|
||||
# row_apo[colid] = ue.code_apogee or ""
|
||||
row_ects["moy_gen"] = sum([ue.ects or 0 for ue in ues if ue.type != UE_SPORT])
|
||||
row_ects["_moy_gen_class"] = "col_moy_gen"
|
||||
|
||||
# --- MIN, MAX, MOY, APO
|
||||
|
||||
row_min["moy_gen"] = fmt_note(self.etud_moy_gen.min())
|
||||
row_max["moy_gen"] = fmt_note(self.etud_moy_gen.max())
|
||||
row_moy["moy_gen"] = fmt_note(self.etud_moy_gen.mean())
|
||||
for ue in ues:
|
||||
colid = f"moy_ue_{ue.id}"
|
||||
row_min[colid] = fmt_note(self.etud_moy_ue[ue.id].min())
|
||||
row_max[colid] = fmt_note(self.etud_moy_ue[ue.id].max())
|
||||
row_moy[colid] = fmt_note(self.etud_moy_ue[ue.id].mean())
|
||||
row_min[f"_{colid}_class"] = "col_ue"
|
||||
row_max[f"_{colid}_class"] = "col_ue"
|
||||
row_moy[f"_{colid}_class"] = "col_ue"
|
||||
row_apo[colid] = ue.code_apogee or ""
|
||||
|
||||
for modimpl in self.formsemestre.modimpls_sorted:
|
||||
if modimpl.id in modimpl_ids:
|
||||
colid = f"moy_{modimpl.module.type_abbrv()}_{modimpl.id}_{ue.id}"
|
||||
if self.is_apc:
|
||||
coef = self.modimpl_coefs_df[modimpl.id][ue.id]
|
||||
else:
|
||||
coef = modimpl.module.coefficient or 0
|
||||
row_coef[colid] = fmt_note(coef)
|
||||
notes = self.modimpl_notes(modimpl.id, ue.id)
|
||||
row_min[colid] = fmt_note(np.nanmin(notes))
|
||||
row_max[colid] = fmt_note(np.nanmax(notes))
|
||||
moy = np.nanmean(notes)
|
||||
row_moy[colid] = fmt_note(moy)
|
||||
if np.isnan(moy):
|
||||
# aucune note dans ce module
|
||||
row_moy[f"_{colid}_class"] = "col_empty"
|
||||
row_apo[colid] = modimpl.module.code_apogee or ""
|
||||
|
||||
return { # { key : row } avec key = min, max, moy, coef
|
||||
"min": row_min,
|
||||
"max": row_max,
|
||||
"moy": row_moy,
|
||||
"coef": row_coef,
|
||||
"ects": row_ects,
|
||||
"apo": row_apo,
|
||||
}
|
||||
|
||||
def _recap_etud_groups_infos(self, etudid: int, row: dict, titles: dict):
|
||||
"""Table recap: ajoute à row les colonnes sur les groupes pour cet etud"""
|
||||
# dec = self.get_etud_decision_sem(etudid)
|
||||
# if dec:
|
||||
# codes_nb[dec["code"]] += 1
|
||||
row_class = ""
|
||||
etud_etat = self.get_etud_etat(etudid)
|
||||
if etud_etat == DEM:
|
||||
gr_name = "Dém."
|
||||
row_class = "dem"
|
||||
elif etud_etat == DEF:
|
||||
gr_name = "Déf."
|
||||
row_class = "def"
|
||||
else:
|
||||
# XXX probablement à revoir pour utiliser données cachées,
|
||||
# via get_etud_groups_in_partition ou autre
|
||||
group = sco_groups.get_etud_main_group(etudid, self.formsemestre.id)
|
||||
gr_name = group["group_name"] or ""
|
||||
row["group"] = gr_name
|
||||
row["_group_class"] = "group"
|
||||
if row_class:
|
||||
row["_tr_class"] = " ".join([row.get("_tr_class", ""), row_class])
|
||||
titles["group"] = "Gr"
|
||||
|
||||
def _recap_add_admissions(self, rows: list[dict], titles: dict):
|
||||
"""Ajoute les colonnes "admission"
|
||||
rows est une liste de dict avec une clé "etudid"
|
||||
Les colonnes ont la classe css "admission"
|
||||
"""
|
||||
fields = {
|
||||
"bac": "Bac",
|
||||
"specialite": "Spécialité",
|
||||
"type_admission": "Type Adm.",
|
||||
"classement": "Rg. Adm.",
|
||||
}
|
||||
first = True
|
||||
for i, cid in enumerate(fields):
|
||||
titles[f"_{cid}_col_order"] = 10000 + i # tout à droite
|
||||
if first:
|
||||
titles[f"_{cid}_class"] = "admission admission_first"
|
||||
first = False
|
||||
else:
|
||||
titles[f"_{cid}_class"] = "admission"
|
||||
titles.update(fields)
|
||||
for row in rows:
|
||||
etud = Identite.query.get(row["etudid"])
|
||||
admission = etud.admission.first()
|
||||
first = True
|
||||
for cid in fields:
|
||||
row[cid] = getattr(admission, cid) or ""
|
||||
if first:
|
||||
row[f"_{cid}_class"] = "admission admission_first"
|
||||
first = False
|
||||
else:
|
||||
row[f"_{cid}_class"] = "admission"
|
||||
|
||||
def _recap_add_partitions(self, rows: list[dict], titles: dict):
|
||||
"""Ajoute les colonnes indiquant les groupes
|
||||
rows est une liste de dict avec une clé "etudid"
|
||||
Les colonnes ont la classe css "partition"
|
||||
"""
|
||||
partitions, partitions_etud_groups = sco_groups.get_formsemestre_groups(
|
||||
self.formsemestre.id
|
||||
)
|
||||
first_partition = True
|
||||
for partition in partitions:
|
||||
cid = f"part_{partition['partition_id']}"
|
||||
titles[cid] = partition["partition_name"]
|
||||
if first_partition:
|
||||
klass = "partition"
|
||||
else:
|
||||
klass = "partition partition_aux"
|
||||
titles[f"_{cid}_class"] = klass
|
||||
titles[f"_{cid}_col_order"] = 10
|
||||
partition_etud_groups = partitions_etud_groups[partition["partition_id"]]
|
||||
for row in rows:
|
||||
# dans NotesTableCompat, à revoir
|
||||
etud_etat = self.get_etud_etat(row["etudid"])
|
||||
if etud_etat == "D":
|
||||
gr_name = "Dém."
|
||||
row["_tr_class"] = "dem"
|
||||
elif etud_etat == DEF:
|
||||
gr_name = "Déf."
|
||||
row["_tr_class"] = "def"
|
||||
else:
|
||||
group = partition_etud_groups.get(row["etudid"])
|
||||
gr_name = group["group_name"] if group else ""
|
||||
if gr_name:
|
||||
row[f"{cid}"] = gr_name
|
||||
row[f"_{cid}_class"] = klass
|
||||
first_partition = False
|
||||
|
||||
def _recap_add_evaluations(
|
||||
self, rows: list[dict], titles: dict, bottom_infos: dict
|
||||
):
|
||||
"""Ajoute les colonnes avec les notes aux évaluations
|
||||
rows est une liste de dict avec une clé "etudid"
|
||||
Les colonnes ont la classe css "evaluation"
|
||||
"""
|
||||
# nouvelle ligne pour description évaluations:
|
||||
bottom_infos["descr_evaluation"] = {
|
||||
"_tr_class": "bottom_info",
|
||||
"_title": "Description évaluation",
|
||||
}
|
||||
first = True
|
||||
for modimpl in self.formsemestre.modimpls_sorted:
|
||||
evals = self.modimpls_results[modimpl.id].get_evaluations_completes(modimpl)
|
||||
eval_index = len(evals) - 1
|
||||
inscrits = {i.etudid for i in modimpl.inscriptions}
|
||||
klass = "evaluation first" if first else "evaluation"
|
||||
first = False
|
||||
for i, e in enumerate(evals):
|
||||
cid = f"eval_{e.id}"
|
||||
titles[
|
||||
cid
|
||||
] = f'{modimpl.module.code} {eval_index} {e.jour.isoformat() if e.jour else ""}'
|
||||
titles[f"_{cid}_class"] = klass
|
||||
titles[f"_{cid}_col_order"] = 9000 + i # à droite
|
||||
eval_index -= 1
|
||||
notes_db = sco_evaluation_db.do_evaluation_get_all_notes(
|
||||
e.evaluation_id
|
||||
)
|
||||
for row in rows:
|
||||
etudid = row["etudid"]
|
||||
if etudid in inscrits:
|
||||
if etudid in notes_db:
|
||||
val = notes_db[etudid]["value"]
|
||||
else:
|
||||
# Note manquante mais prise en compte immédiate: affiche ATT
|
||||
val = scu.NOTES_ATTENTE
|
||||
row[cid] = scu.fmt_note(val)
|
||||
row[f"_{cid}_class"] = klass
|
||||
bottom_infos["coef"][cid] = e.coefficient
|
||||
bottom_infos["min"][cid] = "0"
|
||||
bottom_infos["max"][cid] = scu.fmt_note(e.note_max)
|
||||
bottom_infos["descr_evaluation"][cid] = e.description or ""
|
|
@ -0,0 +1,462 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Classe résultats pour compatibilité avec le code ScoDoc 7
|
||||
"""
|
||||
from functools import cached_property
|
||||
|
||||
from flask import flash, g, Markup, url_for
|
||||
|
||||
from app import log
|
||||
from app.comp import moy_sem
|
||||
from app.comp.aux_stats import StatsMoyenne
|
||||
from app.comp.res_common import ResultatsSemestre
|
||||
from app.comp import res_sem
|
||||
from app.models import FormSemestre
|
||||
from app.models import Identite
|
||||
from app.models import ModuleImpl
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT, DEF
|
||||
from app.scodoc import sco_utils as scu
|
||||
|
||||
# Pour raccorder le code des anciens codes qui attendent une NoteTable
|
||||
class NotesTableCompat(ResultatsSemestre):
|
||||
"""Implementation partielle de NotesTable
|
||||
|
||||
Les méthodes définies dans cette classe sont là
|
||||
pour conserver la compatibilité abvec les codes anciens et
|
||||
il n'est pas recommandé de les utiliser dans de nouveaux
|
||||
développements (API malcommode et peu efficace).
|
||||
"""
|
||||
|
||||
_cached_attrs = ResultatsSemestre._cached_attrs + (
|
||||
"malus",
|
||||
"etud_moy_gen_ranks",
|
||||
"etud_moy_gen_ranks_int",
|
||||
"ue_rangs",
|
||||
)
|
||||
|
||||
def __init__(self, formsemestre: FormSemestre):
|
||||
super().__init__(formsemestre)
|
||||
|
||||
nb_etuds = len(self.etuds)
|
||||
self.ue_rangs = {u.id: (None, nb_etuds) for u in self.ues}
|
||||
self.mod_rangs = None # sera surchargé en Classic, mais pas en APC
|
||||
"""{ modimpl_id : (rangs, effectif) }"""
|
||||
self.moy_min = "NA"
|
||||
self.moy_max = "NA"
|
||||
self.moy_moy = "NA"
|
||||
self.expr_diagnostics = ""
|
||||
self.parcours = self.formsemestre.formation.get_parcours()
|
||||
|
||||
def get_inscrits(self, include_demdef=True, order_by=False) -> list[Identite]:
|
||||
"""Liste des étudiants inscrits
|
||||
order_by = False|'nom'|'moy' tri sur nom ou sur moyenne générale (indicative)
|
||||
|
||||
Note: pour récupérer les etudids des inscrits, non triés, il est plus efficace
|
||||
d'utiliser `[ ins.etudid for ins in nt.formsemestre.inscriptions ]`
|
||||
"""
|
||||
etuds = self.formsemestre.get_inscrits(
|
||||
include_demdef=include_demdef, order=(order_by == "nom")
|
||||
)
|
||||
if order_by == "moy":
|
||||
etuds.sort(
|
||||
key=lambda e: (
|
||||
self.etud_moy_gen_ranks_int.get(e.id, 100000),
|
||||
e.sort_key,
|
||||
)
|
||||
)
|
||||
return etuds
|
||||
|
||||
def get_etudids(self) -> list[int]:
|
||||
"""(deprecated)
|
||||
Liste des etudids inscrits, incluant les démissionnaires.
|
||||
triée par ordre alphabetique de NOM
|
||||
(à éviter: renvoie les etudids, mais est moins efficace que get_inscrits)
|
||||
"""
|
||||
# Note: pour avoir les inscrits non triés,
|
||||
# utiliser [ ins.etudid for ins in self.formsemestre.inscriptions ]
|
||||
return [x["etudid"] for x in self.inscrlist]
|
||||
|
||||
@cached_property
|
||||
def sem(self) -> dict:
|
||||
"""le formsemestre, comme un gros et gras dict (nt.sem)"""
|
||||
return self.formsemestre.get_infos_dict()
|
||||
|
||||
@cached_property
|
||||
def inscrlist(self) -> list[dict]: # utilisé par PE
|
||||
"""Liste des inscrits au semestre (avec DEM et DEF),
|
||||
sous forme de dict etud,
|
||||
classée dans l'ordre alphabétique de noms.
|
||||
"""
|
||||
etuds = self.formsemestre.get_inscrits(include_demdef=True, order=True)
|
||||
return [e.to_dict_scodoc7() for e in etuds]
|
||||
|
||||
@cached_property
|
||||
def stats_moy_gen(self):
|
||||
"""Stats (moy/min/max) sur la moyenne générale"""
|
||||
return StatsMoyenne(self.etud_moy_gen)
|
||||
|
||||
def get_ues_stat_dict(
|
||||
self, filter_sport=False, check_apc_ects=True
|
||||
) -> list[dict]: # was get_ues()
|
||||
"""Liste des UEs, ordonnée par numero.
|
||||
Si filter_sport, retire les UE de type SPORT.
|
||||
Résultat: liste de dicts { champs UE U stats moyenne UE }
|
||||
"""
|
||||
ues = self.formsemestre.query_ues(with_sport=not filter_sport)
|
||||
ues_dict = []
|
||||
for ue in ues:
|
||||
d = ue.to_dict()
|
||||
if ue.type != UE_SPORT:
|
||||
moys = self.etud_moy_ue[ue.id]
|
||||
else:
|
||||
moys = None
|
||||
d.update(StatsMoyenne(moys).to_dict())
|
||||
ues_dict.append(d)
|
||||
if check_apc_ects and self.is_apc and not hasattr(g, "checked_apc_ects"):
|
||||
g.checked_apc_ects = True
|
||||
if None in [ue.ects for ue in ues if ue.type != UE_SPORT]:
|
||||
formation = self.formsemestre.formation
|
||||
ue_sans_ects = [
|
||||
ue for ue in ues if ue.type != UE_SPORT and ue.ects is None
|
||||
]
|
||||
flash(
|
||||
Markup(
|
||||
f"""Calcul moyenne générale impossible: ECTS des UE manquants !<br>
|
||||
(dans {' ,'.join([ue.acronyme for ue in ue_sans_ects])}
|
||||
de la formation: <a href="{url_for("notes.ue_table",
|
||||
scodoc_dept=g.scodoc_dept, formation_id=formation.id)
|
||||
}">{formation.get_titre_version()}</a>)
|
||||
)
|
||||
"""
|
||||
),
|
||||
category="danger",
|
||||
)
|
||||
return ues_dict
|
||||
|
||||
def get_modimpls_dict(self, ue_id=None) -> list[dict]:
|
||||
"""Liste des modules pour une UE (ou toutes si ue_id==None),
|
||||
triés par numéros (selon le type de formation)
|
||||
"""
|
||||
modimpls_dict = []
|
||||
for modimpl in self.formsemestre.modimpls_sorted:
|
||||
if (ue_id is None) or (modimpl.module.ue.id == ue_id):
|
||||
d = modimpl.to_dict()
|
||||
# compat ScoDoc < 9.2: ajoute matières
|
||||
d["mat"] = modimpl.module.matiere.to_dict()
|
||||
modimpls_dict.append(d)
|
||||
return modimpls_dict
|
||||
|
||||
def compute_rangs(self):
|
||||
"""Calcule les classements
|
||||
Moyenne générale: etud_moy_gen_ranks
|
||||
Par UE (sauf ue bonus)
|
||||
"""
|
||||
(
|
||||
self.etud_moy_gen_ranks,
|
||||
self.etud_moy_gen_ranks_int,
|
||||
) = moy_sem.comp_ranks_series(self.etud_moy_gen)
|
||||
for ue in self.formsemestre.query_ues():
|
||||
moy_ue = self.etud_moy_ue[ue.id]
|
||||
self.ue_rangs[ue.id] = (
|
||||
moy_sem.comp_ranks_series(moy_ue)[0], # juste en chaine
|
||||
int(moy_ue.count()),
|
||||
)
|
||||
# .count() -> nb of non NaN values
|
||||
|
||||
def get_etud_ue_rang(self, ue_id, etudid) -> tuple[str, int]:
|
||||
"""Le rang de l'étudiant dans cette ue
|
||||
Result: rang:str, effectif:str
|
||||
"""
|
||||
rangs, effectif = self.ue_rangs[ue_id]
|
||||
if rangs is not None:
|
||||
rang = rangs[etudid]
|
||||
else:
|
||||
return "", ""
|
||||
return rang, effectif
|
||||
|
||||
def etud_check_conditions_ues(self, etudid):
|
||||
"""Vrai si les conditions sur les UE sont remplies.
|
||||
Ne considère que les UE ayant des notes (moyenne calculée).
|
||||
(les UE sans notes ne sont pas comptées comme sous la barre)
|
||||
Prend en compte les éventuelles UE capitalisées.
|
||||
|
||||
Pour les parcours habituels, cela revient à vérifier que
|
||||
les moyennes d'UE sont toutes > à leur barre (sauf celles sans notes)
|
||||
|
||||
Pour les parcours non standards (LP2014), cela peut être plus compliqué.
|
||||
|
||||
Return: True|False, message explicatif
|
||||
"""
|
||||
ue_status_list = []
|
||||
for ue in self.formsemestre.query_ues():
|
||||
ue_status = self.get_etud_ue_status(etudid, ue.id)
|
||||
if ue_status:
|
||||
ue_status_list.append(ue_status)
|
||||
return self.parcours.check_barre_ues(ue_status_list)
|
||||
|
||||
def all_etuds_have_sem_decisions(self):
|
||||
"""True si tous les étudiants du semestre ont une décision de jury.
|
||||
Ne regarde pas les décisions d'UE.
|
||||
"""
|
||||
for ins in self.formsemestre.inscriptions:
|
||||
if ins.etat != scu.INSCRIT:
|
||||
continue # skip démissionnaires
|
||||
if self.get_etud_decision_sem(ins.etudid) is None:
|
||||
return False
|
||||
return True
|
||||
|
||||
def etud_has_decision(self, etudid):
|
||||
"""True s'il y a une décision de jury pour cet étudiant"""
|
||||
return self.get_etud_decision_ues(etudid) or self.get_etud_decision_sem(etudid)
|
||||
|
||||
def get_etud_decision_ues(self, etudid: int) -> dict:
|
||||
"""Decisions du jury pour les UE de cet etudiant, ou None s'il n'y en pas eu.
|
||||
Ne tient pas compte des UE capitalisées.
|
||||
{ ue_id : { 'code' : ADM|CMP|AJ, 'event_date' : }
|
||||
Ne renvoie aucune decision d'UE pour les défaillants
|
||||
"""
|
||||
if self.get_etud_etat(etudid) == DEF:
|
||||
return {}
|
||||
else:
|
||||
if not self.validations:
|
||||
self.validations = res_sem.load_formsemestre_validations(
|
||||
self.formsemestre
|
||||
)
|
||||
return self.validations.decisions_jury_ues.get(etudid, None)
|
||||
|
||||
def get_etud_decision_sem(self, etudid: int) -> dict:
|
||||
"""Decision du jury prise pour cet etudiant, ou None s'il n'y en pas eu.
|
||||
{ 'code' : None|ATT|..., 'assidu' : 0|1, 'event_date' : , compense_formsemestre_id }
|
||||
Si état défaillant, force le code a DEF
|
||||
"""
|
||||
if self.get_etud_etat(etudid) == DEF:
|
||||
return {
|
||||
"code": DEF,
|
||||
"assidu": False,
|
||||
"event_date": "",
|
||||
"compense_formsemestre_id": None,
|
||||
}
|
||||
else:
|
||||
if not self.validations:
|
||||
self.validations = res_sem.load_formsemestre_validations(
|
||||
self.formsemestre
|
||||
)
|
||||
return self.validations.decisions_jury.get(etudid, None)
|
||||
|
||||
def get_etud_mat_moy(self, matiere_id: int, etudid: int) -> str:
|
||||
"""moyenne d'un étudiant dans une matière (ou NA si pas de notes)"""
|
||||
if not self.moyennes_matieres:
|
||||
return "nd"
|
||||
return (
|
||||
self.moyennes_matieres[matiere_id].get(etudid, "-")
|
||||
if matiere_id in self.moyennes_matieres
|
||||
else "-"
|
||||
)
|
||||
|
||||
def get_etud_mod_moy(self, moduleimpl_id: int, etudid: int) -> float:
|
||||
"""La moyenne de l'étudiant dans le moduleimpl
|
||||
En APC, il s'agira d'une moyenne indicative sans valeur.
|
||||
Result: valeur float (peut être naN) ou chaîne "NI" (non inscrit ou DEM)
|
||||
"""
|
||||
raise NotImplementedError() # virtual method
|
||||
|
||||
def get_etud_moy_gen(self, etudid): # -> float | str
|
||||
"""Moyenne générale de cet etudiant dans ce semestre.
|
||||
Prend en compte les UE capitalisées.
|
||||
Si apc, moyenne indicative.
|
||||
Si pas de notes: 'NA'
|
||||
"""
|
||||
return self.etud_moy_gen[etudid]
|
||||
|
||||
def get_etud_ects_pot(self, etudid: int) -> dict:
|
||||
"""
|
||||
Un dict avec les champs
|
||||
ects_pot : (float) nb de crédits ECTS qui seraient validés
|
||||
(sous réserve de validation par le jury)
|
||||
ects_pot_fond: (float) nb d'ECTS issus d'UE fondamentales (non électives)
|
||||
|
||||
Ce sont les ECTS des UE au dessus de la barre (10/20 en principe), avant le jury (donc non
|
||||
encore enregistrées).
|
||||
"""
|
||||
# was nt.get_etud_moy_infos
|
||||
# XXX pour compat nt, à remplacer ultérieurement
|
||||
ues = self.get_etud_ue_validables(etudid)
|
||||
ects_pot = 0.0
|
||||
for ue in ues:
|
||||
if (
|
||||
ue.id in self.etud_moy_ue
|
||||
and ue.ects is not None
|
||||
and self.etud_moy_ue[ue.id][etudid] > self.parcours.NOTES_BARRE_VALID_UE
|
||||
):
|
||||
ects_pot += ue.ects
|
||||
return {
|
||||
"ects_pot": ects_pot,
|
||||
"ects_pot_fond": 0.0, # not implemented (anciennemment pour école ingé)
|
||||
}
|
||||
|
||||
def get_etud_rang(self, etudid: int) -> str:
|
||||
"""Le rang (classement) de l'étudiant dans le semestre.
|
||||
Result: "13" ou "12 ex"
|
||||
"""
|
||||
return self.etud_moy_gen_ranks.get(etudid, 99999)
|
||||
|
||||
def get_etud_rang_group(self, etudid: int, group_id: int):
|
||||
"Le rang de l'étudiant dans ce groupe (NON IMPLEMENTE)"
|
||||
return (None, 0) # XXX unimplemented TODO
|
||||
|
||||
def get_evals_in_mod(self, moduleimpl_id: int) -> list[dict]:
|
||||
"""Liste d'informations (compat NotesTable) sur évaluations completes
|
||||
de ce module.
|
||||
Évaluation "complete" ssi toutes notes saisies ou en attente.
|
||||
"""
|
||||
modimpl = ModuleImpl.query.get(moduleimpl_id)
|
||||
modimpl_results = self.modimpls_results.get(moduleimpl_id)
|
||||
if not modimpl_results:
|
||||
return [] # safeguard
|
||||
evals_results = []
|
||||
for e in modimpl.evaluations:
|
||||
if modimpl_results.evaluations_completes_dict.get(e.id, False):
|
||||
d = e.to_dict()
|
||||
d["heure_debut"] = e.heure_debut # datetime.time
|
||||
d["heure_fin"] = e.heure_fin
|
||||
d["jour"] = e.jour # datetime
|
||||
d["notes"] = {
|
||||
etud.id: {
|
||||
"etudid": etud.id,
|
||||
"value": modimpl_results.evals_notes[e.id][etud.id],
|
||||
}
|
||||
for etud in self.etuds
|
||||
}
|
||||
d["etat"] = {
|
||||
"evalattente": modimpl_results.evaluations_etat[e.id].nb_attente,
|
||||
}
|
||||
evals_results.append(d)
|
||||
elif e.id not in modimpl_results.evaluations_completes_dict:
|
||||
# ne devrait pas arriver ? XXX
|
||||
log(
|
||||
f"Warning: 220213 get_evals_in_mod {e.id} not in mod {moduleimpl_id} ?"
|
||||
)
|
||||
return evals_results
|
||||
|
||||
def get_evaluations_etats(self):
|
||||
"""[ {...evaluation et son etat...} ]"""
|
||||
# TODO: à moderniser
|
||||
from app.scodoc import sco_evaluations
|
||||
|
||||
if not hasattr(self, "_evaluations_etats"):
|
||||
self._evaluations_etats = sco_evaluations.do_evaluation_list_in_sem(
|
||||
self.formsemestre.id
|
||||
)
|
||||
|
||||
return self._evaluations_etats
|
||||
|
||||
def get_mod_evaluation_etat_list(self, moduleimpl_id) -> list[dict]:
|
||||
"""Liste des états des évaluations de ce module"""
|
||||
# XXX TODO à moderniser: lent, recharge des données que l'on a déjà...
|
||||
return [
|
||||
e
|
||||
for e in self.get_evaluations_etats()
|
||||
if e["moduleimpl_id"] == moduleimpl_id
|
||||
]
|
||||
|
||||
def get_moduleimpls_attente(self):
|
||||
"""Liste des modimpls du semestre ayant des notes en attente"""
|
||||
return [
|
||||
modimpl
|
||||
for modimpl in self.formsemestre.modimpls_sorted
|
||||
if self.modimpls_results[modimpl.id].en_attente
|
||||
]
|
||||
|
||||
def get_mod_stats(self, moduleimpl_id: int) -> dict:
|
||||
"""Stats sur les notes obtenues dans un modimpl
|
||||
Vide en APC
|
||||
"""
|
||||
return {
|
||||
"moy": "-",
|
||||
"max": "-",
|
||||
"min": "-",
|
||||
"nb_notes": "-",
|
||||
"nb_missing": "-",
|
||||
"nb_valid_evals": "-",
|
||||
}
|
||||
|
||||
def get_nom_short(self, etudid):
|
||||
"formatte nom d'un etud (pour table recap)"
|
||||
etud = self.identdict[etudid]
|
||||
return (
|
||||
(etud["nom_usuel"] or etud["nom"]).upper()
|
||||
+ " "
|
||||
+ etud["prenom"].capitalize()[:2]
|
||||
+ "."
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def T(self):
|
||||
return self.get_table_moyennes_triees()
|
||||
|
||||
def get_table_moyennes_triees(self) -> list:
|
||||
"""Result: liste de tuples
|
||||
moy_gen, moy_ue_0, ..., moy_ue_n, moy_mod1, ..., moy_mod_n, etudid
|
||||
"""
|
||||
table_moyennes = []
|
||||
etuds_inscriptions = self.formsemestre.etuds_inscriptions
|
||||
ues = self.formsemestre.query_ues(with_sport=True) # avec bonus
|
||||
for etudid in etuds_inscriptions:
|
||||
moy_gen = self.etud_moy_gen.get(etudid, False)
|
||||
if moy_gen is False:
|
||||
# pas de moyenne: démissionnaire ou def
|
||||
t = (
|
||||
["-"]
|
||||
+ ["0.00"] * len(self.ues)
|
||||
+ ["NI"] * len(self.formsemestre.modimpls_sorted)
|
||||
)
|
||||
else:
|
||||
moy_ues = []
|
||||
ue_is_cap = {}
|
||||
for ue in ues:
|
||||
ue_status = self.get_etud_ue_status(etudid, ue.id)
|
||||
if ue_status:
|
||||
moy_ues.append(ue_status["moy"])
|
||||
ue_is_cap[ue.id] = ue_status["is_capitalized"]
|
||||
else:
|
||||
moy_ues.append("?")
|
||||
t = [moy_gen] + list(moy_ues)
|
||||
# Moyennes modules:
|
||||
for modimpl in self.formsemestre.modimpls_sorted:
|
||||
if ue_is_cap.get(modimpl.module.ue.id, False):
|
||||
val = "-c-"
|
||||
else:
|
||||
val = self.get_etud_mod_moy(modimpl.id, etudid)
|
||||
t.append(val)
|
||||
t.append(etudid)
|
||||
table_moyennes.append(t)
|
||||
# tri par moyennes décroissantes,
|
||||
# en laissant les démissionnaires à la fin, par ordre alphabetique
|
||||
etuds = [ins.etud for ins in etuds_inscriptions.values()]
|
||||
etuds.sort(key=lambda e: e.sort_key)
|
||||
self._rang_alpha = {e.id: i for i, e in enumerate(etuds)}
|
||||
table_moyennes.sort(key=self._row_key)
|
||||
return table_moyennes
|
||||
|
||||
def _row_key(self, x):
|
||||
"""clé de tri par moyennes décroissantes,
|
||||
en laissant les demissionnaires à la fin, par ordre alphabetique.
|
||||
(moy_gen, rang_alpha)
|
||||
"""
|
||||
try:
|
||||
moy = -float(x[0])
|
||||
except (ValueError, TypeError):
|
||||
moy = 1000.0
|
||||
return (moy, self._rang_alpha[x[-1]])
|
||||
|
||||
@cached_property
|
||||
def identdict(self) -> dict:
|
||||
"""{ etudid : etud_dict } pour tous les inscrits au semestre"""
|
||||
return {
|
||||
ins.etud.id: ins.etud.to_dict_scodoc7()
|
||||
for ins in self.formsemestre.inscriptions
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
"""Chargement des résultats de semestres (tous types)
|
||||
"""
|
||||
from flask import g
|
||||
|
||||
from app import db
|
||||
from app.comp.jury import ValidationsSemestre
|
||||
from app.comp.res_common import ResultatsSemestre
|
||||
from app.comp.res_classic import ResultatsSemestreClassic
|
||||
from app.comp.res_but import ResultatsSemestreBUT
|
||||
from app.models.formsemestre import FormSemestre
|
||||
from app.scodoc import sco_cache
|
||||
|
||||
|
||||
def load_formsemestre_results(formsemestre: FormSemestre) -> ResultatsSemestre:
|
||||
"""Returns ResultatsSemestre for this formsemestre.
|
||||
Suivant le type de formation, retour une instance de
|
||||
ResultatsSemestreClassic ou de ResultatsSemestreBUT.
|
||||
|
||||
Search in local cache (g.formsemestre_result_cache)
|
||||
If not in cache, build it and cache it.
|
||||
"""
|
||||
is_apc = formsemestre.formation.is_apc()
|
||||
if is_apc and formsemestre.semestre_id == -1:
|
||||
formsemestre.semestre_id = 1
|
||||
db.session.add(formsemestre)
|
||||
db.session.commit()
|
||||
sco_cache.invalidate_formsemestre(formsemestre.id)
|
||||
|
||||
# --- Try local cache (within the same request context)
|
||||
if not hasattr(g, "formsemestre_results_cache"):
|
||||
g.formsemestre_results_cache = {}
|
||||
else:
|
||||
if formsemestre.id in g.formsemestre_results_cache:
|
||||
return g.formsemestre_results_cache[formsemestre.id]
|
||||
|
||||
klass = ResultatsSemestreBUT if is_apc else ResultatsSemestreClassic
|
||||
g.formsemestre_results_cache[formsemestre.id] = klass(formsemestre)
|
||||
return g.formsemestre_results_cache[formsemestre.id]
|
||||
|
||||
|
||||
def load_formsemestre_validations(formsemestre: FormSemestre) -> ValidationsSemestre:
|
||||
"""Charge les résultats de jury de ce semestre.
|
||||
Search in local cache (g.formsemestre_result_cache)
|
||||
If not in cache, build it and cache it.
|
||||
"""
|
||||
if not hasattr(g, "formsemestre_validation_cache"):
|
||||
g.formsemestre_validations_cache = {} # pylint: disable=C0237
|
||||
else:
|
||||
if formsemestre.id in g.formsemestre_validations_cache:
|
||||
return g.formsemestre_validations_cache[formsemestre.id]
|
||||
|
||||
g.formsemestre_validations_cache[formsemestre.id] = ValidationsSemestre(
|
||||
formsemestre
|
||||
)
|
||||
return g.formsemestre_validations_cache[formsemestre.id]
|
|
@ -1,14 +1,11 @@
|
|||
# -*- coding: UTF-8 -*
|
||||
"""Decorators for permissions, roles and ScoDoc7 Zope compatibility
|
||||
"""
|
||||
import functools
|
||||
from functools import wraps
|
||||
import inspect
|
||||
import types
|
||||
import logging
|
||||
|
||||
|
||||
import werkzeug
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import flask
|
||||
from flask import g, current_app, request
|
||||
from flask import abort, url_for, redirect
|
||||
|
@ -193,7 +190,7 @@ def scodoc7func(func):
|
|||
# necessary for db ids and boolean values
|
||||
try:
|
||||
v = int(v)
|
||||
except ValueError:
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
pos_arg_values.append(v)
|
||||
# current_app.logger.info("pos_arg_values=%s" % pos_arg_values)
|
||||
|
|
66
app/email.py
66
app/email.py
|
@ -1,30 +1,86 @@
|
|||
# -*- coding: UTF-8 -*
|
||||
##############################################################################
|
||||
# ScoDoc
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
# See LICENSE
|
||||
##############################################################################
|
||||
|
||||
from threading import Thread
|
||||
from flask import current_app
|
||||
|
||||
from flask import current_app, g
|
||||
from flask_mail import Message
|
||||
|
||||
from app import mail
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
|
||||
def send_async_email(app, msg):
|
||||
"Send an email, async"
|
||||
with app.app_context():
|
||||
mail.send(msg)
|
||||
|
||||
|
||||
def send_email(
|
||||
subject: str, sender: str, recipients: list, text_body: str, html_body=""
|
||||
subject: str,
|
||||
sender: str,
|
||||
recipients: list,
|
||||
text_body: str,
|
||||
html_body="",
|
||||
bcc=(),
|
||||
attachments=(),
|
||||
):
|
||||
"""
|
||||
Send an email
|
||||
Send an email. _All_ ScoDoc mails SHOULD be sent using this function.
|
||||
|
||||
If html_body is specified, build a multipart message with HTML content,
|
||||
else send a plain text email.
|
||||
|
||||
attachements: list of dict { 'filename', 'mimetype', 'data' }
|
||||
"""
|
||||
msg = Message(subject, sender=sender, recipients=recipients)
|
||||
msg = Message(subject, sender=sender, recipients=recipients, bcc=bcc)
|
||||
msg.body = text_body
|
||||
msg.html = html_body
|
||||
if attachments:
|
||||
for attachment in attachments:
|
||||
msg.attach(
|
||||
attachment["filename"], attachment["mimetype"], attachment["data"]
|
||||
)
|
||||
|
||||
send_message(msg)
|
||||
|
||||
|
||||
def send_message(msg):
|
||||
def send_message(msg: Message):
|
||||
"""Send a message.
|
||||
All ScoDoc emails MUST be sent by this function.
|
||||
|
||||
In mail debug mode, addresses are discarded and all mails are sent to the
|
||||
specified debugging address.
|
||||
"""
|
||||
if hasattr(g, "scodoc_dept"):
|
||||
# on est dans un département, on peut accéder aux préférences
|
||||
email_test_mode_address = sco_preferences.get_preference(
|
||||
"email_test_mode_address"
|
||||
)
|
||||
if email_test_mode_address:
|
||||
# Mode spécial test: remplace les adresses de destination
|
||||
orig_to = msg.recipients
|
||||
orig_cc = msg.cc
|
||||
orig_bcc = msg.bcc
|
||||
msg.recipients = [email_test_mode_address]
|
||||
msg.cc = None
|
||||
msg.bcc = None
|
||||
msg.subject = "[TEST SCODOC] " + msg.subject
|
||||
msg.body = (
|
||||
f"""--- Message ScoDoc dérouté pour tests ---
|
||||
Adresses d'origine:
|
||||
to : {orig_to}
|
||||
cc : {orig_cc}
|
||||
bcc: {orig_bcc}
|
||||
---
|
||||
\n\n"""
|
||||
+ msg.body
|
||||
)
|
||||
|
||||
Thread(
|
||||
target=send_async_email, args=(current_app._get_current_object(), msg)
|
||||
).start()
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
"""entreprises.__init__
|
||||
"""
|
||||
|
||||
from flask import Blueprint
|
||||
from app.scodoc import sco_etud
|
||||
from app.auth.models import User
|
||||
from app.models import Departement
|
||||
|
||||
bp = Blueprint("entreprises", __name__)
|
||||
|
||||
LOGS_LEN = 5
|
||||
|
||||
|
||||
@bp.app_template_filter()
|
||||
def format_prenom(s):
|
||||
return sco_etud.format_prenom(s)
|
||||
|
||||
|
||||
@bp.app_template_filter()
|
||||
def format_nom(s):
|
||||
return sco_etud.format_nom(s)
|
||||
|
||||
|
||||
@bp.app_template_filter()
|
||||
def get_nomcomplet_by_username(s):
|
||||
user = User.query.filter_by(user_name=s).first()
|
||||
return user.get_nomcomplet()
|
||||
|
||||
|
||||
@bp.app_template_filter()
|
||||
def get_nomcomplet_by_id(id):
|
||||
user = User.query.filter_by(id=id).first()
|
||||
return user.get_nomcomplet()
|
||||
|
||||
|
||||
@bp.app_template_filter()
|
||||
def get_dept_acronym(id):
|
||||
dept = Departement.query.filter_by(id=id).first()
|
||||
return dept.acronym
|
||||
|
||||
|
||||
from app.entreprises import routes
|
|
@ -0,0 +1,198 @@
|
|||
# -*- mode: python -*-
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gestion scolarite IUT
|
||||
#
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
#
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
import os
|
||||
from config import Config
|
||||
import re
|
||||
import requests
|
||||
import glob
|
||||
|
||||
from flask_login import current_user
|
||||
|
||||
from app.entreprises.models import (
|
||||
Entreprise,
|
||||
EntrepriseContact,
|
||||
EntrepriseOffre,
|
||||
EntrepriseOffreDepartement,
|
||||
EntreprisePreferences,
|
||||
)
|
||||
|
||||
from app import email
|
||||
from app.scodoc import sco_preferences
|
||||
from app.models import Departement
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
|
||||
|
||||
def get_depts():
|
||||
"""
|
||||
Retourne une liste contenant les l'id des départements des roles de l'utilisateur courant
|
||||
"""
|
||||
depts = []
|
||||
for role in current_user.user_roles:
|
||||
dept_id = get_dept_id_by_acronym(role.dept)
|
||||
if dept_id is not None:
|
||||
depts.append(dept_id)
|
||||
return depts
|
||||
|
||||
|
||||
def get_dept_id_by_acronym(acronym):
|
||||
"""
|
||||
Retourne l'id d'un departement a l'aide de son acronym
|
||||
"""
|
||||
dept = Departement.query.filter_by(acronym=acronym).first()
|
||||
if dept is not None:
|
||||
return dept.id
|
||||
return None
|
||||
|
||||
|
||||
def check_offre_depts(depts, offre_depts):
|
||||
"""
|
||||
Retourne vrai si l'utilisateur a le droit de visibilité sur l'offre
|
||||
"""
|
||||
if current_user.has_permission(Permission.RelationsEntreprisesChange, None):
|
||||
return True
|
||||
for offre_dept in offre_depts:
|
||||
if offre_dept.dept_id in depts:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def get_offre_files_and_depts(offre: EntrepriseOffre, depts: list):
|
||||
"""
|
||||
Retourne l'offre, les fichiers attachés a l'offre et les département liés
|
||||
"""
|
||||
offre_depts = EntrepriseOffreDepartement.query.filter_by(offre_id=offre.id).all()
|
||||
if not offre_depts or check_offre_depts(depts, offre_depts):
|
||||
files = []
|
||||
path = os.path.join(
|
||||
Config.SCODOC_VAR_DIR,
|
||||
"entreprises",
|
||||
f"{offre.entreprise_id}",
|
||||
f"{offre.id}",
|
||||
)
|
||||
if os.path.exists(path):
|
||||
for dir in glob.glob(
|
||||
f"{path}/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"
|
||||
):
|
||||
for _file in glob.glob(f"{dir}/*"):
|
||||
file = [os.path.basename(dir), os.path.basename(_file)]
|
||||
files.append(file)
|
||||
return [offre, files, offre_depts]
|
||||
return None
|
||||
|
||||
|
||||
def send_email_notifications_entreprise(
|
||||
subject, entreprise: Entreprise, contact: EntrepriseContact
|
||||
):
|
||||
txt = [
|
||||
"Une entreprise est en attente de validation",
|
||||
"Entreprise:",
|
||||
f"\tnom: {entreprise.nom}",
|
||||
f"\tsiret: {entreprise.siret}",
|
||||
f"\tadresse: {entreprise.adresse}",
|
||||
f"\tcode postal: {entreprise.codepostal}",
|
||||
f"\tville: {entreprise.ville}",
|
||||
f"\tpays: {entreprise.pays}",
|
||||
"",
|
||||
"Contact:",
|
||||
f"nom: {contact.nom}",
|
||||
f"prenom: {contact.prenom}",
|
||||
f"telephone: {contact.telephone}",
|
||||
f"mail: {contact.mail}",
|
||||
f"poste: {contact.poste}",
|
||||
f"service: {contact.service}",
|
||||
]
|
||||
txt = "\n".join(txt)
|
||||
email.send_email(
|
||||
subject,
|
||||
sco_preferences.get_preference("email_from_addr"),
|
||||
[EntreprisePreferences.get_email_notifications],
|
||||
txt,
|
||||
)
|
||||
return txt
|
||||
|
||||
|
||||
def verif_contact_data(contact_data):
|
||||
"""
|
||||
Verifie les données d'une ligne Excel (contact)
|
||||
contact_data[0]: nom
|
||||
contact_data[1]: prenom
|
||||
contact_data[2]: telephone
|
||||
contact_data[3]: mail
|
||||
contact_data[4]: poste
|
||||
contact_data[5]: service
|
||||
contact_data[6]: entreprise_id
|
||||
"""
|
||||
# champs obligatoires
|
||||
if contact_data[0] == "" or contact_data[1] == "" or contact_data[6] == "":
|
||||
return False
|
||||
|
||||
# entreprise_id existant
|
||||
entreprise = Entreprise.query.filter_by(siret=contact_data[6]).first()
|
||||
if entreprise is None:
|
||||
return False
|
||||
|
||||
# contact possède le meme nom et prénom dans la meme entreprise
|
||||
contact = EntrepriseContact.query.filter_by(
|
||||
nom=contact_data[0], prenom=contact_data[1], entreprise_id=entreprise.id
|
||||
).first()
|
||||
if contact is not None:
|
||||
return False
|
||||
|
||||
if contact_data[2] == "" and contact_data[3] == "": # 1 moyen de contact
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def verif_entreprise_data(entreprise_data):
|
||||
"""
|
||||
Verifie les données d'une ligne Excel (entreprise)
|
||||
"""
|
||||
if EntreprisePreferences.get_check_siret():
|
||||
for data in entreprise_data: # champs obligatoires
|
||||
if data == "":
|
||||
return False
|
||||
else:
|
||||
for data in entreprise_data[1:]: # champs obligatoires
|
||||
if data == "":
|
||||
return False
|
||||
if EntreprisePreferences.get_check_siret():
|
||||
siret = entreprise_data[0].strip() # vérification sur le siret
|
||||
if re.match("^\d{14}$", siret) is None:
|
||||
return False
|
||||
try:
|
||||
req = requests.get(
|
||||
f"https://entreprise.data.gouv.fr/api/sirene/v1/siret/{siret}"
|
||||
)
|
||||
except requests.ConnectionError:
|
||||
print("no internet")
|
||||
if req.status_code != 200:
|
||||
return False
|
||||
entreprise = Entreprise.query.filter_by(siret=siret).first()
|
||||
if entreprise is not None:
|
||||
return False
|
||||
return True
|
|
@ -0,0 +1,379 @@
|
|||
# -*- mode: python -*-
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gestion scolarite IUT
|
||||
#
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
#
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
import re
|
||||
import requests
|
||||
|
||||
from flask_wtf import FlaskForm
|
||||
from flask_wtf.file import FileField, FileAllowed, FileRequired
|
||||
from markupsafe import Markup
|
||||
from sqlalchemy import text
|
||||
from wtforms import (
|
||||
StringField,
|
||||
SubmitField,
|
||||
TextAreaField,
|
||||
SelectField,
|
||||
HiddenField,
|
||||
SelectMultipleField,
|
||||
DateField,
|
||||
BooleanField,
|
||||
)
|
||||
from wtforms.validators import ValidationError, DataRequired, Email, Optional
|
||||
from wtforms.widgets import ListWidget, CheckboxInput
|
||||
|
||||
from app.entreprises.models import Entreprise, EntrepriseContact, EntreprisePreferences
|
||||
from app.models import Identite, Departement
|
||||
from app.auth.models import User
|
||||
|
||||
CHAMP_REQUIS = "Ce champ est requis"
|
||||
SUBMIT_MARGE = {"style": "margin-bottom: 10px;"}
|
||||
|
||||
|
||||
def _build_string_field(label, required=True, render_kw=None):
|
||||
if required:
|
||||
return StringField(
|
||||
label,
|
||||
validators=[DataRequired(message=CHAMP_REQUIS)],
|
||||
render_kw=render_kw,
|
||||
)
|
||||
else:
|
||||
return StringField(label, validators=[Optional()], render_kw=render_kw)
|
||||
|
||||
|
||||
class EntrepriseCreationForm(FlaskForm):
|
||||
siret = _build_string_field(
|
||||
"SIRET (*)",
|
||||
render_kw={"placeholder": "Numéro composé de 14 chiffres", "maxlength": "14"},
|
||||
)
|
||||
nom_entreprise = _build_string_field("Nom de l'entreprise (*)")
|
||||
adresse = _build_string_field("Adresse de l'entreprise (*)")
|
||||
codepostal = _build_string_field("Code postal de l'entreprise (*)")
|
||||
ville = _build_string_field("Ville de l'entreprise (*)")
|
||||
pays = _build_string_field("Pays de l'entreprise", required=False)
|
||||
|
||||
nom_contact = _build_string_field("Nom du contact (*)")
|
||||
prenom_contact = _build_string_field("Prénom du contact (*)")
|
||||
telephone = _build_string_field("Téléphone du contact (*)", required=False)
|
||||
mail = StringField(
|
||||
"Mail du contact (*)",
|
||||
validators=[Optional(), Email(message="Adresse e-mail invalide")],
|
||||
)
|
||||
poste = _build_string_field("Poste du contact", required=False)
|
||||
service = _build_string_field("Service du contact", required=False)
|
||||
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def validate(self):
|
||||
validate = True
|
||||
if not FlaskForm.validate(self):
|
||||
validate = False
|
||||
|
||||
if not self.telephone.data and not self.mail.data:
|
||||
self.telephone.errors.append(
|
||||
"Saisir un moyen de contact (mail ou téléphone)"
|
||||
)
|
||||
self.mail.errors.append("Saisir un moyen de contact (mail ou téléphone)")
|
||||
validate = False
|
||||
|
||||
return validate
|
||||
|
||||
def validate_siret(self, siret):
|
||||
if EntreprisePreferences.get_check_siret():
|
||||
siret = siret.data.strip()
|
||||
if re.match("^\d{14}$", siret) is None:
|
||||
raise ValidationError("Format incorrect")
|
||||
try:
|
||||
req = requests.get(
|
||||
f"https://entreprise.data.gouv.fr/api/sirene/v1/siret/{siret}"
|
||||
)
|
||||
except requests.ConnectionError:
|
||||
print("no internet")
|
||||
if req.status_code != 200:
|
||||
raise ValidationError("SIRET inexistant")
|
||||
entreprise = Entreprise.query.filter_by(siret=siret).first()
|
||||
if entreprise is not None:
|
||||
lien = f'<a href="/ScoDoc/entreprises/fiche_entreprise/{entreprise.id}">ici</a>'
|
||||
raise ValidationError(
|
||||
Markup(f"Entreprise déjà présent, lien vers la fiche : {lien}")
|
||||
)
|
||||
|
||||
|
||||
class EntrepriseModificationForm(FlaskForm):
|
||||
hidden_entreprise_siret = HiddenField()
|
||||
siret = StringField("SIRET (*)")
|
||||
nom = _build_string_field("Nom de l'entreprise (*)")
|
||||
adresse = _build_string_field("Adresse (*)")
|
||||
codepostal = _build_string_field("Code postal (*)")
|
||||
ville = _build_string_field("Ville (*)")
|
||||
pays = _build_string_field("Pays", required=False)
|
||||
submit = SubmitField("Modifier", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.siret.render_kw = {
|
||||
"disabled": "",
|
||||
"value": self.hidden_entreprise_siret.data,
|
||||
}
|
||||
|
||||
|
||||
class MultiCheckboxField(SelectMultipleField):
|
||||
widget = ListWidget(prefix_label=False)
|
||||
option_widget = CheckboxInput()
|
||||
|
||||
|
||||
class OffreCreationForm(FlaskForm):
|
||||
intitule = _build_string_field("Intitulé (*)")
|
||||
description = TextAreaField(
|
||||
"Description (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
type_offre = SelectField(
|
||||
"Type de l'offre (*)",
|
||||
choices=[("Stage"), ("Alternance")],
|
||||
validators=[DataRequired(message=CHAMP_REQUIS)],
|
||||
)
|
||||
missions = TextAreaField(
|
||||
"Missions (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
duree = _build_string_field("Durée (*)")
|
||||
depts = MultiCheckboxField("Départements", validators=[Optional()], coerce=int)
|
||||
expiration_date = DateField("Date expiration", validators=[Optional()])
|
||||
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.depts.choices = [
|
||||
(dept.id, dept.acronym) for dept in Departement.query.all()
|
||||
]
|
||||
|
||||
|
||||
class OffreModificationForm(FlaskForm):
|
||||
intitule = _build_string_field("Intitulé (*)")
|
||||
description = TextAreaField(
|
||||
"Description (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
type_offre = SelectField(
|
||||
"Type de l'offre (*)",
|
||||
choices=[("Stage"), ("Alternance")],
|
||||
validators=[DataRequired(message=CHAMP_REQUIS)],
|
||||
)
|
||||
missions = TextAreaField(
|
||||
"Missions (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
duree = _build_string_field("Durée (*)")
|
||||
depts = MultiCheckboxField("Départements", validators=[Optional()], coerce=int)
|
||||
expiration_date = DateField("Date expiration", validators=[Optional()])
|
||||
submit = SubmitField("Modifier", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.depts.choices = [
|
||||
(dept.id, dept.acronym) for dept in Departement.query.all()
|
||||
]
|
||||
|
||||
|
||||
class ContactCreationForm(FlaskForm):
|
||||
hidden_entreprise_id = HiddenField()
|
||||
nom = _build_string_field("Nom (*)")
|
||||
prenom = _build_string_field("Prénom (*)")
|
||||
telephone = _build_string_field("Téléphone (*)", required=False)
|
||||
mail = StringField(
|
||||
"Mail (*)",
|
||||
validators=[Optional(), Email(message="Adresse e-mail invalide")],
|
||||
)
|
||||
poste = _build_string_field("Poste", required=False)
|
||||
service = _build_string_field("Service", required=False)
|
||||
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def validate(self):
|
||||
validate = True
|
||||
if not FlaskForm.validate(self):
|
||||
validate = False
|
||||
|
||||
contact = EntrepriseContact.query.filter_by(
|
||||
entreprise_id=self.hidden_entreprise_id.data,
|
||||
nom=self.nom.data,
|
||||
prenom=self.prenom.data,
|
||||
).first()
|
||||
if contact is not None:
|
||||
self.nom.errors.append("Ce contact existe déjà (même nom et prénom)")
|
||||
self.prenom.errors.append("")
|
||||
validate = False
|
||||
|
||||
if not self.telephone.data and not self.mail.data:
|
||||
self.telephone.errors.append(
|
||||
"Saisir un moyen de contact (mail ou téléphone)"
|
||||
)
|
||||
self.mail.errors.append("Saisir un moyen de contact (mail ou téléphone)")
|
||||
validate = False
|
||||
|
||||
return validate
|
||||
|
||||
|
||||
class ContactModificationForm(FlaskForm):
|
||||
hidden_contact_id = HiddenField()
|
||||
hidden_entreprise_id = HiddenField()
|
||||
nom = _build_string_field("Nom (*)")
|
||||
prenom = _build_string_field("Prénom (*)")
|
||||
telephone = _build_string_field("Téléphone (*)", required=False)
|
||||
mail = StringField(
|
||||
"Mail (*)",
|
||||
validators=[Optional(), Email(message="Adresse e-mail invalide")],
|
||||
)
|
||||
poste = _build_string_field("Poste", required=False)
|
||||
service = _build_string_field("Service", required=False)
|
||||
submit = SubmitField("Modifier", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def validate(self):
|
||||
validate = True
|
||||
if not FlaskForm.validate(self):
|
||||
validate = False
|
||||
|
||||
contact = EntrepriseContact.query.filter(
|
||||
EntrepriseContact.id != self.hidden_contact_id.data,
|
||||
EntrepriseContact.entreprise_id == self.hidden_entreprise_id.data,
|
||||
EntrepriseContact.nom == self.nom.data,
|
||||
EntrepriseContact.prenom == self.prenom.data,
|
||||
).first()
|
||||
if contact is not None:
|
||||
self.nom.errors.append("Ce contact existe déjà (même nom et prénom)")
|
||||
self.prenom.errors.append("")
|
||||
validate = False
|
||||
|
||||
if not self.telephone.data and not self.mail.data:
|
||||
self.telephone.errors.append(
|
||||
"Saisir un moyen de contact (mail ou téléphone)"
|
||||
)
|
||||
self.mail.errors.append("Saisir un moyen de contact (mail ou téléphone)")
|
||||
validate = False
|
||||
|
||||
return validate
|
||||
|
||||
|
||||
class HistoriqueCreationForm(FlaskForm):
|
||||
etudiant = _build_string_field(
|
||||
"Étudiant (*)",
|
||||
render_kw={"placeholder": "Tapez le nom de l'étudiant"},
|
||||
)
|
||||
type_offre = SelectField(
|
||||
"Type de l'offre (*)",
|
||||
choices=[("Stage"), ("Alternance")],
|
||||
validators=[DataRequired(message=CHAMP_REQUIS)],
|
||||
)
|
||||
date_debut = DateField(
|
||||
"Date début (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
date_fin = DateField(
|
||||
"Date fin (*)", validators=[DataRequired(message=CHAMP_REQUIS)]
|
||||
)
|
||||
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def validate(self):
|
||||
validate = True
|
||||
if not FlaskForm.validate(self):
|
||||
validate = False
|
||||
|
||||
if (
|
||||
self.date_debut.data
|
||||
and self.date_fin.data
|
||||
and self.date_debut.data > self.date_fin.data
|
||||
):
|
||||
self.date_debut.errors.append("Les dates sont incompatibles")
|
||||
self.date_fin.errors.append("Les dates sont incompatibles")
|
||||
validate = False
|
||||
|
||||
return validate
|
||||
|
||||
def validate_etudiant(self, etudiant):
|
||||
etudiant_data = etudiant.data.upper().strip()
|
||||
stm = text(
|
||||
"SELECT id, CONCAT(nom, ' ', prenom) as nom_prenom FROM Identite WHERE CONCAT(nom, ' ', prenom)=:nom_prenom"
|
||||
)
|
||||
etudiant = (
|
||||
Identite.query.from_statement(stm).params(nom_prenom=etudiant_data).first()
|
||||
)
|
||||
if etudiant is None:
|
||||
raise ValidationError("Champ incorrect (selectionnez dans la liste)")
|
||||
|
||||
|
||||
class EnvoiOffreForm(FlaskForm):
|
||||
responsable = _build_string_field(
|
||||
"Responsable de formation (*)",
|
||||
render_kw={"placeholder": "Tapez le nom du responsable de formation"},
|
||||
)
|
||||
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
def validate_responsable(self, responsable):
|
||||
responsable_data = responsable.data.upper().strip()
|
||||
stm = text(
|
||||
"SELECT id, UPPER(CONCAT(nom, ' ', prenom, ' ', '(', user_name, ')')) FROM \"user\" WHERE UPPER(CONCAT(nom, ' ', prenom, ' ', '(', user_name, ')'))=:responsable_data"
|
||||
)
|
||||
responsable = (
|
||||
User.query.from_statement(stm)
|
||||
.params(responsable_data=responsable_data)
|
||||
.first()
|
||||
)
|
||||
if responsable is None:
|
||||
raise ValidationError("Champ incorrect (selectionnez dans la liste)")
|
||||
|
||||
|
||||
class AjoutFichierForm(FlaskForm):
|
||||
fichier = FileField(
|
||||
"Fichier (*)",
|
||||
validators=[
|
||||
FileRequired(message=CHAMP_REQUIS),
|
||||
FileAllowed(["pdf", "docx"], "Fichier .pdf ou .docx uniquement"),
|
||||
],
|
||||
)
|
||||
submit = SubmitField("Ajouter", render_kw=SUBMIT_MARGE)
|
||||
|
||||
|
||||
class SuppressionConfirmationForm(FlaskForm):
|
||||
submit = SubmitField("Supprimer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
|
||||
class ValidationConfirmationForm(FlaskForm):
|
||||
submit = SubmitField("Valider", render_kw=SUBMIT_MARGE)
|
||||
|
||||
|
||||
class ImportForm(FlaskForm):
|
||||
fichier = FileField(
|
||||
"Fichier (*)",
|
||||
validators=[
|
||||
FileRequired(message=CHAMP_REQUIS),
|
||||
FileAllowed(["xlsx"], "Fichier .xlsx uniquement"),
|
||||
],
|
||||
)
|
||||
submit = SubmitField("Importer", render_kw=SUBMIT_MARGE)
|
||||
|
||||
|
||||
class PreferencesForm(FlaskForm):
|
||||
mail_entreprise = StringField(
|
||||
"Mail notifications",
|
||||
validators=[Optional(), Email(message="Adresse e-mail invalide")],
|
||||
)
|
||||
check_siret = BooleanField("Vérification SIRET")
|
||||
submit = SubmitField("Valider", render_kw=SUBMIT_MARGE)
|
|
@ -0,0 +1,187 @@
|
|||
from app import db
|
||||
|
||||
|
||||
class Entreprise(db.Model):
|
||||
__tablename__ = "are_entreprises"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
siret = db.Column(db.Text)
|
||||
nom = db.Column(db.Text)
|
||||
adresse = db.Column(db.Text)
|
||||
codepostal = db.Column(db.Text)
|
||||
ville = db.Column(db.Text)
|
||||
pays = db.Column(db.Text, default="FRANCE")
|
||||
visible = db.Column(db.Boolean, default=False)
|
||||
contacts = db.relationship(
|
||||
"EntrepriseContact",
|
||||
backref="entreprise",
|
||||
lazy="dynamic",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
offres = db.relationship(
|
||||
"EntrepriseOffre",
|
||||
backref="entreprise",
|
||||
lazy="dynamic",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"siret": self.siret,
|
||||
"nom_entreprise": self.nom,
|
||||
"adresse": self.adresse,
|
||||
"code_postal": self.codepostal,
|
||||
"ville": self.ville,
|
||||
"pays": self.pays,
|
||||
}
|
||||
|
||||
|
||||
class EntrepriseContact(db.Model):
|
||||
__tablename__ = "are_contacts"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_id = db.Column(
|
||||
db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
|
||||
)
|
||||
nom = db.Column(db.Text)
|
||||
prenom = db.Column(db.Text)
|
||||
telephone = db.Column(db.Text)
|
||||
mail = db.Column(db.Text)
|
||||
poste = db.Column(db.Text)
|
||||
service = db.Column(db.Text)
|
||||
|
||||
def to_dict(self):
|
||||
entreprise = Entreprise.query.filter_by(id=self.entreprise_id).first()
|
||||
return {
|
||||
"nom": self.nom,
|
||||
"prenom": self.prenom,
|
||||
"telephone": self.telephone,
|
||||
"mail": self.mail,
|
||||
"poste": self.poste,
|
||||
"service": self.service,
|
||||
"entreprise_siret": entreprise.siret,
|
||||
}
|
||||
|
||||
|
||||
class EntrepriseOffre(db.Model):
|
||||
__tablename__ = "are_offres"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_id = db.Column(
|
||||
db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
|
||||
)
|
||||
date_ajout = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
intitule = db.Column(db.Text)
|
||||
description = db.Column(db.Text)
|
||||
type_offre = db.Column(db.Text)
|
||||
missions = db.Column(db.Text)
|
||||
duree = db.Column(db.Text)
|
||||
expiration_date = db.Column(db.Date)
|
||||
expired = db.Column(db.Boolean, default=False)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"intitule": self.intitule,
|
||||
"description": self.description,
|
||||
"type_offre": self.type_offre,
|
||||
"missions": self.missions,
|
||||
"duree": self.duree,
|
||||
}
|
||||
|
||||
|
||||
class EntrepriseLog(db.Model):
|
||||
__tablename__ = "are_logs"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
authenticated_user = db.Column(db.Text)
|
||||
object = db.Column(db.Integer)
|
||||
text = db.Column(db.Text)
|
||||
|
||||
|
||||
class EntrepriseEtudiant(db.Model):
|
||||
__tablename__ = "are_etudiants"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_id = db.Column(
|
||||
db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
|
||||
)
|
||||
etudid = db.Column(db.Integer)
|
||||
type_offre = db.Column(db.Text)
|
||||
date_debut = db.Column(db.Date)
|
||||
date_fin = db.Column(db.Date)
|
||||
formation_text = db.Column(db.Text)
|
||||
formation_scodoc = db.Column(db.Integer)
|
||||
|
||||
|
||||
class EntrepriseEnvoiOffre(db.Model):
|
||||
__tablename__ = "are_envoi_offre"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
sender_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
|
||||
receiver_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
|
||||
offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
|
||||
date_envoi = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
|
||||
|
||||
class EntrepriseEnvoiOffreEtudiant(db.Model):
|
||||
__tablename__ = "are_envoi_offre_etudiant"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
sender_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
|
||||
receiver_id = db.Column(
|
||||
db.Integer, db.ForeignKey("identite.id", ondelete="cascade")
|
||||
)
|
||||
offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
|
||||
date_envoi = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
|
||||
|
||||
class EntrepriseOffreDepartement(db.Model):
|
||||
__tablename__ = "are_offre_departement"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
|
||||
dept_id = db.Column(db.Integer, db.ForeignKey("departement.id", ondelete="cascade"))
|
||||
|
||||
|
||||
class EntreprisePreferences(db.Model):
|
||||
__tablename__ = "are_preferences"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.Text)
|
||||
value = db.Column(db.Text)
|
||||
|
||||
@classmethod
|
||||
def get_email_notifications(cls):
|
||||
mail = EntreprisePreferences.query.filter_by(
|
||||
name="mail_notifications_entreprise"
|
||||
).first()
|
||||
if mail is None:
|
||||
return ""
|
||||
else:
|
||||
return mail.value
|
||||
|
||||
@classmethod
|
||||
def set_email_notifications(cls, mail: str):
|
||||
if mail != cls.get_email_notifications():
|
||||
m = EntreprisePreferences.query.filter_by(
|
||||
name="mail_notifications_entreprise"
|
||||
).first()
|
||||
if m is None:
|
||||
prefs = EntreprisePreferences(
|
||||
name="mail_notifications_entreprise",
|
||||
value=mail,
|
||||
)
|
||||
db.session.add(prefs)
|
||||
else:
|
||||
m.value = mail
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def get_check_siret(cls):
|
||||
check_siret = EntreprisePreferences.query.filter_by(name="check_siret").first()
|
||||
if check_siret is None:
|
||||
return 1
|
||||
else:
|
||||
return int(check_siret.value)
|
||||
|
||||
@classmethod
|
||||
def set_check_siret(cls, check_siret: int):
|
||||
cs = EntreprisePreferences.query.filter_by(name="check_siret").first()
|
||||
if cs is None:
|
||||
prefs = EntreprisePreferences(name="check_siret", value=check_siret)
|
||||
db.session.add(prefs)
|
||||
else:
|
||||
cs.value = check_siret
|
||||
db.session.commit()
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1 @@
|
|||
# empty but required for pylint
|
|
@ -0,0 +1 @@
|
|||
# empty but required for pylint
|
|
@ -28,19 +28,14 @@
|
|||
"""
|
||||
Formulaires configuration Exports Apogée (codes)
|
||||
"""
|
||||
import re
|
||||
|
||||
from flask import flash, url_for, redirect, render_template
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import SubmitField, validators
|
||||
from wtforms.fields.simple import StringField
|
||||
|
||||
from app import models
|
||||
from app.models import ScoDocSiteConfig
|
||||
from app.models import SHORT_STR_LEN
|
||||
|
||||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_utils as scu
|
||||
|
||||
|
||||
def _build_code_field(code):
|
||||
|
@ -62,6 +57,7 @@ def _build_code_field(code):
|
|||
|
||||
|
||||
class CodesDecisionsForm(FlaskForm):
|
||||
"Formulaire code décisions Apogée"
|
||||
ADC = _build_code_field("ADC")
|
||||
ADJ = _build_code_field("ADJ")
|
||||
ADM = _build_code_field("ADM")
|
||||
|
@ -71,8 +67,19 @@ class CodesDecisionsForm(FlaskForm):
|
|||
ATT = _build_code_field("ATT")
|
||||
CMP = _build_code_field("CMP")
|
||||
DEF = _build_code_field("DEF")
|
||||
DEM = _build_code_field("DEF")
|
||||
DEM = _build_code_field("DEM")
|
||||
NAR = _build_code_field("NAR")
|
||||
RAT = _build_code_field("RAT")
|
||||
NOTES_FMT = StringField(
|
||||
label="Format notes exportées",
|
||||
description="""Format des notes. Par défaut <tt style="font-family: monotype;">%3.2f</tt> (deux chiffres après la virgule)""",
|
||||
validators=[
|
||||
validators.Length(
|
||||
max=SHORT_STR_LEN,
|
||||
message=f"Le format ne doit pas dépasser {SHORT_STR_LEN} caractères",
|
||||
),
|
||||
validators.DataRequired("format requis"),
|
||||
],
|
||||
)
|
||||
submit = SubmitField("Valider")
|
||||
cancel = SubmitField("Annuler", render_kw={"formnovalidate": True})
|
||||
|
|
|
@ -30,30 +30,26 @@ Formulaires configuration logos
|
|||
|
||||
Contrib @jmp, dec 21
|
||||
"""
|
||||
import re
|
||||
|
||||
from flask import flash, url_for, redirect, render_template
|
||||
from flask_wtf import FlaskForm
|
||||
from flask_wtf.file import FileField, FileAllowed
|
||||
from wtforms import SelectField, SubmitField, FormField, validators, FieldList
|
||||
from wtforms import SubmitField, FormField, validators, FieldList
|
||||
from wtforms import ValidationError
|
||||
from wtforms.fields.simple import StringField, HiddenField
|
||||
|
||||
from app import AccessDenied
|
||||
from app.models import Departement
|
||||
from app.models import ScoDocSiteConfig
|
||||
from app.scodoc import sco_logos, html_sco_header
|
||||
from app.scodoc import sco_utils as scu
|
||||
from app.scodoc.sco_config_actions import (
|
||||
LogoDelete,
|
||||
LogoUpdate,
|
||||
LogoInsert,
|
||||
BonusSportUpdate,
|
||||
)
|
||||
|
||||
from flask_login import current_user
|
||||
|
||||
from app.scodoc.sco_logos import find_logo
|
||||
|
||||
|
||||
JAVASCRIPTS = html_sco_header.BOOTSTRAP_MULTISELECT_JS + []
|
||||
|
||||
CSSSTYLES = html_sco_header.BOOTSTRAP_MULTISELECT_CSS
|
||||
|
@ -112,6 +108,15 @@ def dept_key_to_id(dept_key):
|
|||
return dept_key
|
||||
|
||||
|
||||
def logo_name_validator(message=None):
|
||||
def validate_logo_name(form, field):
|
||||
name = field.data if field.data else ""
|
||||
if not scu.is_valid_filename(name):
|
||||
raise ValidationError(message)
|
||||
|
||||
return validate_logo_name
|
||||
|
||||
|
||||
class AddLogoForm(FlaskForm):
|
||||
"""Formulaire permettant l'ajout d'un logo (dans un département)"""
|
||||
|
||||
|
@ -119,11 +124,7 @@ class AddLogoForm(FlaskForm):
|
|||
name = StringField(
|
||||
label="Nom",
|
||||
validators=[
|
||||
validators.regexp(
|
||||
r"^[a-zA-Z0-9-]*$",
|
||||
re.IGNORECASE,
|
||||
"Ne doit comporter que lettres, chiffres ou -",
|
||||
),
|
||||
logo_name_validator("Nom de logo invalide (alphanumérique, _)"),
|
||||
validators.Length(
|
||||
max=20, message="Un nom ne doit pas dépasser 20 caractères"
|
||||
),
|
||||
|
@ -296,23 +297,15 @@ def _make_depts_data(modele):
|
|||
return data
|
||||
|
||||
|
||||
def _make_data(bonus_sport, modele):
|
||||
def _make_data(modele):
|
||||
data = {
|
||||
"bonus_sport_func_name": bonus_sport,
|
||||
"depts": _make_depts_data(modele=modele),
|
||||
}
|
||||
return data
|
||||
|
||||
|
||||
class ScoDocConfigurationForm(FlaskForm):
|
||||
"Panneau de configuration général"
|
||||
bonus_sport_func_name = SelectField(
|
||||
label="Fonction de calcul des bonus sport&culture",
|
||||
choices=[
|
||||
(x, x if x else "Aucune")
|
||||
for x in ScoDocSiteConfig.get_bonus_sport_func_names()
|
||||
],
|
||||
)
|
||||
class LogosConfigurationForm(FlaskForm):
|
||||
"Panneau de configuration des logos"
|
||||
depts = FieldList(FormField(DeptForm))
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
@ -361,11 +354,6 @@ class ScoDocConfigurationForm(FlaskForm):
|
|||
return dept_form.get_form(logoname)
|
||||
|
||||
def select_action(self):
|
||||
if (
|
||||
self.data["bonus_sport_func_name"]
|
||||
!= ScoDocSiteConfig.get_bonus_sport_func_name()
|
||||
):
|
||||
return BonusSportUpdate(self.data)
|
||||
for dept_entry in self.depts:
|
||||
dept_form = dept_entry.form
|
||||
action = dept_form.select_action()
|
||||
|
@ -374,14 +362,11 @@ class ScoDocConfigurationForm(FlaskForm):
|
|||
return None
|
||||
|
||||
|
||||
def configuration():
|
||||
"""Panneau de configuration général"""
|
||||
auth_name = str(current_user)
|
||||
if not current_user.is_administrator():
|
||||
raise AccessDenied("invalid user (%s) must be SuperAdmin" % auth_name)
|
||||
form = ScoDocConfigurationForm(
|
||||
def config_logos():
|
||||
"Page de configuration des logos"
|
||||
# nb: le contrôle d'accès (SuperAdmin) doit être fait dans la vue
|
||||
form = LogosConfigurationForm(
|
||||
data=_make_data(
|
||||
bonus_sport=ScoDocSiteConfig.get_bonus_sport_func_name(),
|
||||
modele=sco_logos.list_logos(),
|
||||
)
|
||||
)
|
||||
|
@ -390,13 +375,13 @@ def configuration():
|
|||
if action:
|
||||
action.execute()
|
||||
flash(action.message)
|
||||
return redirect(
|
||||
url_for(
|
||||
"scodoc.configuration",
|
||||
)
|
||||
)
|
||||
return redirect(url_for("scodoc.configure_logos"))
|
||||
else:
|
||||
if not form.validate():
|
||||
scu.flash_errors(form)
|
||||
|
||||
return render_template(
|
||||
"configuration.html",
|
||||
"config_logos.html",
|
||||
scodoc_dept=None,
|
||||
title="Configuration ScoDoc",
|
||||
form=form,
|
|
@ -0,0 +1,103 @@
|
|||
# -*- mode: python -*-
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# ScoDoc
|
||||
#
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
#
|
||||
# Emmanuel Viennet emmanuel.viennet@viennet.net
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
"""
|
||||
Formulaires configuration Exports Apogée (codes)
|
||||
"""
|
||||
|
||||
from flask import flash, url_for, redirect, request, render_template
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import BooleanField, SelectField, SubmitField
|
||||
|
||||
import app
|
||||
from app.models import ScoDocSiteConfig
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
|
||||
class BonusConfigurationForm(FlaskForm):
|
||||
"Panneau de configuration des logos"
|
||||
bonus_sport_func_name = SelectField(
|
||||
label="Fonction de calcul des bonus sport&culture",
|
||||
choices=[
|
||||
(name, displayed_name if name else "Aucune")
|
||||
for (name, displayed_name) in ScoDocSiteConfig.get_bonus_sport_class_list()
|
||||
],
|
||||
)
|
||||
submit_bonus = SubmitField("Valider")
|
||||
cancel_bonus = SubmitField("Annuler", render_kw={"formnovalidate": True})
|
||||
|
||||
|
||||
class ScoDocConfigurationForm(FlaskForm):
|
||||
"Panneau de configuration avancée"
|
||||
enable_entreprises = BooleanField("activer le module <em>entreprises</em>")
|
||||
submit_scodoc = SubmitField("Valider")
|
||||
cancel_scodoc = SubmitField("Annuler", render_kw={"formnovalidate": True})
|
||||
|
||||
|
||||
def configuration():
|
||||
"Page de configuration principale"
|
||||
# nb: le contrôle d'accès (SuperAdmin) doit être fait dans la vue
|
||||
form_bonus = BonusConfigurationForm(
|
||||
data={
|
||||
"bonus_sport_func_name": ScoDocSiteConfig.get_bonus_sport_class_name(),
|
||||
}
|
||||
)
|
||||
form_scodoc = ScoDocConfigurationForm(
|
||||
data={"enable_entreprises": ScoDocSiteConfig.is_entreprises_enabled()}
|
||||
)
|
||||
if request.method == "POST" and (
|
||||
form_bonus.cancel_bonus.data or form_scodoc.cancel_scodoc.data
|
||||
): # cancel button
|
||||
return redirect(url_for("scodoc.index"))
|
||||
if form_bonus.submit_bonus.data and form_bonus.validate():
|
||||
if (
|
||||
form_bonus.data["bonus_sport_func_name"]
|
||||
!= ScoDocSiteConfig.get_bonus_sport_class_name()
|
||||
):
|
||||
ScoDocSiteConfig.set_bonus_sport_class(
|
||||
form_bonus.data["bonus_sport_func_name"]
|
||||
)
|
||||
app.clear_scodoc_cache()
|
||||
flash(f"Fonction bonus sport&culture configurée.")
|
||||
return redirect(url_for("scodoc.index"))
|
||||
elif form_scodoc.submit_scodoc.data and form_scodoc.validate():
|
||||
if ScoDocSiteConfig.enable_entreprises(
|
||||
enabled=form_scodoc.data["enable_entreprises"]
|
||||
):
|
||||
flash(
|
||||
"Module entreprise "
|
||||
+ ("activé" if form_scodoc.data["enable_entreprises"] else "désactivé")
|
||||
)
|
||||
return redirect(url_for("scodoc.index"))
|
||||
|
||||
return render_template(
|
||||
"configuration.html",
|
||||
form_bonus=form_bonus,
|
||||
form_scodoc=form_scodoc,
|
||||
scu=scu,
|
||||
title="Configuration",
|
||||
)
|
|
@ -29,7 +29,6 @@
|
|||
Formulaires création département
|
||||
"""
|
||||
|
||||
from flask import flash, url_for, redirect, render_template
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import SubmitField, validators
|
||||
from wtforms.fields.simple import StringField, BooleanField
|
||||
|
|
|
@ -12,14 +12,7 @@ GROUPNAME_STR_LEN = 64
|
|||
from app.models.raw_sql_init import create_database_functions
|
||||
|
||||
from app.models.absences import Absence, AbsenceNotification, BilletAbsence
|
||||
from app.models.config import ScoDocSiteConfig
|
||||
from app.models.departements import Departement
|
||||
|
||||
from app.models.entreprises import (
|
||||
Entreprise,
|
||||
EntrepriseCorrespondant,
|
||||
EntrepriseContact,
|
||||
)
|
||||
from app.models.etudiants import (
|
||||
Identite,
|
||||
Adresse,
|
||||
|
@ -56,13 +49,15 @@ from app.models.evaluations import (
|
|||
)
|
||||
from app.models.groups import Partition, GroupDescr, group_membership
|
||||
from app.models.notes import (
|
||||
ScolarEvent,
|
||||
ScolarFormSemestreValidation,
|
||||
ScolarAutorisationInscription,
|
||||
BulAppreciations,
|
||||
NotesNotes,
|
||||
NotesNotesLog,
|
||||
)
|
||||
from app.models.validations import (
|
||||
ScolarEvent,
|
||||
ScolarFormSemestreValidation,
|
||||
ScolarAutorisationInscription,
|
||||
)
|
||||
from app.models.preferences import ScoPreference
|
||||
|
||||
from app.models.but_refcomp import (
|
||||
|
@ -71,3 +66,4 @@ from app.models.but_refcomp import (
|
|||
ApcSituationPro,
|
||||
ApcAppCritique,
|
||||
)
|
||||
from app.models.config import ScoDocSiteConfig
|
||||
|
|
|
@ -9,11 +9,24 @@ from datetime import datetime
|
|||
from enum import unique
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import class_mapper
|
||||
import sqlalchemy
|
||||
|
||||
from app import db
|
||||
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
# from https://stackoverflow.com/questions/2537471/method-of-iterating-over-sqlalchemy-models-defined-columns
|
||||
def attribute_names(cls):
|
||||
"liste ids (noms de colonnes) d'un modèle"
|
||||
return [
|
||||
prop.key
|
||||
for prop in class_mapper(cls).iterate_properties
|
||||
if isinstance(prop, sqlalchemy.orm.ColumnProperty)
|
||||
]
|
||||
|
||||
|
||||
class XMLModel:
|
||||
_xml_attribs = {} # to be overloaded
|
||||
id = "_"
|
||||
|
@ -24,21 +37,31 @@ class XMLModel:
|
|||
and renamed for our models.
|
||||
The mapping is specified by the _xml_attribs
|
||||
attribute in each model class.
|
||||
Keep only attributes corresponding to columns in our model:
|
||||
other XML attributes are simply ignored.
|
||||
"""
|
||||
return {cls._xml_attribs.get(k, k): v for (k, v) in args.items()}
|
||||
columns = attribute_names(cls)
|
||||
renamed_attributes = {cls._xml_attribs.get(k, k): v for (k, v) in args.items()}
|
||||
return {k: renamed_attributes[k] for k in renamed_attributes if k in columns}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<{self.__class__.__name__} {self.id} "{self.titre if hasattr(self, "titre") else ""}">'
|
||||
|
||||
|
||||
class ApcReferentielCompetences(db.Model, XMLModel):
|
||||
"Référentiel de compétence d'une spécialité"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
dept_id = db.Column(db.Integer, db.ForeignKey("departement.id"), index=True)
|
||||
annexe = db.Column(db.Text())
|
||||
specialite = db.Column(db.Text())
|
||||
specialite_long = db.Column(db.Text())
|
||||
type_titre = db.Column(db.Text())
|
||||
type_structure = db.Column(db.Text())
|
||||
type_departement = db.Column(db.Text()) # "secondaire", "tertiaire"
|
||||
version_orebut = db.Column(db.Text())
|
||||
_xml_attribs = { # Orébut xml attrib : attribute
|
||||
"type": "type_titre",
|
||||
"version": "version_orebut",
|
||||
}
|
||||
# ScoDoc specific fields:
|
||||
scodoc_date_loaded = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
|
@ -58,15 +81,22 @@ class ApcReferentielCompetences(db.Model, XMLModel):
|
|||
)
|
||||
formations = db.relationship("Formation", backref="referentiel_competence")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ApcReferentielCompetences {self.id} {self.specialite}>"
|
||||
|
||||
def to_dict(self):
|
||||
"""Représentation complète du ref. de comp.
|
||||
comme un dict.
|
||||
"""
|
||||
return {
|
||||
"dept_id": self.dept_id,
|
||||
"annexe": self.annexe,
|
||||
"specialite": self.specialite,
|
||||
"specialite_long": self.specialite_long,
|
||||
"type_structure": self.type_structure,
|
||||
"type_departement": self.type_departement,
|
||||
"type_titre": self.type_titre,
|
||||
"version_orebut": self.version_orebut,
|
||||
"scodoc_date_loaded": self.scodoc_date_loaded.isoformat() + "Z"
|
||||
if self.scodoc_date_loaded
|
||||
else "",
|
||||
|
@ -77,23 +107,21 @@ class ApcReferentielCompetences(db.Model, XMLModel):
|
|||
|
||||
|
||||
class ApcCompetence(db.Model, XMLModel):
|
||||
__table_args__ = (
|
||||
# les compétences dans Orébut sont identifiées par leur "titre"
|
||||
# unique au sein d'un référentiel:
|
||||
db.UniqueConstraint(
|
||||
"referentiel_id", "titre", name="apc_competence_referentiel_id_titre_key"
|
||||
),
|
||||
)
|
||||
"Compétence"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
referentiel_id = db.Column(
|
||||
db.Integer, db.ForeignKey("apc_referentiel_competences.id"), nullable=False
|
||||
)
|
||||
# les compétences dans Orébut sont identifiées par leur id unique
|
||||
# (mais id_orebut n'est pas unique car le même ref. pourra être chargé dans plusieurs depts)
|
||||
id_orebut = db.Column(db.Text(), nullable=True, index=True)
|
||||
titre = db.Column(db.Text(), nullable=False, index=True)
|
||||
titre_long = db.Column(db.Text())
|
||||
couleur = db.Column(db.Text())
|
||||
numero = db.Column(db.Integer) # ordre de présentation
|
||||
_xml_attribs = { # xml_attrib : attribute
|
||||
"name": "titre",
|
||||
"id": "id_orebut",
|
||||
"nom_court": "titre", # was name
|
||||
"libelle_long": "titre_long",
|
||||
}
|
||||
situations = db.relationship(
|
||||
|
@ -115,8 +143,12 @@ class ApcCompetence(db.Model, XMLModel):
|
|||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ApcCompetence {self.id} {self.titre}>"
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"id_orebut": self.id_orebut,
|
||||
"titre": self.titre,
|
||||
"titre_long": self.titre_long,
|
||||
"couleur": self.couleur,
|
||||
|
@ -246,7 +278,10 @@ class ApcAnneeParcours(db.Model, XMLModel):
|
|||
return {
|
||||
"ordre": self.ordre,
|
||||
"competences": {
|
||||
x.competence.titre: {"niveau": x.niveau}
|
||||
x.competence.titre: {
|
||||
"niveau": x.niveau,
|
||||
"id_orebut": x.competence.id_orebut,
|
||||
}
|
||||
for x in self.niveaux_competences
|
||||
},
|
||||
}
|
||||
|
|
|
@ -3,10 +3,10 @@
|
|||
"""Model : site config WORK IN PROGRESS #WIP
|
||||
"""
|
||||
|
||||
from flask import flash
|
||||
from app import db, log
|
||||
from app.scodoc import bonus_sport
|
||||
from app.comp import bonus_spo
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
import functools
|
||||
|
||||
from app.scodoc.sco_codes_parcours import (
|
||||
ADC,
|
||||
|
@ -36,6 +36,7 @@ CODES_SCODOC_TO_APO = {
|
|||
DEM: "NAR",
|
||||
NAR: "NAR",
|
||||
RAT: "ATT",
|
||||
"NOTES_FMT": "%3.2f",
|
||||
}
|
||||
|
||||
|
||||
|
@ -69,6 +70,7 @@ class ScoDocSiteConfig(db.Model):
|
|||
"INSTITUTION_ADDRESS": str,
|
||||
"INSTITUTION_CITY": str,
|
||||
"DEFAULT_PDF_FOOTER_TEMPLATE": str,
|
||||
"enable_entreprises": bool,
|
||||
}
|
||||
|
||||
def __init__(self, name, value):
|
||||
|
@ -87,69 +89,74 @@ class ScoDocSiteConfig(db.Model):
|
|||
}
|
||||
|
||||
@classmethod
|
||||
def set_bonus_sport_func(cls, func_name):
|
||||
def set_bonus_sport_class(cls, class_name):
|
||||
"""Record bonus_sport config.
|
||||
If func_name not defined, raise NameError
|
||||
If class_name not defined, raise NameError
|
||||
"""
|
||||
if func_name not in cls.get_bonus_sport_func_names():
|
||||
raise NameError("invalid function name for bonus_sport")
|
||||
if class_name not in cls.get_bonus_sport_class_names():
|
||||
raise NameError("invalid class name for bonus_sport")
|
||||
c = ScoDocSiteConfig.query.filter_by(name=cls.BONUS_SPORT).first()
|
||||
if c:
|
||||
log("setting to " + func_name)
|
||||
c.value = func_name
|
||||
log("setting to " + class_name)
|
||||
c.value = class_name
|
||||
else:
|
||||
c = ScoDocSiteConfig(cls.BONUS_SPORT, func_name)
|
||||
c = ScoDocSiteConfig(cls.BONUS_SPORT, class_name)
|
||||
db.session.add(c)
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def get_bonus_sport_func_name(cls):
|
||||
def get_bonus_sport_class_name(cls):
|
||||
"""Get configured bonus function name, or None if None."""
|
||||
f = cls.get_bonus_sport_func_from_name()
|
||||
if f is None:
|
||||
klass = cls.get_bonus_sport_class_from_name()
|
||||
if klass is None:
|
||||
return ""
|
||||
else:
|
||||
return f.__name__
|
||||
return klass.name
|
||||
|
||||
@classmethod
|
||||
def get_bonus_sport_func(cls):
|
||||
def get_bonus_sport_class(cls):
|
||||
"""Get configured bonus function, or None if None."""
|
||||
return cls.get_bonus_sport_func_from_name()
|
||||
return cls.get_bonus_sport_class_from_name()
|
||||
|
||||
@classmethod
|
||||
def get_bonus_sport_func_from_name(cls, func_name=None):
|
||||
"""returns bonus func with specified name.
|
||||
def get_bonus_sport_class_from_name(cls, class_name=None):
|
||||
"""returns bonus class with specified name.
|
||||
If name not specified, return the configured function.
|
||||
None if no bonus function configured.
|
||||
Raises ScoValueError if func_name not found in module bonus_sport.
|
||||
If class_name not found in module bonus_sport, returns None
|
||||
and flash a warning.
|
||||
"""
|
||||
if func_name is None:
|
||||
if not class_name: # None or ""
|
||||
c = ScoDocSiteConfig.query.filter_by(name=cls.BONUS_SPORT).first()
|
||||
if c is None:
|
||||
return None
|
||||
func_name = c.value
|
||||
if func_name == "": # pas de bonus défini
|
||||
class_name = c.value
|
||||
if class_name == "": # pas de bonus défini
|
||||
return None
|
||||
try:
|
||||
return getattr(bonus_sport, func_name)
|
||||
except AttributeError:
|
||||
raise ScoValueError(
|
||||
f"""Fonction de calcul maison inexistante: {func_name}.
|
||||
(contacter votre administrateur local)."""
|
||||
klass = bonus_spo.get_bonus_class_dict().get(class_name)
|
||||
if klass is None:
|
||||
flash(
|
||||
f"""Fonction de calcul bonus sport inexistante: {class_name}.
|
||||
Changez là ou contactez votre administrateur local."""
|
||||
)
|
||||
return klass
|
||||
|
||||
@classmethod
|
||||
def get_bonus_sport_func_names(cls):
|
||||
"""List available functions names
|
||||
def get_bonus_sport_class_names(cls) -> list:
|
||||
"""List available bonus class names
|
||||
(starting with empty string to represent "no bonus function").
|
||||
"""
|
||||
return [""] + sorted(
|
||||
[
|
||||
getattr(bonus_sport, name).__name__
|
||||
for name in dir(bonus_sport)
|
||||
if name.startswith("bonus_")
|
||||
]
|
||||
)
|
||||
return [""] + sorted(bonus_spo.get_bonus_class_dict().keys())
|
||||
|
||||
@classmethod
|
||||
def get_bonus_sport_class_list(cls) -> list[tuple]:
|
||||
"""List available bonus class names
|
||||
(starting with empty string to represent "no bonus function").
|
||||
"""
|
||||
d = bonus_spo.get_bonus_class_dict()
|
||||
class_list = [(name, d[name].displayed_name) for name in d.keys()]
|
||||
class_list.sort(key=lambda x: x[1].replace(" du ", " de "))
|
||||
return [("", "")] + class_list
|
||||
|
||||
@classmethod
|
||||
def get_code_apo(cls, code: str) -> str:
|
||||
|
@ -176,3 +183,27 @@ class ScoDocSiteConfig(db.Model):
|
|||
cfg.value = code_apo
|
||||
db.session.add(cfg)
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def is_entreprises_enabled(cls) -> bool:
|
||||
"""True si on doit activer le module entreprise"""
|
||||
cfg = ScoDocSiteConfig.query.filter_by(name="enable_entreprises").first()
|
||||
if (cfg is None) or not cfg.value:
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def enable_entreprises(cls, enabled=True) -> bool:
|
||||
"""Active (ou déactive) le module entreprises. True si changement."""
|
||||
if enabled != ScoDocSiteConfig.is_entreprises_enabled():
|
||||
cfg = ScoDocSiteConfig.query.filter_by(name="enable_entreprises").first()
|
||||
if cfg is None:
|
||||
cfg = ScoDocSiteConfig(
|
||||
name="enable_entreprises", value="on" if enabled else ""
|
||||
)
|
||||
else:
|
||||
cfg.value = "on" if enabled else ""
|
||||
db.session.add(cfg)
|
||||
db.session.commit()
|
||||
return True
|
||||
return False
|
||||
|
|
|
@ -21,7 +21,7 @@ class Departement(db.Model):
|
|||
db.Boolean(), nullable=False, default=True, server_default="true"
|
||||
) # sur page d'accueil
|
||||
|
||||
entreprises = db.relationship("Entreprise", lazy="dynamic", backref="departement")
|
||||
# entreprises = db.relationship("Entreprise", lazy="dynamic", backref="departement")
|
||||
etudiants = db.relationship("Identite", lazy="dynamic", backref="departement")
|
||||
formations = db.relationship("Formation", lazy="dynamic", backref="departement")
|
||||
formsemestres = db.relationship(
|
||||
|
@ -55,6 +55,9 @@ def create_dept(acronym: str, visible=True) -> Departement:
|
|||
"Create new departement"
|
||||
from app.models import ScoPreference
|
||||
|
||||
existing = Departement.query.filter_by(acronym=acronym).count()
|
||||
if existing:
|
||||
raise ValueError(f"acronyme {acronym} déjà existant")
|
||||
departement = Departement(acronym=acronym, visible=visible)
|
||||
p1 = ScoPreference(name="DeptName", value=acronym, departement=departement)
|
||||
db.session.add(p1)
|
||||
|
|
|
@ -1,66 +0,0 @@
|
|||
# -*- coding: UTF-8 -*
|
||||
|
||||
"""Gestion des absences
|
||||
"""
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class Entreprise(db.Model):
|
||||
"""une entreprise"""
|
||||
|
||||
__tablename__ = "entreprises"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_id = db.synonym("id")
|
||||
dept_id = db.Column(db.Integer, db.ForeignKey("departement.id"), index=True)
|
||||
nom = db.Column(db.Text)
|
||||
adresse = db.Column(db.Text)
|
||||
ville = db.Column(db.Text)
|
||||
codepostal = db.Column(db.Text)
|
||||
pays = db.Column(db.Text)
|
||||
contact_origine = db.Column(db.Text)
|
||||
secteur = db.Column(db.Text)
|
||||
note = db.Column(db.Text)
|
||||
privee = db.Column(db.Text)
|
||||
localisation = db.Column(db.Text)
|
||||
# -1 inconnue, 0, 25, 50, 75, 100:
|
||||
qualite_relation = db.Column(db.Integer)
|
||||
plus10salaries = db.Column(db.Boolean())
|
||||
date_creation = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
|
||||
|
||||
class EntrepriseCorrespondant(db.Model):
|
||||
"""Personne contact en entreprise"""
|
||||
|
||||
__tablename__ = "entreprise_correspondant"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_corresp_id = db.synonym("id")
|
||||
entreprise_id = db.Column(db.Integer, db.ForeignKey("entreprises.id"))
|
||||
nom = db.Column(db.Text)
|
||||
prenom = db.Column(db.Text)
|
||||
civilite = db.Column(db.Text)
|
||||
fonction = db.Column(db.Text)
|
||||
phone1 = db.Column(db.Text)
|
||||
phone2 = db.Column(db.Text)
|
||||
mobile = db.Column(db.Text)
|
||||
mail1 = db.Column(db.Text)
|
||||
mail2 = db.Column(db.Text)
|
||||
fax = db.Column(db.Text)
|
||||
note = db.Column(db.Text)
|
||||
|
||||
|
||||
class EntrepriseContact(db.Model):
|
||||
"""Evènement (contact) avec une entreprise"""
|
||||
|
||||
__tablename__ = "entreprise_contact"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
entreprise_contact_id = db.synonym("id")
|
||||
date = db.Column(db.DateTime(timezone=True))
|
||||
type_contact = db.Column(db.Text)
|
||||
entreprise_id = db.Column(db.Integer, db.ForeignKey("entreprises.id"))
|
||||
entreprise_corresp_id = db.Column(
|
||||
db.Integer, db.ForeignKey("entreprise_correspondant.id")
|
||||
)
|
||||
etudid = db.Column(db.Integer) # sans contrainte pour garder logs après suppression
|
||||
description = db.Column(db.Text)
|
||||
enseignant = db.Column(db.Text)
|
|
@ -4,11 +4,21 @@
|
|||
et données rattachées (adresses, annotations, ...)
|
||||
"""
|
||||
|
||||
from flask import g, url_for
|
||||
import datetime
|
||||
from functools import cached_property
|
||||
from flask import abort, url_for
|
||||
from flask import g, request
|
||||
import sqlalchemy
|
||||
from sqlalchemy import desc, text
|
||||
|
||||
from app import db
|
||||
from app import db, log
|
||||
from app import models
|
||||
|
||||
from app.scodoc import notesdb as ndb
|
||||
from app.scodoc.sco_bac import Baccalaureat
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
|
||||
class Identite(db.Model):
|
||||
"""étudiant"""
|
||||
|
@ -46,18 +56,42 @@ class Identite(db.Model):
|
|||
#
|
||||
adresses = db.relationship("Adresse", lazy="dynamic", backref="etud")
|
||||
billets = db.relationship("BilletAbsence", backref="etudiant", lazy="dynamic")
|
||||
# one-to-one relation:
|
||||
admission = db.relationship("Admission", backref="identite", lazy="dynamic")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Etud {self.id} {self.nom} {self.prenom}>"
|
||||
|
||||
@classmethod
|
||||
def from_request(cls, etudid=None, code_nip=None):
|
||||
"""Etudiant à partir de l'etudid ou du code_nip, soit
|
||||
passés en argument soit retrouvés directement dans la requête web.
|
||||
Erreur 404 si inexistant.
|
||||
"""
|
||||
args = make_etud_args(etudid=etudid, code_nip=code_nip)
|
||||
return Identite.query.filter_by(**args).first_or_404()
|
||||
|
||||
@property
|
||||
def civilite_str(self):
|
||||
"""returns 'M.' ou 'Mme' ou '' (pour le genre neutre,
|
||||
personnes ne souhaitant pas d'affichage).
|
||||
"""
|
||||
return {"M": "M.", "F": "Mme", "X": ""}[self.civilite]
|
||||
|
||||
def nom_disp(self):
|
||||
"nom à afficher"
|
||||
def sex_nom(self, no_accents=False) -> str:
|
||||
"'M. DUPONTÉ', ou si no_accents, 'M. DUPONTE'"
|
||||
s = f"{self.civilite_str} {(self.nom_usuel or self.nom).upper()}"
|
||||
if no_accents:
|
||||
return scu.suppress_accents(s)
|
||||
return s
|
||||
|
||||
@property
|
||||
def e(self):
|
||||
"terminaison en français: 'ne', '', 'ou '(e)'"
|
||||
return {"M": "", "F": "e"}.get(self.civilite, "(e)")
|
||||
|
||||
def nom_disp(self) -> str:
|
||||
"Nom à afficher"
|
||||
if self.nom_usuel:
|
||||
return (
|
||||
(self.nom_usuel + " (" + self.nom + ")") if self.nom else self.nom_usuel
|
||||
|
@ -65,32 +99,92 @@ class Identite(db.Model):
|
|||
else:
|
||||
return self.nom
|
||||
|
||||
@cached_property
|
||||
def nomprenom(self, reverse=False) -> str:
|
||||
"""Civilité/nom/prenom pour affichages: "M. Pierre Dupont"
|
||||
Si reverse, "Dupont Pierre", sans civilité.
|
||||
"""
|
||||
nom = self.nom_usuel or self.nom
|
||||
prenom = self.prenom_str
|
||||
if reverse:
|
||||
fields = (nom, prenom)
|
||||
else:
|
||||
fields = (self.civilite_str, prenom, nom)
|
||||
return " ".join([x for x in fields if x])
|
||||
|
||||
@property
|
||||
def prenom_str(self):
|
||||
"""Prénom à afficher. Par exemple: "Jean-Christophe" """
|
||||
if not self.prenom:
|
||||
return ""
|
||||
frags = self.prenom.split()
|
||||
r = []
|
||||
for frag in frags:
|
||||
fields = frag.split("-")
|
||||
r.append("-".join([x.lower().capitalize() for x in fields]))
|
||||
return " ".join(r)
|
||||
|
||||
@property
|
||||
def nom_short(self):
|
||||
"Nom et début du prénom pour table recap: 'DUPONT Pi.'"
|
||||
return f"{(self.nom_usuel or self.nom or '?').upper()} {(self.prenom or '')[:2].capitalize()}."
|
||||
|
||||
@cached_property
|
||||
def sort_key(self) -> tuple:
|
||||
"clé pour tris par ordre alphabétique"
|
||||
return (
|
||||
scu.suppress_accents(self.nom_usuel or self.nom or "").lower(),
|
||||
scu.suppress_accents(self.prenom or "").lower(),
|
||||
)
|
||||
|
||||
def get_first_email(self, field="email") -> str:
|
||||
"le mail associé à la première adrese de l'étudiant, ou None"
|
||||
return self.adresses[0].email or None if self.adresses.count() > 0 else None
|
||||
"Le mail associé à la première adrese de l'étudiant, ou None"
|
||||
return getattr(self.adresses[0], field) if self.adresses.count() > 0 else None
|
||||
|
||||
def to_dict_scodoc7(self):
|
||||
"""Représentation dictionnaire,
|
||||
compatible ScoDoc7 mais sans infos admission
|
||||
"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
# ScoDoc7 output_formators: (backward compat)
|
||||
e["etudid"] = self.id
|
||||
e["date_naissance"] = ndb.DateISOtoDMY(e["date_naissance"])
|
||||
e["ne"] = self.e
|
||||
return {k: e[k] or "" for k in e} # convert_null_outputs_to_empty
|
||||
|
||||
def to_dict_bul(self, include_urls=True):
|
||||
"""Infos exportées dans les bulletins"""
|
||||
"""Infos exportées dans les bulletins
|
||||
L'étudiant, et sa première adresse.
|
||||
"""
|
||||
from app.scodoc import sco_photos
|
||||
|
||||
d = {
|
||||
"civilite": self.civilite,
|
||||
"code_ine": self.code_ine,
|
||||
"code_nip": self.code_nip,
|
||||
"date_naissance": self.date_naissance.isoformat()
|
||||
"code_ine": self.code_ine or "",
|
||||
"code_nip": self.code_nip or "",
|
||||
"date_naissance": self.date_naissance.strftime("%d/%m/%Y")
|
||||
if self.date_naissance
|
||||
else None,
|
||||
"email": self.get_first_email(),
|
||||
else "",
|
||||
"email": self.get_first_email() or "",
|
||||
"emailperso": self.get_first_email("emailperso"),
|
||||
"etudid": self.id,
|
||||
"nom": self.nom_disp(),
|
||||
"prenom": self.prenom,
|
||||
"prenom": self.prenom or "",
|
||||
"nomprenom": self.nomprenom or "",
|
||||
"lieu_naissance": self.lieu_naissance or "",
|
||||
"dept_naissance": self.dept_naissance or "",
|
||||
"nationalite": self.nationalite or "",
|
||||
"boursier": self.boursier or "",
|
||||
}
|
||||
if include_urls:
|
||||
d["fiche_url"] = url_for(
|
||||
"scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=self.id
|
||||
)
|
||||
d["photo_url"] = (sco_photos.get_etud_photo_url(self.id),)
|
||||
d["photo_url"] = sco_photos.get_etud_photo_url(self.id)
|
||||
adresse = self.adresses.first()
|
||||
if adresse:
|
||||
d.update(adresse.to_dict(convert_nulls_to_str=True))
|
||||
return d
|
||||
|
||||
def inscription_courante(self):
|
||||
|
@ -104,8 +198,36 @@ class Identite(db.Model):
|
|||
]
|
||||
return r[0] if r else None
|
||||
|
||||
def etat_inscription(self, formsemestre_id):
|
||||
"""etat de l'inscription de cet étudiant au semestre:
|
||||
def inscriptions_courantes(self) -> list: # -> list[FormSemestreInscription]:
|
||||
"""Liste des inscriptions à des semestres _courants_
|
||||
(il est rare qu'il y en ai plus d'une, mais c'est possible).
|
||||
Triées par date de début de semestre décroissante (le plus récent en premier).
|
||||
"""
|
||||
from app.models.formsemestre import FormSemestre, FormSemestreInscription
|
||||
|
||||
return (
|
||||
FormSemestreInscription.query.join(FormSemestreInscription.formsemestre)
|
||||
.filter(
|
||||
FormSemestreInscription.etudid == self.id,
|
||||
text("date_debut < now() and date_fin > now()"),
|
||||
)
|
||||
.order_by(desc(FormSemestre.date_debut))
|
||||
.all()
|
||||
)
|
||||
|
||||
def inscription_courante_date(self, date_debut, date_fin):
|
||||
"""La première inscription à un formsemestre incluant la
|
||||
période [date_debut, date_fin]
|
||||
"""
|
||||
r = [
|
||||
ins
|
||||
for ins in self.formsemestre_inscriptions
|
||||
if ins.formsemestre.contient_periode(date_debut, date_fin)
|
||||
]
|
||||
return r[0] if r else None
|
||||
|
||||
def inscription_etat(self, formsemestre_id):
|
||||
"""État de l'inscription de cet étudiant au semestre:
|
||||
False si pas inscrit, ou scu.INSCRIT, DEMISSION, DEF
|
||||
"""
|
||||
# voir si ce n'est pas trop lent:
|
||||
|
@ -116,6 +238,152 @@ class Identite(db.Model):
|
|||
return ins.etat
|
||||
return False
|
||||
|
||||
def inscription_descr(self) -> dict:
|
||||
"""Description de l'état d'inscription"""
|
||||
inscription_courante = self.inscription_courante()
|
||||
if inscription_courante:
|
||||
titre_sem = inscription_courante.formsemestre.titre_mois()
|
||||
return {
|
||||
"etat_in_cursem": inscription_courante.etat,
|
||||
"inscription_courante": inscription_courante,
|
||||
"inscription": titre_sem,
|
||||
"inscription_str": "Inscrit en " + titre_sem,
|
||||
"situation": self.descr_situation_etud(),
|
||||
}
|
||||
else:
|
||||
if self.formsemestre_inscriptions:
|
||||
# cherche l'inscription la plus récente:
|
||||
fin_dernier_sem = max(
|
||||
[
|
||||
inscr.formsemestre.date_debut
|
||||
for inscr in self.formsemestre_inscriptions
|
||||
]
|
||||
)
|
||||
if fin_dernier_sem > datetime.date.today():
|
||||
inscription = "futur"
|
||||
situation = "futur élève"
|
||||
else:
|
||||
inscription = "ancien"
|
||||
situation = "ancien élève"
|
||||
else:
|
||||
inscription = ("non inscrit",)
|
||||
situation = inscription
|
||||
return {
|
||||
"etat_in_cursem": "?",
|
||||
"inscription_courante": None,
|
||||
"inscription": inscription,
|
||||
"inscription_str": inscription,
|
||||
"situation": situation,
|
||||
}
|
||||
|
||||
def descr_situation_etud(self) -> str:
|
||||
"""Chaîne décrivant la situation _actuelle_ de l'étudiant.
|
||||
Exemple:
|
||||
"inscrit en BUT R&T semestre 2 FI (Jan 2022 - Jul 2022) le 16/01/2022"
|
||||
ou
|
||||
"non inscrit"
|
||||
"""
|
||||
inscriptions_courantes = self.inscriptions_courantes()
|
||||
if inscriptions_courantes:
|
||||
inscr = inscriptions_courantes[0]
|
||||
if inscr.etat == scu.INSCRIT:
|
||||
situation = f"inscrit{self.e} en {inscr.formsemestre.titre_mois()}"
|
||||
# Cherche la date d'inscription dans scolar_events:
|
||||
events = models.ScolarEvent.query.filter_by(
|
||||
etudid=self.id,
|
||||
formsemestre_id=inscr.formsemestre.id,
|
||||
event_type="INSCRIPTION",
|
||||
).all()
|
||||
if not events:
|
||||
log(
|
||||
f"*** situation inconsistante pour {self} (inscrit mais pas d'event)"
|
||||
)
|
||||
situation += " (inscription non enregistrée)" # ???
|
||||
else:
|
||||
date_ins = events[0].event_date
|
||||
situation += date_ins.strftime(" le %d/%m/%Y")
|
||||
else:
|
||||
situation = f"démission de {inscr.formsemestre.titre_mois()}"
|
||||
# Cherche la date de demission dans scolar_events:
|
||||
events = models.ScolarEvent.query.filter_by(
|
||||
etudid=self.id,
|
||||
formsemestre_id=inscr.formsemestre.id,
|
||||
event_type="DEMISSION",
|
||||
).all()
|
||||
if not events:
|
||||
log(
|
||||
f"*** situation inconsistante pour {self} (demission mais pas d'event)"
|
||||
)
|
||||
date_dem = "???" # ???
|
||||
else:
|
||||
date_dem = events[0].event_date
|
||||
situation += date_dem.strftime(" le %d/%m/%Y")
|
||||
else:
|
||||
situation = "non inscrit" + self.e
|
||||
|
||||
return situation
|
||||
|
||||
def photo_html(self, title=None, size="small") -> str:
|
||||
"""HTML img tag for the photo, either in small size (h90)
|
||||
or original size (size=="orig")
|
||||
"""
|
||||
from app.scodoc import sco_photos
|
||||
|
||||
# sco_photo traite des dicts:
|
||||
return sco_photos.etud_photo_html(
|
||||
etud=dict(
|
||||
etudid=self.id,
|
||||
code_nip=self.code_nip,
|
||||
nomprenom=self.nomprenom,
|
||||
nom_disp=self.nom_disp(),
|
||||
photo_filename=self.photo_filename,
|
||||
),
|
||||
title=title,
|
||||
size=size,
|
||||
)
|
||||
|
||||
|
||||
def make_etud_args(
|
||||
etudid=None, code_nip=None, use_request=True, raise_exc=False, abort_404=True
|
||||
) -> dict:
|
||||
"""forme args dict pour requete recherche etudiant
|
||||
On peut specifier etudid
|
||||
ou bien (si use_request) cherche dans la requete http: etudid, code_nip, code_ine
|
||||
(dans cet ordre).
|
||||
|
||||
Résultat: dict avec soit "etudid", soit "code_nip", soit "code_ine"
|
||||
"""
|
||||
args = None
|
||||
if etudid:
|
||||
try:
|
||||
args = {"etudid": int(etudid)}
|
||||
except ValueError as exc:
|
||||
raise ScoValueError("Adresse invalide") from exc
|
||||
elif code_nip:
|
||||
args = {"code_nip": code_nip}
|
||||
elif use_request: # use form from current request (Flask global)
|
||||
if request.method == "POST":
|
||||
vals = request.form
|
||||
elif request.method == "GET":
|
||||
vals = request.args
|
||||
else:
|
||||
vals = {}
|
||||
try:
|
||||
if "etudid" in vals:
|
||||
args = {"etudid": int(vals["etudid"])}
|
||||
elif "code_nip" in vals:
|
||||
args = {"code_nip": str(vals["code_nip"])}
|
||||
elif "code_ine" in vals:
|
||||
args = {"code_ine": str(vals["code_ine"])}
|
||||
except ValueError:
|
||||
args = {}
|
||||
if not args:
|
||||
if abort_404:
|
||||
abort(404, "pas d'étudiant sélectionné")
|
||||
elif raise_exc:
|
||||
raise ValueError("make_etud_args: pas d'étudiant sélectionné !")
|
||||
return args
|
||||
|
||||
|
||||
class Adresse(db.Model):
|
||||
"""Adresse d'un étudiant
|
||||
|
@ -144,6 +412,14 @@ class Adresse(db.Model):
|
|||
)
|
||||
description = db.Column(db.Text)
|
||||
|
||||
def to_dict(self, convert_nulls_to_str=False):
|
||||
"""Représentation dictionnaire,"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
if convert_nulls_to_str:
|
||||
return {k: e[k] or "" for k in e}
|
||||
return e
|
||||
|
||||
|
||||
class Admission(db.Model):
|
||||
"""Informations liées à l'admission d'un étudiant"""
|
||||
|
@ -193,6 +469,28 @@ class Admission(db.Model):
|
|||
# classement (1..Ngr) par le jury dans le groupe APB
|
||||
apb_classement_gr = db.Column(db.Integer)
|
||||
|
||||
def get_bac(self) -> Baccalaureat:
|
||||
"Le bac. utiliser bac.abbrev() pour avoir une chaine de caractères."
|
||||
return Baccalaureat(self.bac, specialite=self.specialite)
|
||||
|
||||
def to_dict(self, no_nulls=False):
|
||||
"""Représentation dictionnaire,"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
if no_nulls:
|
||||
for k in e:
|
||||
if e[k] is None:
|
||||
col_type = getattr(
|
||||
sqlalchemy.inspect(models.Admission).columns, "apb_groupe"
|
||||
).expression.type
|
||||
if isinstance(col_type, sqlalchemy.Text):
|
||||
e[k] = ""
|
||||
elif isinstance(col_type, sqlalchemy.Integer):
|
||||
e[k] = 0
|
||||
elif isinstance(col_type, sqlalchemy.Boolean):
|
||||
e[k] = False
|
||||
return e
|
||||
|
||||
|
||||
# Suivi scolarité / débouchés
|
||||
class ItemSuivi(db.Model):
|
||||
|
|
|
@ -2,12 +2,16 @@
|
|||
|
||||
"""ScoDoc models: evaluations
|
||||
"""
|
||||
import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import UniteEns
|
||||
from app.models import formsemestre
|
||||
from app.models.formsemestre import FormSemestre
|
||||
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
|
||||
from app.scodoc import sco_evaluation_db
|
||||
|
||||
|
||||
class Evaluation(db.Model):
|
||||
|
@ -51,11 +55,11 @@ class Evaluation(db.Model):
|
|||
e["evaluation_id"] = self.id
|
||||
e["jour"] = ndb.DateISOtoDMY(e["jour"])
|
||||
e["numero"] = ndb.int_null_is_zero(e["numero"])
|
||||
return sco_evaluation_db.evaluation_enrich_dict(e)
|
||||
return evaluation_enrich_dict(e)
|
||||
|
||||
def from_dict(self, data):
|
||||
"""Set evaluation attributes from given dict values."""
|
||||
sco_evaluation_db._check_evaluation_args(data)
|
||||
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])
|
||||
|
@ -145,3 +149,89 @@ class EvaluationUEPoids(db.Model):
|
|||
|
||||
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 fileds 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 heure_debut_dt < datetime.time(12, 00):
|
||||
e["matin"] = 1
|
||||
else:
|
||||
e["matin"] = 0
|
||||
if 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 !")
|
||||
|
|
|
@ -59,6 +59,10 @@ class Formation(db.Model):
|
|||
"""get l'instance de TypeParcours de cette formation"""
|
||||
return sco_codes_parcours.get_parcours_from_code(self.type_parcours)
|
||||
|
||||
def get_titre_version(self) -> str:
|
||||
"""Titre avec version"""
|
||||
return f"{self.acronyme} {self.titre} v{self.version}"
|
||||
|
||||
def is_apc(self):
|
||||
"True si formation APC avec SAE (BUT)"
|
||||
return self.get_parcours().APC_SAE
|
||||
|
@ -161,3 +165,16 @@ class Matiere(db.Model):
|
|||
numero = db.Column(db.Integer) # ordre de présentation
|
||||
|
||||
modules = db.relationship("Module", lazy="dynamic", backref="matiere")
|
||||
|
||||
def __repr__(self):
|
||||
return f"""<{self.__class__.__name__}(id={self.id}, ue_id={
|
||||
self.ue_id}, titre='{self.titre}')>"""
|
||||
|
||||
def to_dict(self):
|
||||
"""as a dict, with the same conversions as in ScoDoc7"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
# ScoDoc7 output_formators
|
||||
e["ue_id"] = self.id
|
||||
e["numero"] = e["numero"] if e["numero"] else 0
|
||||
return e
|
||||
|
|
|
@ -3,14 +3,15 @@
|
|||
"""ScoDoc models: formsemestre
|
||||
"""
|
||||
import datetime
|
||||
from functools import cached_property
|
||||
|
||||
import flask_sqlalchemy
|
||||
|
||||
from app import db
|
||||
from app import log
|
||||
from app.models import APO_CODE_STR_LEN
|
||||
from app.models import SHORT_STR_LEN
|
||||
from app.models import CODE_STR_LEN
|
||||
from app.models import UniteEns
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.models.ues import UniteEns
|
||||
|
@ -20,6 +21,8 @@ from app.models.etudiants import Identite
|
|||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.sco_vdi import ApoEtapeVDI
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
from app.scodoc.sco_utils import MONTH_NAMES_ABBREV
|
||||
|
||||
|
||||
class FormSemestre(db.Model):
|
||||
|
@ -47,7 +50,7 @@ class FormSemestre(db.Model):
|
|||
gestion_compensation = db.Column(
|
||||
db.Boolean(), nullable=False, default=False, server_default="false"
|
||||
)
|
||||
# ne publie pas le bulletin XML:
|
||||
# ne publie pas le bulletin XML ou JSON:
|
||||
bul_hide_xml = db.Column(
|
||||
db.Boolean(), nullable=False, default=False, server_default="false"
|
||||
)
|
||||
|
@ -84,7 +87,11 @@ class FormSemestre(db.Model):
|
|||
etapes = db.relationship(
|
||||
"FormSemestreEtape", cascade="all,delete", backref="formsemestre"
|
||||
)
|
||||
modimpls = db.relationship("ModuleImpl", backref="formsemestre", lazy="dynamic")
|
||||
modimpls = db.relationship(
|
||||
"ModuleImpl",
|
||||
backref="formsemestre",
|
||||
lazy="dynamic",
|
||||
)
|
||||
etuds = db.relationship(
|
||||
"Identite",
|
||||
secondary="notes_formsemestre_inscription",
|
||||
|
@ -97,6 +104,11 @@ class FormSemestre(db.Model):
|
|||
lazy=True,
|
||||
backref=db.backref("formsemestres", lazy=True),
|
||||
)
|
||||
partitions = db.relationship(
|
||||
"Partition",
|
||||
backref=db.backref("formsemestre", lazy=True),
|
||||
lazy="dynamic",
|
||||
)
|
||||
# Ancien id ScoDoc7 pour les migrations de bases anciennes
|
||||
# ne pas utiliser après migrate_scodoc7_dept_archives
|
||||
scodoc7_id = db.Column(db.Text(), nullable=True)
|
||||
|
@ -106,18 +118,63 @@ class FormSemestre(db.Model):
|
|||
if self.modalite is None:
|
||||
self.modalite = FormationModalite.DEFAULT_MODALITE
|
||||
|
||||
def __repr__(self):
|
||||
return f"<{self.__class__.__name__} {self.id} {self.titre_num()}>"
|
||||
|
||||
def to_dict(self):
|
||||
"dict (compatible ScoDoc7)"
|
||||
d = dict(self.__dict__)
|
||||
d.pop("_sa_instance_state", None)
|
||||
# ScoDoc7 output_formators: (backward compat)
|
||||
d["formsemestre_id"] = self.id
|
||||
d["date_debut"] = (
|
||||
self.date_debut.strftime("%d/%m/%Y") if self.date_debut else ""
|
||||
)
|
||||
d["date_fin"] = self.date_fin.strftime("%d/%m/%Y") if self.date_fin else ""
|
||||
d["titre_num"] = self.titre_num()
|
||||
if self.date_debut:
|
||||
d["date_debut"] = self.date_debut.strftime("%d/%m/%Y")
|
||||
d["date_debut_iso"] = self.date_debut.isoformat()
|
||||
else:
|
||||
d["date_debut"] = d["date_debut_iso"] = ""
|
||||
if self.date_fin:
|
||||
d["date_fin"] = self.date_fin.strftime("%d/%m/%Y")
|
||||
d["date_fin_iso"] = self.date_fin.isoformat()
|
||||
else:
|
||||
d["date_fin"] = d["date_fin_iso"] = ""
|
||||
d["responsables"] = [u.id for u in self.responsables]
|
||||
return d
|
||||
|
||||
def get_infos_dict(self) -> dict:
|
||||
"""Un dict avec des informations sur le semestre
|
||||
pour les bulletins et autres templates
|
||||
(contenu compatible scodoc7 / anciens templates)
|
||||
"""
|
||||
d = self.to_dict()
|
||||
d["anneescolaire"] = self.annee_scolaire_str()
|
||||
d["annee_debut"] = str(self.date_debut.year)
|
||||
d["annee"] = d["annee_debut"]
|
||||
d["annee_fin"] = str(self.date_fin.year)
|
||||
if d["annee_fin"] != d["annee_debut"]:
|
||||
d["annee"] += "-" + str(d["annee_fin"])
|
||||
d["mois_debut_ord"] = self.date_debut.month
|
||||
d["mois_fin_ord"] = self.date_fin.month
|
||||
# La période: considère comme "S1" (ou S3) les débuts en aout-sept-octobre
|
||||
# devrait sans doute pouvoir etre changé...
|
||||
if self.date_debut.month >= 8 and self.date_debut.month <= 10:
|
||||
d["periode"] = 1 # typiquement, début en septembre: S1, S3...
|
||||
else:
|
||||
d["periode"] = 2 # typiquement, début en février: S2, S4...
|
||||
d["titreannee"] = self.titre_annee()
|
||||
d["mois_debut"] = self.mois_debut()
|
||||
d["mois_fin"] = self.mois_fin()
|
||||
d["titremois"] = "%s %s (%s - %s)" % (
|
||||
d["titre_num"],
|
||||
self.modalite or "",
|
||||
d["mois_debut"],
|
||||
d["mois_fin"],
|
||||
)
|
||||
d["session_id"] = self.session_id()
|
||||
d["etapes"] = self.etapes_apo_vdi()
|
||||
d["etapes_apo_str"] = self.etapes_apo_str()
|
||||
return d
|
||||
|
||||
def query_ues(self, with_sport=False) -> flask_sqlalchemy.BaseQuery:
|
||||
"""UE des modules de ce semestre, triées par numéro.
|
||||
- Formations classiques: les UEs auxquelles appartiennent
|
||||
|
@ -139,6 +196,42 @@ class FormSemestre(db.Model):
|
|||
sem_ues = sem_ues.filter(UniteEns.type != sco_codes_parcours.UE_SPORT)
|
||||
return sem_ues.order_by(UniteEns.numero)
|
||||
|
||||
@cached_property
|
||||
def modimpls_sorted(self) -> list[ModuleImpl]:
|
||||
"""Liste des modimpls du semestre (y compris bonus)
|
||||
- triée par type/numéro/code en APC
|
||||
- triée par numéros d'UE/matières/modules pour les formations standard.
|
||||
"""
|
||||
modimpls = self.modimpls.all()
|
||||
if self.formation.is_apc():
|
||||
modimpls.sort(
|
||||
key=lambda m: (
|
||||
m.module.module_type or 0,
|
||||
m.module.numero or 0,
|
||||
m.module.code or 0,
|
||||
)
|
||||
)
|
||||
else:
|
||||
modimpls.sort(
|
||||
key=lambda m: (
|
||||
m.module.ue.numero or 0,
|
||||
m.module.matiere.numero or 0,
|
||||
m.module.numero or 0,
|
||||
m.module.code or "",
|
||||
)
|
||||
)
|
||||
return modimpls
|
||||
|
||||
def can_be_edited_by(self, user):
|
||||
"""Vrai si user peut modifier ce semestre"""
|
||||
if not user.has_permission(Permission.ScoImplement): # pas chef
|
||||
if not self.resp_can_edit or user.id not in [
|
||||
resp.id for resp in self.responsables
|
||||
]:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def est_courant(self) -> bool:
|
||||
"""Vrai si la date actuelle (now) est dans le semestre
|
||||
(les dates de début et fin sont incluses)
|
||||
|
@ -146,6 +239,31 @@ class FormSemestre(db.Model):
|
|||
today = datetime.date.today()
|
||||
return (self.date_debut <= today) and (today <= self.date_fin)
|
||||
|
||||
def contient_periode(self, date_debut, date_fin) -> bool:
|
||||
"""Vrai si l'intervalle [date_debut, date_fin] est
|
||||
inclus dans le semestre.
|
||||
(les dates de début et fin sont incluses)
|
||||
"""
|
||||
return (self.date_debut <= date_debut) and (date_fin <= self.date_fin)
|
||||
|
||||
def est_sur_une_annee(self):
|
||||
"""Test si sem est entièrement sur la même année scolaire.
|
||||
(ce n'est pas obligatoire mais si ce n'est pas le
|
||||
cas les exports Apogée risquent de mal fonctionner)
|
||||
Pivot au 1er août.
|
||||
"""
|
||||
if self.date_debut > self.date_fin:
|
||||
log(f"Warning: semestre {self.id} begins after ending !")
|
||||
annee_debut = self.date_debut.year
|
||||
if self.date_debut.month < 8: # août
|
||||
# considere que debut sur l'anne scolaire precedente
|
||||
annee_debut -= 1
|
||||
annee_fin = self.date_fin.year
|
||||
if self.date_fin.month < 9:
|
||||
# 9 (sept) pour autoriser un début en sept et une fin en aout
|
||||
annee_fin -= 1
|
||||
return annee_debut == annee_fin
|
||||
|
||||
def est_decale(self):
|
||||
"""Vrai si semestre "décalé"
|
||||
c'est à dire semestres impairs commençant entre janvier et juin
|
||||
|
@ -157,6 +275,11 @@ class FormSemestre(db.Model):
|
|||
not self.semestre_id % 2 and self.date_debut.month > 6
|
||||
)
|
||||
|
||||
def etapes_apo_vdi(self) -> list[ApoEtapeVDI]:
|
||||
"Liste des vdis"
|
||||
# was read_formsemestre_etapes
|
||||
return [e.as_apovdi() for e in self.etapes if e.etape_apo]
|
||||
|
||||
def etapes_apo_str(self) -> str:
|
||||
"""Chaine décrivant les étapes de ce semestre
|
||||
ex: "V1RT, V1RT3, V1RT4"
|
||||
|
@ -169,6 +292,7 @@ class FormSemestre(db.Model):
|
|||
"""chaîne "J. Dupond, X. Martin"
|
||||
ou "Jacques Dupond, Xavier Martin"
|
||||
"""
|
||||
# was "nomcomplet"
|
||||
if not self.responsables:
|
||||
return ""
|
||||
if abbrev_prenom:
|
||||
|
@ -176,10 +300,22 @@ class FormSemestre(db.Model):
|
|||
else:
|
||||
return ", ".join([u.get_nomcomplet() for u in self.responsables])
|
||||
|
||||
def est_responsable(self, user):
|
||||
"True si l'user est l'un des responsables du semestre"
|
||||
return user.id in [u.id for u in self.responsables]
|
||||
|
||||
def annee_scolaire_str(self):
|
||||
"2021 - 2022"
|
||||
return scu.annee_scolaire_repr(self.date_debut.year, self.date_debut.month)
|
||||
|
||||
def mois_debut(self) -> str:
|
||||
"Oct 2021"
|
||||
return f"{MONTH_NAMES_ABBREV[self.date_debut.month - 1]} {self.date_debut.year}"
|
||||
|
||||
def mois_fin(self) -> str:
|
||||
"Jul 2022"
|
||||
return f"{MONTH_NAMES_ABBREV[self.date_fin.month - 1]} {self.date_fin.year}"
|
||||
|
||||
def session_id(self) -> str:
|
||||
"""identifiant externe de semestre de formation
|
||||
Exemple: RT-DUT-FI-S1-ANNEE
|
||||
|
@ -213,6 +349,15 @@ class FormSemestre(db.Model):
|
|||
"-".join((imputation_dept, parcours_name, modalite, semestre_id, annee_sco))
|
||||
)
|
||||
|
||||
def titre_annee(self) -> str:
|
||||
""" """
|
||||
titre_annee = (
|
||||
f"{self.titre_num()} {self.modalite or ''} {self.date_debut.year}"
|
||||
)
|
||||
if self.date_fin.year != self.date_debut.year:
|
||||
titre_annee += "-" + str(self.date_fin.year)
|
||||
return titre_annee
|
||||
|
||||
def titre_mois(self) -> str:
|
||||
"""Le titre et les dates du semestre, pour affichage dans des listes
|
||||
Ex: "BUT QLIO (PN 2022) semestre 1 FI (Sept 2022 - Jan 2023)"
|
||||
|
@ -231,7 +376,7 @@ class FormSemestre(db.Model):
|
|||
|
||||
def get_abs_count(self, etudid):
|
||||
"""Les comptes d'absences de cet étudiant dans ce semestre:
|
||||
tuple (nb abs non justifiées, nb abs justifiées)
|
||||
tuple (nb abs, nb abs justifiées)
|
||||
Utilise un cache.
|
||||
"""
|
||||
from app.scodoc import sco_abs
|
||||
|
@ -240,14 +385,29 @@ class FormSemestre(db.Model):
|
|||
etudid, self.date_debut.isoformat(), self.date_fin.isoformat()
|
||||
)
|
||||
|
||||
def get_inscrits(self, include_dem=False) -> list:
|
||||
def get_inscrits(self, include_demdef=False, order=False) -> list[Identite]:
|
||||
"""Liste des étudiants inscrits à ce semestre
|
||||
Si all, tous les étudiants, avec les démissionnaires.
|
||||
Si include_demdef, tous les étudiants, avec les démissionnaires
|
||||
et défaillants.
|
||||
Si order, tri par clé sort_key
|
||||
"""
|
||||
if include_dem:
|
||||
return [ins.etud for ins in self.inscriptions]
|
||||
if include_demdef:
|
||||
etuds = [ins.etud for ins in self.inscriptions]
|
||||
else:
|
||||
return [ins.etud for ins in self.inscriptions if ins.etat == scu.INSCRIT]
|
||||
etuds = [ins.etud for ins in self.inscriptions if ins.etat == scu.INSCRIT]
|
||||
if order:
|
||||
etuds.sort(key=lambda e: e.sort_key)
|
||||
return etuds
|
||||
|
||||
@cached_property
|
||||
def etudids_actifs(self) -> set:
|
||||
"Set des etudids inscrits non démissionnaires et non défaillants"
|
||||
return {ins.etudid for ins in self.inscriptions if ins.etat == scu.INSCRIT}
|
||||
|
||||
@cached_property
|
||||
def etuds_inscriptions(self) -> dict:
|
||||
"""Map { etudid : inscription } (incluant DEM et DEF)"""
|
||||
return {ins.etud.id: ins for ins in self.inscriptions}
|
||||
|
||||
|
||||
# Association id des utilisateurs responsables (aka directeurs des etudes) du semestre
|
||||
|
@ -342,16 +502,18 @@ class FormSemestreUECoef(db.Model):
|
|||
formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
index=True,
|
||||
)
|
||||
ue_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_ue.id"),
|
||||
index=True,
|
||||
)
|
||||
coefficient = db.Column(db.Float, nullable=False)
|
||||
|
||||
|
||||
class FormSemestreUEComputationExpr(db.Model):
|
||||
"""Formules utilisateurs pour calcul moyenne UE"""
|
||||
"""Formules utilisateurs pour calcul moyenne UE (désactivées en 9.2+)."""
|
||||
|
||||
__tablename__ = "notes_formsemestre_ue_computation_expr"
|
||||
__table_args__ = (db.UniqueConstraint("formsemestre_id", "ue_id"),)
|
||||
|
@ -418,6 +580,9 @@ class FormSemestreInscription(db.Model):
|
|||
# etape apogee d'inscription (experimental 2020)
|
||||
etape = db.Column(db.String(APO_CODE_STR_LEN))
|
||||
|
||||
def __repr__(self):
|
||||
return f"<{self.__class__.__name__} {self.id} etudid={self.etudid} sem={self.formsemestre_id} etat={self.etat}>"
|
||||
|
||||
|
||||
class NotesSemSet(db.Model):
|
||||
"""semsets: ensemble de formsemestres pour exports Apogée"""
|
||||
|
|
|
@ -31,6 +31,11 @@ class Partition(db.Model):
|
|||
show_in_lists = db.Column(
|
||||
db.Boolean(), nullable=False, default=True, server_default="true"
|
||||
)
|
||||
groups = db.relationship(
|
||||
"GroupDescr",
|
||||
backref=db.backref("partition", lazy=True),
|
||||
lazy="dynamic",
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(Partition, self).__init__(**kwargs)
|
||||
|
@ -42,6 +47,9 @@ class Partition(db.Model):
|
|||
else:
|
||||
self.numero = 1
|
||||
|
||||
def __repr__(self):
|
||||
return f"""<{self.__class__.__name__} {self.id} "{self.partition_name or '(default)'}">"""
|
||||
|
||||
|
||||
class GroupDescr(db.Model):
|
||||
"""Description d'un groupe d'une partition"""
|
||||
|
@ -55,6 +63,17 @@ class GroupDescr(db.Model):
|
|||
# "A", "C2", ... (NULL for 'all'):
|
||||
group_name = db.Column(db.String(GROUPNAME_STR_LEN))
|
||||
|
||||
etuds = db.relationship(
|
||||
"Identite",
|
||||
secondary="group_membership",
|
||||
lazy="dynamic",
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
f"""<{self.__class__.__name__} {self.id} "{self.group_name or '(tous)'}">"""
|
||||
)
|
||||
|
||||
|
||||
group_membership = db.Table(
|
||||
"group_membership",
|
||||
|
|
|
@ -2,10 +2,12 @@
|
|||
"""ScoDoc models: moduleimpls
|
||||
"""
|
||||
import pandas as pd
|
||||
import flask_sqlalchemy
|
||||
|
||||
from app import db
|
||||
from app.comp import df_cache
|
||||
from app.models import UniteEns, Identite
|
||||
from app.models.etudiants import Identite
|
||||
from app.models.modules import Module
|
||||
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app.scodoc import sco_utils as scu
|
||||
|
@ -53,7 +55,7 @@ class ModuleImpl(db.Model):
|
|||
if evaluations_poids is None:
|
||||
from app.comp import moy_mod
|
||||
|
||||
evaluations_poids, _ = moy_mod.df_load_evaluations_poids(self.id)
|
||||
evaluations_poids, _ = moy_mod.load_evaluations_poids(self.id)
|
||||
df_cache.EvaluationsPoidsCache.set(self.id, evaluations_poids)
|
||||
return evaluations_poids
|
||||
|
||||
|
@ -72,14 +74,14 @@ class ModuleImpl(db.Model):
|
|||
return True
|
||||
from app.comp import moy_mod
|
||||
|
||||
return moy_mod.check_moduleimpl_conformity(
|
||||
return moy_mod.moduleimpl_is_conforme(
|
||||
self,
|
||||
self.get_evaluations_poids(),
|
||||
self.module.formation.get_module_coefs(self.module.semestre_id),
|
||||
)
|
||||
|
||||
def to_dict(self):
|
||||
"""as a dict, with the same conversions as in ScoDoc7"""
|
||||
"""as a dict, with the same conversions as in ScoDoc7, including module"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
# ScoDoc7 output_formators: (backward compat)
|
||||
|
@ -127,3 +129,40 @@ class ModuleImplInscription(db.Model):
|
|||
ModuleImpl,
|
||||
backref=db.backref("inscriptions", cascade="all, delete-orphan"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def etud_modimpls_in_ue(
|
||||
cls, formsemestre_id: int, etudid: int, ue_id: int
|
||||
) -> flask_sqlalchemy.BaseQuery:
|
||||
"""moduleimpls de l'UE auxquels l'étudiant est inscrit.
|
||||
(Attention: inutile en APC, il faut considérer les coefficients)
|
||||
"""
|
||||
return ModuleImplInscription.query.filter(
|
||||
ModuleImplInscription.etudid == etudid,
|
||||
ModuleImplInscription.moduleimpl_id == ModuleImpl.id,
|
||||
ModuleImpl.formsemestre_id == formsemestre_id,
|
||||
ModuleImpl.module_id == Module.id,
|
||||
Module.ue_id == ue_id,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def nb_inscriptions_dans_ue(
|
||||
cls, formsemestre_id: int, etudid: int, ue_id: int
|
||||
) -> int:
|
||||
"""Nombre de moduleimpls de l'UE auxquels l'étudiant est inscrit"""
|
||||
return cls.etud_modimpls_in_ue(formsemestre_id, etudid, ue_id).count()
|
||||
|
||||
@classmethod
|
||||
def sum_coefs_modimpl_ue(
|
||||
cls, formsemestre_id: int, etudid: int, ue_id: int
|
||||
) -> float:
|
||||
"""Somme des coefficients des modules auxquels l'étudiant est inscrit
|
||||
dans l'UE du semestre indiqué.
|
||||
N'utilise que les coefficients, donc inadapté aux formations APC.
|
||||
"""
|
||||
return sum(
|
||||
[
|
||||
inscr.modimpl.module.coefficient
|
||||
for inscr in cls.etud_modimpls_in_ue(formsemestre_id, etudid, ue_id)
|
||||
]
|
||||
)
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
from app import db
|
||||
from app.models import APO_CODE_STR_LEN
|
||||
from app.scodoc import sco_utils as scu
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
||||
|
||||
|
@ -32,8 +33,8 @@ class Module(db.Model):
|
|||
numero = db.Column(db.Integer) # ordre de présentation
|
||||
# id de l'element pedagogique Apogee correspondant:
|
||||
code_apogee = db.Column(db.String(APO_CODE_STR_LEN))
|
||||
# Type: ModuleType: DEFAULT, MALUS, RESSOURCE, MODULE_SAE (enum)
|
||||
module_type = db.Column(db.Integer)
|
||||
# Type: ModuleType.STANDARD, MALUS, RESSOURCE, SAE (enum)
|
||||
module_type = db.Column(db.Integer, nullable=False, default=0, server_default="0")
|
||||
# Relations:
|
||||
modimpls = db.relationship("ModuleImpl", backref="module", lazy="dynamic")
|
||||
ues_apc = db.relationship("UniteEns", secondary="module_ue_coef", viewonly=True)
|
||||
|
@ -62,6 +63,7 @@ class Module(db.Model):
|
|||
e["numero"] = 0 if self.numero is None else self.numero
|
||||
e["coefficient"] = 0.0 if self.coefficient is None else self.coefficient
|
||||
e["module_type"] = 0 if self.module_type is None else self.module_type
|
||||
e["code_apogee"] = e["code_apogee"] or "" # pas de None
|
||||
return e
|
||||
|
||||
def is_apc(self):
|
||||
|
@ -74,6 +76,11 @@ class Module(db.Model):
|
|||
def type_name(self):
|
||||
return scu.MODULE_TYPE_NAMES[self.module_type]
|
||||
|
||||
def type_abbrv(self):
|
||||
""" "mod", "malus", "res", "sae"
|
||||
(utilisées pour style css)"""
|
||||
return scu.ModuleType.get_abbrev(self.module_type)
|
||||
|
||||
def set_ue_coef(self, ue, coef: float) -> None:
|
||||
"""Set coef module vers cette UE"""
|
||||
self.update_ue_coef_dict({ue.id: coef})
|
||||
|
@ -129,9 +136,29 @@ class Module(db.Model):
|
|||
# à redéfinir les relationships...
|
||||
return sorted(self.ue_coefs, key=lambda x: x.ue.numero)
|
||||
|
||||
def ue_coefs_descr(self):
|
||||
"""List of tuples [ (ue_acronyme, coef) ]"""
|
||||
return [(c.ue.acronyme, c.coef) for c in self.get_ue_coefs_sorted()]
|
||||
def ue_coefs_list(self, include_zeros=True):
|
||||
"""Liste des coefs vers les UE (pour les modules APC).
|
||||
Si include_zeros, liste aussi les UE sans coef (donc nul) de ce semestre,
|
||||
sauf UE bonus sport.
|
||||
Result: List of tuples [ (ue, coef) ]
|
||||
"""
|
||||
if not self.is_apc():
|
||||
return []
|
||||
if include_zeros:
|
||||
# Toutes les UE du même semestre:
|
||||
ues_semestre = (
|
||||
self.formation.ues.filter_by(semestre_idx=self.ue.semestre_idx)
|
||||
.filter(UniteEns.type != UE_SPORT)
|
||||
.order_by(UniteEns.numero)
|
||||
.all()
|
||||
)
|
||||
coefs_dict = self.get_ue_coef_dict()
|
||||
coefs_list = []
|
||||
for ue in ues_semestre:
|
||||
coefs_list.append((ue, coefs_dict.get(ue.id, 0.0)))
|
||||
return coefs_list
|
||||
# Liste seulement les coefs définis:
|
||||
return [(c.ue, c.coef) for c in self.get_ue_coefs_sorted()]
|
||||
|
||||
|
||||
class ModuleUECoef(db.Model):
|
||||
|
|
|
@ -4,102 +4,9 @@
|
|||
"""
|
||||
|
||||
from app import db
|
||||
from app.models import SHORT_STR_LEN
|
||||
from app.models import CODE_STR_LEN
|
||||
|
||||
|
||||
class ScolarEvent(db.Model):
|
||||
"""Evenement dans le parcours scolaire d'un étudiant"""
|
||||
|
||||
__tablename__ = "scolar_events"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
event_id = db.synonym("id")
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
)
|
||||
event_date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
ue_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_ue.id"),
|
||||
)
|
||||
# 'CREATION', 'INSCRIPTION', 'DEMISSION',
|
||||
# 'AUT_RED', 'EXCLUS', 'VALID_UE', 'VALID_SEM'
|
||||
# 'ECHEC_SEM'
|
||||
# 'UTIL_COMPENSATION'
|
||||
event_type = db.Column(db.String(SHORT_STR_LEN))
|
||||
# Semestre compensé par formsemestre_id:
|
||||
comp_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
|
||||
|
||||
class ScolarFormSemestreValidation(db.Model):
|
||||
"""Décisions de jury"""
|
||||
|
||||
__tablename__ = "scolar_formsemestre_validation"
|
||||
# Assure unicité de la décision:
|
||||
__table_args__ = (db.UniqueConstraint("etudid", "formsemestre_id", "ue_id"),)
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
formsemestre_validation_id = db.synonym("id")
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
index=True,
|
||||
)
|
||||
formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
index=True,
|
||||
)
|
||||
ue_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_ue.id"),
|
||||
index=True,
|
||||
)
|
||||
code = db.Column(db.String(CODE_STR_LEN), nullable=False, index=True)
|
||||
# NULL pour les UE, True|False pour les semestres:
|
||||
assidu = db.Column(db.Boolean)
|
||||
event_date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
# NULL sauf si compense un semestre:
|
||||
compense_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
moy_ue = db.Column(db.Float)
|
||||
# (normalement NULL) indice du semestre, utile seulement pour
|
||||
# UE "antérieures" et si la formation définit des UE utilisées
|
||||
# dans plusieurs semestres (cas R&T IUTV v2)
|
||||
semestre_id = db.Column(db.Integer)
|
||||
# Si UE validée dans le cursus d'un autre etablissement
|
||||
is_external = db.Column(db.Boolean, default=False, server_default="false")
|
||||
|
||||
|
||||
class ScolarAutorisationInscription(db.Model):
|
||||
"""Autorisation d'inscription dans un semestre"""
|
||||
|
||||
__tablename__ = "scolar_autorisation_inscription"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
autorisation_inscription_id = db.synonym("id")
|
||||
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
)
|
||||
formation_code = db.Column(db.String(SHORT_STR_LEN), nullable=False)
|
||||
# semestre ou on peut s'inscrire:
|
||||
semestre_id = db.Column(db.Integer)
|
||||
date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
origin_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
import app.scodoc.notesdb as ndb
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
|
||||
class BulAppreciations(db.Model):
|
||||
|
@ -161,3 +68,29 @@ class NotesNotesLog(db.Model):
|
|||
comment = db.Column(db.Text) # texte libre
|
||||
date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
uid = db.Column(db.Integer, db.ForeignKey("user.id"))
|
||||
|
||||
|
||||
def etud_has_notes_attente(etudid, formsemestre_id):
|
||||
"""Vrai si cet etudiant a au moins une note en attente dans ce semestre.
|
||||
(ne compte que les notes en attente dans des évaluations avec coef. non nul).
|
||||
"""
|
||||
cursor = db.session.execute(
|
||||
"""SELECT COUNT(*)
|
||||
FROM notes_notes n, notes_evaluation e, notes_moduleimpl m,
|
||||
notes_moduleimpl_inscription i
|
||||
WHERE n.etudid = :etudid
|
||||
and n.value = :code_attente
|
||||
and n.evaluation_id = e.id
|
||||
and e.moduleimpl_id = m.id
|
||||
and m.formsemestre_id = :formsemestre_id
|
||||
and e.coefficient != 0
|
||||
and m.id = i.moduleimpl_id
|
||||
and i.etudid = :etudid
|
||||
""",
|
||||
{
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"code_attente": scu.NOTES_ATTENTE,
|
||||
},
|
||||
)
|
||||
return cursor.fetchone()[0] > 0
|
||||
|
|
|
@ -4,7 +4,6 @@
|
|||
from app import db
|
||||
from app.models import APO_CODE_STR_LEN
|
||||
from app.models import SHORT_STR_LEN
|
||||
from app.scodoc import notesdb as ndb
|
||||
from app.scodoc import sco_utils as scu
|
||||
|
||||
|
||||
|
@ -41,6 +40,8 @@ class UniteEns(db.Model):
|
|||
# coef UE, utilise seulement si l'option use_ue_coefs est activée:
|
||||
coefficient = db.Column(db.Float)
|
||||
|
||||
color = db.Column(db.Text())
|
||||
|
||||
# relations
|
||||
matieres = db.relationship("Matiere", lazy="dynamic", backref="ue")
|
||||
modules = db.relationship("Module", lazy="dynamic", backref="ue")
|
||||
|
@ -52,14 +53,17 @@ class UniteEns(db.Model):
|
|||
'EXTERNE' if self.is_external else ''})>"""
|
||||
|
||||
def to_dict(self):
|
||||
"""as a dict, with the same conversions as in ScoDoc7"""
|
||||
"""as a dict, with the same conversions as in ScoDoc7
|
||||
(except ECTS: keep None)
|
||||
"""
|
||||
e = dict(self.__dict__)
|
||||
e.pop("_sa_instance_state", None)
|
||||
# ScoDoc7 output_formators
|
||||
e["ue_id"] = self.id
|
||||
e["numero"] = e["numero"] if e["numero"] else 0
|
||||
e["ects"] = e["ects"] if e["ects"] else 0.0
|
||||
e["ects"] = e["ects"]
|
||||
e["coefficient"] = e["coefficient"] if e["coefficient"] else 0.0
|
||||
e["code_apogee"] = e["code_apogee"] or "" # pas de None
|
||||
return e
|
||||
|
||||
def is_locked(self):
|
||||
|
|
|
@ -0,0 +1,109 @@
|
|||
# -*- coding: UTF-8 -*
|
||||
|
||||
"""Notes, décisions de jury, évènements scolaires
|
||||
"""
|
||||
|
||||
from app import db
|
||||
from app.models import SHORT_STR_LEN
|
||||
from app.models import CODE_STR_LEN
|
||||
|
||||
|
||||
class ScolarFormSemestreValidation(db.Model):
|
||||
"""Décisions de jury"""
|
||||
|
||||
__tablename__ = "scolar_formsemestre_validation"
|
||||
# Assure unicité de la décision:
|
||||
__table_args__ = (db.UniqueConstraint("etudid", "formsemestre_id", "ue_id"),)
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
formsemestre_validation_id = db.synonym("id")
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
index=True,
|
||||
)
|
||||
formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
index=True,
|
||||
)
|
||||
ue_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_ue.id"),
|
||||
index=True,
|
||||
)
|
||||
code = db.Column(db.String(CODE_STR_LEN), nullable=False, index=True)
|
||||
# NULL pour les UE, True|False pour les semestres:
|
||||
assidu = db.Column(db.Boolean)
|
||||
event_date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
# NULL sauf si compense un semestre:
|
||||
compense_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
moy_ue = db.Column(db.Float)
|
||||
# (normalement NULL) indice du semestre, utile seulement pour
|
||||
# UE "antérieures" et si la formation définit des UE utilisées
|
||||
# dans plusieurs semestres (cas R&T IUTV v2)
|
||||
semestre_id = db.Column(db.Integer)
|
||||
# Si UE validée dans le cursus d'un autre etablissement
|
||||
is_external = db.Column(
|
||||
db.Boolean, default=False, server_default="false", index=True
|
||||
)
|
||||
|
||||
ue = db.relationship("UniteEns", lazy="select", uselist=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f"{self.__class__.__name__}({self.formsemestre_id}, {self.etudid}, code={self.code}, ue={self.ue_id}, moy_ue={self.moy_ue})"
|
||||
|
||||
|
||||
class ScolarAutorisationInscription(db.Model):
|
||||
"""Autorisation d'inscription dans un semestre"""
|
||||
|
||||
__tablename__ = "scolar_autorisation_inscription"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
autorisation_inscription_id = db.synonym("id")
|
||||
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
)
|
||||
formation_code = db.Column(db.String(SHORT_STR_LEN), nullable=False)
|
||||
# semestre ou on peut s'inscrire:
|
||||
semestre_id = db.Column(db.Integer)
|
||||
date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
origin_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
|
||||
|
||||
class ScolarEvent(db.Model):
|
||||
"""Evenement dans le parcours scolaire d'un étudiant"""
|
||||
|
||||
__tablename__ = "scolar_events"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
event_id = db.synonym("id")
|
||||
etudid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("identite.id"),
|
||||
)
|
||||
event_date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
|
||||
formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
||||
ue_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_ue.id"),
|
||||
)
|
||||
# 'CREATION', 'INSCRIPTION', 'DEMISSION',
|
||||
# 'AUT_RED', 'EXCLUS', 'VALID_UE', 'VALID_SEM'
|
||||
# 'ECHEC_SEM'
|
||||
# 'UTIL_COMPENSATION'
|
||||
event_type = db.Column(db.String(SHORT_STR_LEN))
|
||||
# Semestre compensé par formsemestre_id:
|
||||
comp_formsemestre_id = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey("notes_formsemestre.id"),
|
||||
)
|
|
@ -0,0 +1 @@
|
|||
# empty but required for pylint
|
|
@ -87,7 +87,7 @@ def get_tags_latex(code_latex):
|
|||
"""
|
||||
if code_latex:
|
||||
# changé par EV: était r"([\*]{2}[a-zA-Z0-9:éèàâêëïôöù]+[\*]{2})"
|
||||
res = re.findall(r"([\*]{2}[^ \t\n\r\f\v\*]+[\*]{2})", code_latex)
|
||||
res = re.findall(r"([\*]{2}[^\t\n\r\f\v\*]+[\*]{2})", code_latex)
|
||||
return [tag[2:-2] for tag in res]
|
||||
else:
|
||||
return []
|
||||
|
|
|
@ -46,9 +46,12 @@ import io
|
|||
import os
|
||||
from zipfile import ZipFile
|
||||
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import FormSemestre
|
||||
|
||||
from app.scodoc.gen_tables import GenTable, SeqGenTable
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_codes_parcours # sco_codes_parcours.NEXT -> sem suivant
|
||||
from app.scodoc import sco_etud
|
||||
from app.scodoc import sco_formsemestre
|
||||
|
@ -174,6 +177,8 @@ class JuryPE(object):
|
|||
self.PARCOURSINFO_DICT = {} # Les parcours des étudiants
|
||||
self.syntheseJury = {} # Le jury de synthèse
|
||||
|
||||
self.semestresDeScoDoc = sco_formsemestre.do_formsemestre_list()
|
||||
|
||||
# Calcul du jury PE
|
||||
self.exe_calculs_juryPE(semBase)
|
||||
self.synthetise_juryPE()
|
||||
|
@ -317,12 +322,10 @@ class JuryPE(object):
|
|||
etudiants = []
|
||||
for sem in semsListe: # pour chacun des semestres de la liste
|
||||
|
||||
# nt = self.get_notes_d_un_semestre( sem['formsemestre_id'] )
|
||||
nt = self.get_cache_notes_d_un_semestre(sem["formsemestre_id"])
|
||||
# sco_cache.NotesTableCache.get( sem['formsemestre_id'])
|
||||
etudiantsDuSemestre = (
|
||||
nt.get_etudids()
|
||||
) # nt.identdict.keys() # identification des etudiants du semestre
|
||||
) # identification des etudiants du semestre
|
||||
|
||||
if pe_tools.PE_DEBUG:
|
||||
pe_tools.pe_print(
|
||||
|
@ -486,14 +489,14 @@ class JuryPE(object):
|
|||
lastdate = max(sesdates) # date de fin de l'inscription la plus récente
|
||||
|
||||
# if PETable.AFFICHAGE_DEBUG_PE == True : pe_tools.pe_print(" derniere inscription = ", lastDateSem)
|
||||
semestresDeScoDoc = sco_formsemestre.do_formsemestre_list()
|
||||
|
||||
if sonDernierSidValide is None:
|
||||
# si l'étudiant n'a validé aucun semestre, les prend tous ? (à vérifier)
|
||||
semestresSuperieurs = semestresDeScoDoc
|
||||
semestresSuperieurs = self.semestresDeScoDoc
|
||||
else:
|
||||
semestresSuperieurs = [
|
||||
sem
|
||||
for sem in semestresDeScoDoc
|
||||
for sem in self.semestresDeScoDoc
|
||||
if sem["semestre_id"] > sonDernierSidValide
|
||||
] # Semestre de rang plus élevé que son dernier sem valide
|
||||
datesDesSemestresSuperieurs = [
|
||||
|
@ -1127,9 +1130,10 @@ class JuryPE(object):
|
|||
# ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------
|
||||
def get_cache_notes_d_un_semestre(self, formsemestre_id): # inutile en realité !
|
||||
def get_cache_notes_d_un_semestre(self, formsemestre_id: int) -> NotesTableCompat:
|
||||
"""Charge la table des notes d'un formsemestre"""
|
||||
return sco_cache.NotesTableCache.get(formsemestre_id)
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
return res_sem.load_formsemestre_results(formsemestre)
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
|
|
@ -37,8 +37,12 @@ Created on Fri Sep 9 09:15:05 2016
|
|||
"""
|
||||
|
||||
from app import log
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import FormSemestre
|
||||
from app.models.moduleimpls import ModuleImpl
|
||||
|
||||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_tag_module
|
||||
from app.pe import pe_tagtable
|
||||
|
||||
|
@ -51,7 +55,7 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
- nt: le tableau de notes du semestre considéré
|
||||
- nt.inscrlist: étudiants inscrits à ce semestre, par ordre alphabétique (avec demissions)
|
||||
- nt.identdict: { etudid : ident }
|
||||
- nt._modimpls : liste des moduleimpl { ... 'module_id', ...}
|
||||
- liste des moduleimpl { ... 'module_id', ...}
|
||||
|
||||
Attributs supplémentaires :
|
||||
- inscrlist/identdict: étudiants inscrits hors démissionnaires ou défaillants
|
||||
|
@ -96,7 +100,11 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
self.nt = notetable
|
||||
|
||||
# Les attributs hérités : la liste des étudiants
|
||||
self.inscrlist = [etud for etud in self.nt.inscrlist if etud["etat"] == "I"]
|
||||
self.inscrlist = [
|
||||
etud
|
||||
for etud in self.nt.inscrlist
|
||||
if self.nt.get_etud_etat(etud["etudid"]) == "I"
|
||||
]
|
||||
self.identdict = {
|
||||
etudid: ident
|
||||
for (etudid, ident) in self.nt.identdict.items()
|
||||
|
@ -106,12 +114,15 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
# Les modules pris en compte dans le calcul des moyennes par tag => ceux des UE standards
|
||||
self.modimpls = [
|
||||
modimpl
|
||||
for modimpl in self.nt._modimpls
|
||||
if modimpl["ue"]["type"] == sco_codes_parcours.UE_STANDARD
|
||||
for modimpl in self.nt.formsemestre.modimpls_sorted
|
||||
if modimpl.module.ue.type == sco_codes_parcours.UE_STANDARD
|
||||
] # la liste des modules (objet modimpl)
|
||||
# self._modimpl_ids = [modimpl['moduleimpl_id'] for modimpl in self._modimpls] # la liste de id des modules (modimpl_id)
|
||||
self.somme_coeffs = sum(
|
||||
[modimpl["module"]["coefficient"] for modimpl in self.modimpls]
|
||||
[
|
||||
modimpl.module.coefficient
|
||||
for modimpl in self.modimpls
|
||||
if modimpl.module.coefficient is not None
|
||||
]
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
@ -155,9 +166,9 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
tagdict = {}
|
||||
|
||||
for modimpl in self.modimpls:
|
||||
modimpl_id = modimpl["moduleimpl_id"]
|
||||
modimpl_id = modimpl.id
|
||||
# liste des tags pour le modimpl concerné:
|
||||
tags = sco_tag_module.module_tag_list(modimpl["module_id"])
|
||||
tags = sco_tag_module.module_tag_list(modimpl.module.id)
|
||||
|
||||
for (
|
||||
tag
|
||||
|
@ -171,27 +182,25 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
|
||||
# Ajout du modimpl au tagname considéré
|
||||
tagdict[tagname][modimpl_id] = {
|
||||
"module_id": modimpl["module_id"], # les données sur le module
|
||||
"coeff": modimpl["module"][
|
||||
"coefficient"
|
||||
], # le coeff du module dans le semestre
|
||||
"module_id": modimpl.module.id, # les données sur le module
|
||||
"coeff": modimpl.module.coefficient, # le coeff du module dans le semestre
|
||||
"ponderation": ponderation, # la pondération demandée pour le tag sur le module
|
||||
"module_code": modimpl["module"][
|
||||
"code"
|
||||
], # le code qui doit se retrouver à l'identique dans des ue capitalisee
|
||||
"ue_id": modimpl["ue"]["ue_id"], # les données sur l'ue
|
||||
"ue_code": modimpl["ue"]["ue_code"],
|
||||
"ue_acronyme": modimpl["ue"]["acronyme"],
|
||||
"module_code": modimpl.module.code, # le code qui doit se retrouver à l'identique dans des ue capitalisee
|
||||
"ue_id": modimpl.module.ue.id, # les données sur l'ue
|
||||
"ue_code": modimpl.module.ue.ue_code,
|
||||
"ue_acronyme": modimpl.module.ue.acronyme,
|
||||
}
|
||||
return tagdict
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
def comp_MoyennesTag(self, tag, force=False):
|
||||
"""Calcule et renvoie les "moyennes" de tous les étudiants du SemTag (non défaillants)
|
||||
à un tag donné, en prenant en compte
|
||||
def comp_MoyennesTag(self, tag, force=False) -> list:
|
||||
"""Calcule et renvoie les "moyennes" de tous les étudiants du SemTag
|
||||
(non défaillants) à un tag donné, en prenant en compte
|
||||
tous les modimpl_id concerné par le tag, leur coeff et leur pondération.
|
||||
Force ou non le calcul de la moyenne lorsque des notes sont manquantes.
|
||||
Renvoie les informations sous la forme d'une liste [ (moy, somme_coeff_normalise, etudid), ...]
|
||||
|
||||
Renvoie les informations sous la forme d'une liste
|
||||
[ (moy, somme_coeff_normalise, etudid), ...]
|
||||
"""
|
||||
lesMoyennes = []
|
||||
for etudid in self.get_etudids():
|
||||
|
@ -217,7 +226,9 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
def get_moyennes_DUT(self):
|
||||
"""Lit les moyennes DUT du semestre pour tous les étudiants
|
||||
et les renvoie au même format que comp_MoyennesTag"""
|
||||
return [(self.nt.moy_gen[etudid], 1.0, etudid) for etudid in self.get_etudids()]
|
||||
return [
|
||||
(self.nt.etud_moy_gen[etudid], 1.0, etudid) for etudid in self.get_etudids()
|
||||
]
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
def get_noteEtCoeff_modimpl(self, modimpl_id, etudid, profondeur=2):
|
||||
|
@ -229,7 +240,7 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
"""
|
||||
(note, coeff_norm) = (None, None)
|
||||
|
||||
modimpl = get_moduleimpl(self.nt, modimpl_id) # Le module considéré
|
||||
modimpl = get_moduleimpl(modimpl_id) # Le module considéré
|
||||
if modimpl == None or profondeur < 0:
|
||||
return (None, None)
|
||||
|
||||
|
@ -237,14 +248,14 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
ue_capitalisees = self.get_ue_capitalisees(
|
||||
etudid
|
||||
) # les ue capitalisées des étudiants
|
||||
ue_capitalisees_id = [
|
||||
ue["ue_id"] for ue in ue_capitalisees
|
||||
] # les id des ue capitalisées
|
||||
ue_capitalisees_id = {
|
||||
ue_cap["ue_id"] for ue_cap in ue_capitalisees
|
||||
} # les id des ue capitalisées
|
||||
|
||||
# Si le module ne fait pas partie des UE capitalisées
|
||||
if modimpl["module"]["ue_id"] not in ue_capitalisees_id:
|
||||
if modimpl.module.ue.id not in ue_capitalisees_id:
|
||||
note = self.nt.get_etud_mod_moy(modimpl_id, etudid) # lecture de la note
|
||||
coeff = modimpl["module"]["coefficient"] # le coeff
|
||||
coeff = modimpl.module.coefficient # le coeff
|
||||
coeff_norm = (
|
||||
coeff / self.somme_coeffs if self.somme_coeffs != 0 else 0
|
||||
) # le coeff normalisé
|
||||
|
@ -255,29 +266,30 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
self.nt, etudid, modimpl_id
|
||||
) # la moyenne actuelle
|
||||
# A quel semestre correspond l'ue capitalisée et quelles sont ses notes ?
|
||||
# fid_prec = [ ue['formsemestre_id'] for ue in ue_capitalisees if ue['ue_id'] == modimpl['module']['ue_id'] ][0]
|
||||
# semestre_id = modimpl['module']['semestre_id']
|
||||
fids_prec = [
|
||||
ue["formsemestre_id"]
|
||||
for ue in ue_capitalisees
|
||||
if ue["ue_code"] == modimpl["ue"]["ue_code"]
|
||||
ue_cap["formsemestre_id"]
|
||||
for ue_cap in ue_capitalisees
|
||||
if ue_cap["ue_code"] == modimpl.module.ue.ue_code
|
||||
] # and ue['semestre_id'] == semestre_id]
|
||||
if len(fids_prec) > 0:
|
||||
# => le formsemestre_id du semestre dont vient la capitalisation
|
||||
fid_prec = fids_prec[0]
|
||||
# Lecture des notes de ce semestre
|
||||
nt_prec = sco_cache.NotesTableCache.get(
|
||||
fid_prec
|
||||
) # le tableau de note du semestre considéré
|
||||
# le tableau de note du semestre considéré:
|
||||
formsemestre_prec = FormSemestre.query.get_or_404(fid_prec)
|
||||
nt_prec: NotesTableCompat = res_sem.load_formsemestre_results(
|
||||
formsemestre_prec
|
||||
)
|
||||
|
||||
# Y-a-t-il un module équivalent c'est à dire correspondant au même code (le module_id n'étant pas significatif en cas de changement de PPN)
|
||||
|
||||
modimpl_prec = [
|
||||
module
|
||||
for module in nt_prec._modimpls
|
||||
if module["module"]["code"] == modimpl["module"]["code"]
|
||||
modi
|
||||
for modi in nt_prec.formsemestre.modimpls_sorted
|
||||
if modi.module.code == modimpl.module.code
|
||||
]
|
||||
if len(modimpl_prec) > 0: # si une correspondance est trouvée
|
||||
modprec_id = modimpl_prec[0]["moduleimpl_id"]
|
||||
modprec_id = modimpl_prec[0].id
|
||||
moy_ue_capitalisee = get_moy_ue_from_nt(nt_prec, etudid, modprec_id)
|
||||
if (
|
||||
moy_ue_capitalisee is None
|
||||
|
@ -285,7 +297,7 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
note = self.nt.get_etud_mod_moy(
|
||||
modimpl_id, etudid
|
||||
) # lecture de la note
|
||||
coeff = modimpl["module"]["coefficient"] # le coeff
|
||||
coeff = modimpl.module.coefficient # le coeff
|
||||
coeff_norm = (
|
||||
coeff / self.somme_coeffs if self.somme_coeffs != 0 else 0
|
||||
) # le coeff normalisé
|
||||
|
@ -299,10 +311,11 @@ class SemestreTag(pe_tagtable.TableTag):
|
|||
return (note, coeff_norm)
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
def get_ue_capitalisees(self, etudid):
|
||||
"""Renvoie la liste des ue_id effectivement capitalisées par un étudiant"""
|
||||
# return [ ue for ue in self.nt.ue_capitalisees[etudid] if self.nt.get_etud_ue_status(etudid,ue['ue_id'])['is_capitalized'] ]
|
||||
return self.nt.ue_capitalisees[etudid]
|
||||
def get_ue_capitalisees(self, etudid) -> list[dict]:
|
||||
"""Renvoie la liste des capitalisation effectivement capitalisées par un étudiant"""
|
||||
if etudid in self.nt.validations.ue_capitalisees.index:
|
||||
return self.nt.validations.ue_capitalisees.loc[[etudid]].to_dict("records")
|
||||
return []
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
def get_listesNotesEtCoeffsTagEtudiant(self, tag, etudid):
|
||||
|
@ -468,37 +481,27 @@ def comp_coeff_pond(coeffs, ponderations):
|
|||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
def get_moduleimpl(nt, modimpl_id):
|
||||
"""Renvoie l'objet modimpl dont l'id est modimpl_id fourni dans la note table nt,
|
||||
en utilisant l'attribut nt._modimpls"""
|
||||
modimplids = [
|
||||
modimpl["moduleimpl_id"] for modimpl in nt._modimpls
|
||||
] # la liste de id des modules (modimpl_id)
|
||||
if modimpl_id not in modimplids:
|
||||
if SemestreTag.DEBUG:
|
||||
log(
|
||||
"SemestreTag.get_moduleimpl( %s ) : le modimpl recherche n'existe pas"
|
||||
% (modimpl_id)
|
||||
)
|
||||
return None
|
||||
return nt._modimpls[modimplids.index(modimpl_id)]
|
||||
def get_moduleimpl(modimpl_id) -> dict:
|
||||
"""Renvoie l'objet modimpl dont l'id est modimpl_id"""
|
||||
modimpl = ModuleImpl.query.get(modimpl_id)
|
||||
if modimpl:
|
||||
return modimpl
|
||||
if SemestreTag.DEBUG:
|
||||
log(
|
||||
"SemestreTag.get_moduleimpl( %s ) : le modimpl recherche n'existe pas"
|
||||
% (modimpl_id)
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# **********************************************
|
||||
def get_moy_ue_from_nt(nt, etudid, modimpl_id):
|
||||
"""Renvoie la moyenne de l'UE d'un etudid dans laquelle se trouve le module de modimpl_id
|
||||
en partant du note table nt"""
|
||||
mod = get_moduleimpl(nt, modimpl_id) # le module
|
||||
indice = 0
|
||||
while indice < len(nt._ues):
|
||||
if (
|
||||
nt._ues[indice]["ue_id"] == mod["module"]["ue_id"]
|
||||
): # si les ue_id correspond
|
||||
data = [
|
||||
ligne for ligne in nt.T if ligne[-1] == etudid
|
||||
] # les notes de l'étudiant
|
||||
if data:
|
||||
return data[0][indice + 1] # la moyenne à l'ue
|
||||
else:
|
||||
indice += 1
|
||||
return None # si non trouvé
|
||||
def get_moy_ue_from_nt(nt, etudid, modimpl_id) -> float:
|
||||
"""Renvoie la moyenne de l'UE d'un etudid dans laquelle se trouve
|
||||
le module de modimpl_id
|
||||
"""
|
||||
# ré-écrit
|
||||
modimpl = get_moduleimpl(modimpl_id) # le module
|
||||
ue_status = nt.get_etud_ue_status(etudid, modimpl.module.ue.id)
|
||||
if ue_status is None:
|
||||
return None
|
||||
return ue_status["moy"]
|
||||
|
|
|
@ -38,6 +38,7 @@ Created on Thu Sep 8 09:36:33 2016
|
|||
"""
|
||||
|
||||
import datetime
|
||||
import numpy as np
|
||||
|
||||
from app.scodoc import notes_table
|
||||
|
||||
|
@ -117,15 +118,15 @@ class TableTag(object):
|
|||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
def get_moy_from_stats(self, tag):
|
||||
""" Renvoie la moyenne des notes calculées pour d'un tag donné"""
|
||||
"""Renvoie la moyenne des notes calculées pour d'un tag donné"""
|
||||
return self.statistiques[tag][0] if tag in self.statistiques else None
|
||||
|
||||
def get_min_from_stats(self, tag):
|
||||
""" Renvoie la plus basse des notes calculées pour d'un tag donné"""
|
||||
"""Renvoie la plus basse des notes calculées pour d'un tag donné"""
|
||||
return self.statistiques[tag][1] if tag in self.statistiques else None
|
||||
|
||||
def get_max_from_stats(self, tag):
|
||||
""" Renvoie la plus haute des notes calculées pour d'un tag donné"""
|
||||
"""Renvoie la plus haute des notes calculées pour d'un tag donné"""
|
||||
return self.statistiques[tag][2] if tag in self.statistiques else None
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------
|
||||
|
@ -236,7 +237,7 @@ class TableTag(object):
|
|||
return moystr
|
||||
|
||||
def str_res_d_un_etudiant(self, etudid, delim=";"):
|
||||
"""Renvoie sur une ligne les résultats d'un étudiant à tous les tags (par ordre alphabétique). """
|
||||
"""Renvoie sur une ligne les résultats d'un étudiant à tous les tags (par ordre alphabétique)."""
|
||||
return delim.join(
|
||||
[self.str_resTag_d_un_etudiant(tag, etudid) for tag in self.get_all_tags()]
|
||||
)
|
||||
|
@ -256,7 +257,7 @@ class TableTag(object):
|
|||
# -----------------------------------------------------------------------
|
||||
|
||||
def str_tagtable(self, delim=";", decimal_sep=","):
|
||||
"""Renvoie une chaine de caractère listant toutes les moyennes, les rangs des étudiants pour tous les tags. """
|
||||
"""Renvoie une chaine de caractère listant toutes les moyennes, les rangs des étudiants pour tous les tags."""
|
||||
entete = ["etudid", "nom", "prenom"]
|
||||
for tag in self.get_all_tags():
|
||||
entete += [titre + "_" + tag for titre in ["note", "rang", "nb_inscrit"]]
|
||||
|
@ -287,48 +288,53 @@ class TableTag(object):
|
|||
|
||||
|
||||
# *********************************************
|
||||
def moyenne_ponderee_terme_a_terme(notes, coeffs=None, force=False):
|
||||
def moyenne_ponderee_terme_a_terme(notes, coefs=None, force=False):
|
||||
"""
|
||||
Calcule la moyenne pondérée d'une liste de notes avec d'éventuels coeffs de pondération.
|
||||
Renvoie le résultat sous forme d'un tuple (moy, somme_coeff)
|
||||
|
||||
La liste de notes contient soit : 1) des valeurs numériques 2) des strings "-NA-" (pas de notes) ou "-NI-" (pas inscrit)
|
||||
ou "-c-" ue capitalisée, 3) None.
|
||||
La liste de notes contient soit :
|
||||
1) des valeurs numériques
|
||||
2) des strings "-NA-" (pas de notes) ou "-NI-" (pas inscrit) ou "-c-" ue capitalisée,
|
||||
3) None.
|
||||
|
||||
Le paramètre force indique si le calcul de la moyenne doit être forcée ou non, c'est à
|
||||
dire s'il y a ou non omission des notes non numériques (auquel cas la moyenne est calculée sur les
|
||||
notes disponibles) ; sinon renvoie (None, None).
|
||||
dire s'il y a ou non omission des notes non numériques (auquel cas la moyenne est
|
||||
calculée sur les notes disponibles) ; sinon renvoie (None, None).
|
||||
"""
|
||||
# Vérification des paramètres d'entrée
|
||||
if not isinstance(notes, list) or (
|
||||
coeffs != None and not isinstance(coeffs, list) and len(coeffs) != len(notes)
|
||||
coefs != None and not isinstance(coefs, list) and len(coefs) != len(notes)
|
||||
):
|
||||
raise ValueError("Erreur de paramètres dans moyenne_ponderee_terme_a_terme")
|
||||
|
||||
# Récupération des valeurs des paramètres d'entrée
|
||||
coeffs = [1] * len(notes) if coeffs == None else coeffs
|
||||
coefs = [1] * len(notes) if coefs is None else coefs
|
||||
|
||||
# S'il n'y a pas de notes
|
||||
if not notes: # Si notes = []
|
||||
return (None, None)
|
||||
|
||||
notesValides = [
|
||||
(1 if isinstance(note, float) or isinstance(note, int) else 0) for note in notes
|
||||
] # Liste indiquant les notes valides
|
||||
if force == True or (
|
||||
force == False and sum(notesValides) == len(notes)
|
||||
): # Si on force le calcul de la moyenne ou qu'on ne le force pas et qu'on a le bon nombre de notes
|
||||
(moyenne, ponderation) = (0.0, 0.0)
|
||||
# Liste indiquant les notes valides
|
||||
notes_valides = [
|
||||
(isinstance(note, float) and not np.isnan(note)) or isinstance(note, int)
|
||||
for note in notes
|
||||
]
|
||||
# Si on force le calcul de la moyenne ou qu'on ne le force pas
|
||||
# et qu'on a le bon nombre de notes
|
||||
if force or sum(notes_valides) == len(notes):
|
||||
moyenne, ponderation = 0.0, 0.0
|
||||
for i in range(len(notes)):
|
||||
if notesValides[i]:
|
||||
moyenne += coeffs[i] * notes[i]
|
||||
ponderation += coeffs[i]
|
||||
if notes_valides[i]:
|
||||
moyenne += coefs[i] * notes[i]
|
||||
ponderation += coefs[i]
|
||||
return (
|
||||
(moyenne / (ponderation * 1.0), ponderation)
|
||||
if ponderation != 0
|
||||
else (None, 0)
|
||||
)
|
||||
else: # Si on ne force pas le calcul de la moyenne
|
||||
return (None, None)
|
||||
# Si on ne force pas le calcul de la moyenne
|
||||
return (None, None)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------
|
||||
|
|
|
@ -36,6 +36,7 @@
|
|||
"""
|
||||
|
||||
from flask import send_file, request
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc import sco_formsemestre
|
||||
|
@ -50,27 +51,34 @@ from app.pe import pe_avislatex
|
|||
def _pe_view_sem_recap_form(formsemestre_id):
|
||||
H = [
|
||||
html_sco_header.sco_header(page_title="Avis de poursuite d'études"),
|
||||
"""<h2 class="formsemestre">Génération des avis de poursuites d'études</h2>
|
||||
f"""<h2 class="formsemestre">Génération des avis de poursuites d'études</h2>
|
||||
<p class="help">
|
||||
Cette fonction génère un ensemble de fichiers permettant d'éditer des avis de poursuites d'études.
|
||||
Cette fonction génère un ensemble de fichiers permettant d'éditer des avis de
|
||||
poursuites d'études.
|
||||
<br/>
|
||||
De nombreux aspects sont paramétrables:
|
||||
<a href="https://scodoc.org/AvisPoursuiteEtudes" target="_blank" rel="noopener noreferrer">
|
||||
De nombreux aspects sont paramétrables:
|
||||
<a href="https://scodoc.org/AvisPoursuiteEtudes" target="_blank" rel="noopener">
|
||||
voir la documentation</a>.
|
||||
</p>
|
||||
<form method="post" action="pe_view_sem_recap" id="pe_view_sem_recap_form" enctype="multipart/form-data">
|
||||
<form method="post" action="pe_view_sem_recap" id="pe_view_sem_recap_form"
|
||||
enctype="multipart/form-data">
|
||||
<div class="pe_template_up">
|
||||
Les templates sont généralement installés sur le serveur ou dans le paramétrage de ScoDoc.<br/>
|
||||
Au besoin, vous pouvez spécifier ici votre propre fichier de template (<tt>un_avis.tex</tt>):
|
||||
<div class="pe_template_upb">Template: <input type="file" size="30" name="avis_tmpl_file"/></div>
|
||||
<div class="pe_template_upb">Pied de page: <input type="file" size="30" name="footer_tmpl_file"/></div>
|
||||
Les templates sont généralement installés sur le serveur ou dans le
|
||||
paramétrage de ScoDoc.
|
||||
<br/>
|
||||
Au besoin, vous pouvez spécifier ici votre propre fichier de template
|
||||
(<tt>un_avis.tex</tt>):
|
||||
<div class="pe_template_upb">Template:
|
||||
<input type="file" size="30" name="avis_tmpl_file"/>
|
||||
</div>
|
||||
<div class="pe_template_upb">Pied de page:
|
||||
<input type="file" size="30" name="footer_tmpl_file"/>
|
||||
</div>
|
||||
</div>
|
||||
<input type="submit" value="Générer les documents"/>
|
||||
<input type="hidden" name="formsemestre_id" value="{formsemestre_id}">
|
||||
</form>
|
||||
""".format(
|
||||
formsemestre_id=formsemestre_id
|
||||
),
|
||||
""",
|
||||
]
|
||||
return "\n".join(H) + html_sco_header.sco_footer()
|
||||
|
||||
|
@ -97,8 +105,12 @@ def pe_view_sem_recap(
|
|||
template_latex = ""
|
||||
# template fourni via le formulaire Web
|
||||
if avis_tmpl_file:
|
||||
template_latex = avis_tmpl_file.read().decode('utf-8')
|
||||
template_latex = template_latex
|
||||
try:
|
||||
template_latex = avis_tmpl_file.read().decode("utf-8")
|
||||
except UnicodeDecodeError as e:
|
||||
raise ScoValueError(
|
||||
"Données (template) invalides (caractères non UTF8 ?)"
|
||||
) from e
|
||||
else:
|
||||
# template indiqué dans préférences ScoDoc ?
|
||||
template_latex = pe_avislatex.get_code_latex_from_scodoc_preference(
|
||||
|
@ -114,8 +126,7 @@ def pe_view_sem_recap(
|
|||
footer_latex = ""
|
||||
# template fourni via le formulaire Web
|
||||
if footer_tmpl_file:
|
||||
footer_latex = footer_tmpl_file.read().decode('utf-8')
|
||||
footer_latex = footer_latex
|
||||
footer_latex = footer_tmpl_file.read().decode("utf-8")
|
||||
else:
|
||||
footer_latex = pe_avislatex.get_code_latex_from_scodoc_preference(
|
||||
formsemestre_id, champ="pe_avis_latex_footer"
|
||||
|
|
|
@ -73,7 +73,8 @@ def TrivialFormulator(
|
|||
input_type : 'text', 'textarea', 'password',
|
||||
'radio', 'menu', 'checkbox',
|
||||
'hidden', 'separator', 'file', 'date', 'datedmy' (avec validation),
|
||||
'boolcheckbox', 'text_suggest'
|
||||
'boolcheckbox', 'text_suggest',
|
||||
'color'
|
||||
(default text)
|
||||
size : text field width
|
||||
rows, cols: textarea geometry
|
||||
|
@ -253,13 +254,13 @@ class TF(object):
|
|||
continue # allowed empty field, skip
|
||||
# type
|
||||
typ = descr.get("type", "string")
|
||||
if val != "" and val != None:
|
||||
if val != "" and val is not None:
|
||||
# check only non-null values
|
||||
if typ[:3] == "int":
|
||||
try:
|
||||
val = int(val)
|
||||
self.values[field] = val
|
||||
except:
|
||||
except ValueError:
|
||||
msg.append(
|
||||
"La valeur du champ '%s' doit être un nombre entier" % field
|
||||
)
|
||||
|
@ -269,25 +270,36 @@ class TF(object):
|
|||
try:
|
||||
val = float(val.replace(",", ".")) # allow ,
|
||||
self.values[field] = val
|
||||
except:
|
||||
except ValueError:
|
||||
msg.append(
|
||||
"La valeur du champ '%s' doit être un nombre" % field
|
||||
)
|
||||
ok = 0
|
||||
if typ[:3] == "int" or typ == "float" or typ == "real":
|
||||
if "min_value" in descr and val < descr["min_value"]:
|
||||
if (
|
||||
ok
|
||||
and (typ[:3] == "int" or typ == "float" or typ == "real")
|
||||
and val != ""
|
||||
and val != None
|
||||
):
|
||||
if "min_value" in descr and self.values[field] < descr["min_value"]:
|
||||
msg.append(
|
||||
"La valeur (%d) du champ '%s' est trop petite (min=%s)"
|
||||
% (val, field, descr["min_value"])
|
||||
)
|
||||
ok = 0
|
||||
|
||||
if "max_value" in descr and val > descr["max_value"]:
|
||||
if "max_value" in descr and self.values[field] > descr["max_value"]:
|
||||
msg.append(
|
||||
"La valeur (%s) du champ '%s' est trop grande (max=%s)"
|
||||
% (val, field, descr["max_value"])
|
||||
)
|
||||
ok = 0
|
||||
if ok and (typ[:3] == "str") and "max_length" in descr:
|
||||
if len(self.values[field]) > descr["max_length"]:
|
||||
msg.append(
|
||||
"Le champ '%s' est trop long (max %d caractères)"
|
||||
% (field, descr["max_length"])
|
||||
)
|
||||
ok = 0
|
||||
|
||||
# allowed values
|
||||
if "allowed_values" in descr:
|
||||
|
@ -594,6 +606,11 @@ class TF(object):
|
|||
var {field}_as = new bsn.AutoSuggest('{field}', {field}_opts);
|
||||
"""
|
||||
)
|
||||
elif input_type == "color":
|
||||
lem.append(
|
||||
'<input type="color" name="%s" id="%s" %s' % (field, field, attribs)
|
||||
)
|
||||
lem.append(('value="%(' + field + ')s" >') % values)
|
||||
else:
|
||||
raise ValueError("unkown input_type for form (%s)!" % input_type)
|
||||
explanation = descr.get("explanation", "")
|
||||
|
@ -712,7 +729,11 @@ var {field}_as = new bsn.AutoSuggest('{field}', {field}_opts);
|
|||
R.append("%s</td>" % title)
|
||||
R.append('<td class="tf-ro-field%s">' % klass)
|
||||
|
||||
if input_type == "text" or input_type == "text_suggest":
|
||||
if (
|
||||
input_type == "text"
|
||||
or input_type == "text_suggest"
|
||||
or input_type == "color"
|
||||
):
|
||||
R.append(("%(" + field + ")s") % self.values)
|
||||
elif input_type in ("radio", "menu", "checkbox", "boolcheckbox"):
|
||||
if input_type == "boolcheckbox":
|
||||
|
|
|
@ -28,6 +28,46 @@
|
|||
from operator import mul
|
||||
import pprint
|
||||
|
||||
""" ANCIENS BONUS SPORT pour ScoDoc < 9.2 NON UTILISES A PARTIR DE 9.2 (voir comp/bonus_spo.py)
|
||||
|
||||
La fonction bonus_sport reçoit:
|
||||
|
||||
- notes_sport: la liste des notes des modules de sport et culture (une note par module
|
||||
de l'UE de type sport/culture, toujours dans remise sur 20);
|
||||
- coefs: un coef (float) pondérant chaque note (la plupart des bonus les ignorent);
|
||||
- infos: dictionnaire avec des données pouvant être utilisées pour les calculs.
|
||||
Ces données dépendent du type de formation.
|
||||
infos = {
|
||||
"moy" : la moyenne générale (float). 0. en BUT.
|
||||
"sem" : {
|
||||
"date_debut_iso" : "2010-08-01", # date de début de semestre
|
||||
}
|
||||
"moy_ues": {
|
||||
ue_id : { # ue_status
|
||||
"is_capitalized" : True|False,
|
||||
"moy" : float, # moyenne d'UE prise en compte (peut-être capitalisée)
|
||||
"sum_coefs": float, # > 0 si UE avec la moyenne calculée
|
||||
"cur_moy_ue": float, # moyenne de l'UE (sans capitalisation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Les notes passées sont:
|
||||
- pour les formations classiques, la moyenne dans le module, calculée comme d'habitude
|
||||
(moyenne pondérée des notes d'évaluations);
|
||||
- pour le BUT: pareil, *en ignorant* les éventuels poids des évaluations. Le coefficient
|
||||
de l'évaluation est pris en compte, mais pas les poids vers les UE.
|
||||
|
||||
Pour modifier les moyennes d'UE:
|
||||
- modifier infos["moy_ues"][ue_id][["cur_moy_ue"]
|
||||
et, seulement si l'UE n'est pas capitalisée, infos["moy_ues"][ue_id][["moy"]/
|
||||
|
||||
La valeur retournée est:
|
||||
- formations classiques: ajoutée à la moyenne générale
|
||||
- BUT: valeur multipliée par la somme des coefs modules sport ajoutée à chaque UE.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
def bonus_iutv(notes_sport, coefs, infos=None):
|
||||
"""Calcul bonus modules optionels (sport, culture), règle IUT Villetaneuse
|
||||
|
@ -52,7 +92,7 @@ def bonus_direct(notes_sport, coefs, infos=None):
|
|||
|
||||
|
||||
def bonus_iut_stdenis(notes_sport, coefs, infos=None):
|
||||
"""Semblable à bonus_iutv mais sans coefficients et total limité à 0.5 points."""
|
||||
"""Semblable à bonus_iutv mais total limité à 0.5 points."""
|
||||
points = sum([x - 10 for x in notes_sport if x > 10]) # points au dessus de 10
|
||||
bonus = points * 0.05 # ou / 20
|
||||
return min(bonus, 0.5) # bonus limité à 1/2 point
|
||||
|
@ -335,7 +375,7 @@ def bonus_iutBordeaux1(notes_sport, coefs, infos=None):
|
|||
return bonus
|
||||
|
||||
|
||||
def bonus_iuto(notes_sport, coefs, infos=None):
|
||||
def bonus_iuto(notes_sport, coefs, infos=None): # OBSOLETE => EN ATTENTE (27/01/2022)
|
||||
"""Calcul bonus modules optionels (sport, culture), règle IUT Orleans
|
||||
* Avant aout 2013
|
||||
Un bonus de 2,5% de la note de sport est accordé à chaque UE sauf
|
||||
|
@ -416,6 +456,11 @@ def bonus_iutbeziers(notes_sport, coefs, infos=None):
|
|||
return bonus
|
||||
|
||||
|
||||
def bonus_iutlemans(notes_sport, coefs, infos=None):
|
||||
"fake: formule inutilisée en ScoDoc 9.2 mais doiut être présente"
|
||||
return 0.0
|
||||
|
||||
|
||||
def bonus_iutlr(notes_sport, coefs, infos=None):
|
||||
"""Calcul bonus modules optionels (sport, culture), règle IUT La Rochelle
|
||||
Si la note de sport est comprise entre 0 et 10 : pas d'ajout de point
|
||||
|
|
|
@ -63,12 +63,15 @@ from app.scodoc.sco_pdf import SU
|
|||
from app import log
|
||||
|
||||
|
||||
def mark_paras(L, tags):
|
||||
"""Put each (string) element of L between <b>"""
|
||||
def mark_paras(L, tags) -> list[str]:
|
||||
"""Put each (string) element of L between <tag>...</tag>,
|
||||
for each supplied tag.
|
||||
Leave non string elements untouched.
|
||||
"""
|
||||
for tag in tags:
|
||||
b = "<" + tag + ">"
|
||||
c = "</" + tag.split()[0] + ">"
|
||||
L = [b + (x or "") + c for x in L]
|
||||
start = "<" + tag + ">"
|
||||
end = "</" + tag.split()[0] + ">"
|
||||
L = [(start + (x or "") + end) if isinstance(x, str) else x for x in L]
|
||||
return L
|
||||
|
||||
|
||||
|
@ -233,7 +236,10 @@ class GenTable(object):
|
|||
colspan_count -= 1
|
||||
# if colspan_count > 0:
|
||||
# continue # skip cells after a span
|
||||
content = row.get(cid, "") or "" # nota: None converted to ''
|
||||
if pdf_mode:
|
||||
content = row.get(f"_{cid}_pdf", "") or row.get(cid, "") or ""
|
||||
else:
|
||||
content = row.get(cid, "") or "" # nota: None converted to ''
|
||||
colspan = row.get("_%s_colspan" % cid, 0)
|
||||
if colspan > 1:
|
||||
pdf_style_list.append(
|
||||
|
@ -547,9 +553,16 @@ class GenTable(object):
|
|||
omit_hidden_lines=True,
|
||||
)
|
||||
try:
|
||||
Pt = [
|
||||
[Paragraph(SU(str(x)), CellStyle) for x in line] for line in data_list
|
||||
]
|
||||
Pt = []
|
||||
for line in data_list:
|
||||
Pt.append(
|
||||
[
|
||||
Paragraph(SU(str(x)), CellStyle)
|
||||
if (not isinstance(x, Paragraph))
|
||||
else x
|
||||
for x in line
|
||||
]
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ScoPDFFormatError(str(exc)) from exc
|
||||
pdf_style_list += self.pdf_table_style
|
||||
|
@ -748,7 +761,7 @@ if __name__ == "__main__":
|
|||
doc = io.BytesIO()
|
||||
document = sco_pdf.BaseDocTemplate(doc)
|
||||
document.addPageTemplates(
|
||||
sco_pdf.ScolarsPageTemplate(
|
||||
sco_pdf.ScoDocPageTemplate(
|
||||
document,
|
||||
)
|
||||
)
|
||||
|
|
|
@ -30,12 +30,12 @@
|
|||
|
||||
import html
|
||||
|
||||
from flask import g
|
||||
from flask import render_template
|
||||
from flask import request
|
||||
from flask_login import current_user
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app import log
|
||||
from app import scodoc_flash_status_messages
|
||||
from app.scodoc import html_sidebar
|
||||
import sco_version
|
||||
|
||||
|
@ -105,7 +105,6 @@ _HTML_BEGIN = """<!DOCTYPE html>
|
|||
<link href="/ScoDoc/static/css/scodoc.css" rel="stylesheet" type="text/css" />
|
||||
<link href="/ScoDoc/static/css/menu.css" rel="stylesheet" type="text/css" />
|
||||
<script src="/ScoDoc/static/libjs/menu.js"></script>
|
||||
<script src="/ScoDoc/static/libjs/sorttable.js"></script>
|
||||
<script src="/ScoDoc/static/libjs/bubble.js"></script>
|
||||
<script>
|
||||
window.onload=function(){enableTooltips("gtrcontent")};
|
||||
|
@ -153,13 +152,14 @@ def sco_header(
|
|||
"Main HTML page header for ScoDoc"
|
||||
from app.scodoc.sco_formsemestre_status import formsemestre_page_title
|
||||
|
||||
scodoc_flash_status_messages()
|
||||
|
||||
# Get head message from http request:
|
||||
if not head_message:
|
||||
if request.method == "POST":
|
||||
head_message = request.form.get("head_message", "")
|
||||
elif request.method == "GET":
|
||||
head_message = request.args.get("head_message", "")
|
||||
|
||||
params = {
|
||||
"page_title": page_title or sco_version.SCONAME,
|
||||
"no_side_bar": no_side_bar,
|
||||
|
@ -249,6 +249,9 @@ def sco_header(
|
|||
'<link rel="stylesheet" type="text/css" href="/ScoDoc/static/DataTables/datatables.min.css"/>'
|
||||
)
|
||||
H.append('<script src="/ScoDoc/static/DataTables/datatables.min.js"></script>')
|
||||
# H.append(
|
||||
# '<link href="/ScoDoc/static/css/tooltip.css" rel="stylesheet" type="text/css" />'
|
||||
# )
|
||||
# JS additionels
|
||||
for js in javascripts:
|
||||
H.append("""<script src="/ScoDoc/static/%s"></script>\n""" % js)
|
||||
|
@ -280,6 +283,9 @@ def sco_header(
|
|||
if not no_side_bar:
|
||||
H.append(html_sidebar.sidebar())
|
||||
H.append("""<div id="gtrcontent">""")
|
||||
# En attendant le replacement complet de cette fonction,
|
||||
# inclusion ici des messages flask
|
||||
H.append(render_template("flashed_messages.html"))
|
||||
#
|
||||
# Barre menu semestre:
|
||||
H.append(formsemestre_page_title())
|
||||
|
@ -313,7 +319,7 @@ def sco_footer():
|
|||
|
||||
|
||||
def html_sem_header(
|
||||
title, sem=None, with_page_header=True, with_h2=True, page_title=None, **args
|
||||
title, with_page_header=True, with_h2=True, page_title=None, **args
|
||||
):
|
||||
"Titre d'une page semestre avec lien vers tableau de bord"
|
||||
# sem now unused and thus optional...
|
||||
|
|
|
@ -29,6 +29,7 @@
|
|||
"""
|
||||
from html.parser import HTMLParser
|
||||
from html.entities import name2codepoint
|
||||
from multiprocessing.sharedctypes import Value
|
||||
import re
|
||||
|
||||
from flask import g, url_for
|
||||
|
@ -36,17 +37,23 @@ from flask import g, url_for
|
|||
from . import listhistogram
|
||||
|
||||
|
||||
def horizontal_bargraph(value, mark):
|
||||
def horizontal_bargraph(value, mark) -> str:
|
||||
"""html drawing an horizontal bar and a mark
|
||||
used to vizualize the relative level of a student
|
||||
"""
|
||||
tmpl = """
|
||||
try:
|
||||
vals = {"value": int(value), "mark": int(mark)}
|
||||
except ValueError:
|
||||
return ""
|
||||
return (
|
||||
"""
|
||||
<span class="graph">
|
||||
<span class="bar" style="width: %(value)d%%;"></span>
|
||||
<span class="mark" style="left: %(mark)d%%; "></span>
|
||||
</span>
|
||||
"""
|
||||
return tmpl % {"value": int(value), "mark": int(mark)}
|
||||
% vals
|
||||
)
|
||||
|
||||
|
||||
def histogram_notes(notes):
|
||||
|
|
|
@ -25,7 +25,9 @@
|
|||
#
|
||||
##############################################################################
|
||||
|
||||
"""Calculs sur les notes et cache des resultats
|
||||
"""Calculs sur les notes et cache des résultats
|
||||
|
||||
Ancien code ScoDoc 7 en cours de rénovation
|
||||
"""
|
||||
|
||||
from operator import itemgetter
|
||||
|
@ -49,8 +51,8 @@ from app.scodoc.sco_formsemestre import (
|
|||
from app.scodoc.sco_codes_parcours import (
|
||||
DEF,
|
||||
UE_SPORT,
|
||||
UE_is_fondamentale,
|
||||
UE_is_professionnelle,
|
||||
ue_is_fondamentale,
|
||||
ue_is_professionnelle,
|
||||
)
|
||||
from app.scodoc.sco_parcours_dut import formsemestre_get_etud_capitalisation
|
||||
from app.scodoc import sco_codes_parcours
|
||||
|
@ -102,7 +104,7 @@ def comp_ranks(T):
|
|||
|
||||
def get_sem_ues_modimpls(formsemestre_id, modimpls=None):
|
||||
"""Get liste des UE du semestre (à partir des moduleimpls)
|
||||
(utilisé quand on ne peut pas construire nt et faire nt.get_ues())
|
||||
(utilisé quand on ne peut pas construire nt et faire nt.get_ues_stat_dict())
|
||||
"""
|
||||
if modimpls is None:
|
||||
modimpls = sco_moduleimpl.moduleimpl_list(formsemestre_id=formsemestre_id)
|
||||
|
@ -168,7 +170,8 @@ class NotesTable:
|
|||
"""
|
||||
|
||||
def __init__(self, formsemestre_id):
|
||||
log(f"NotesTable( formsemestre_id={formsemestre_id} )")
|
||||
# log(f"NotesTable( formsemestre_id={formsemestre_id} )")
|
||||
raise NotImplementedError() # XXX
|
||||
if not formsemestre_id:
|
||||
raise ValueError("invalid formsemestre_id (%s)" % formsemestre_id)
|
||||
self.formsemestre_id = formsemestre_id
|
||||
|
@ -200,7 +203,7 @@ class NotesTable:
|
|||
self.inscrlist.sort(key=itemgetter("nomp"))
|
||||
|
||||
# { etudid : rang dans l'ordre alphabetique }
|
||||
self.rang_alpha = {e["etudid"]: i for i, e in enumerate(self.inscrlist)}
|
||||
self._rang_alpha = {e["etudid"]: i for i, e in enumerate(self.inscrlist)}
|
||||
|
||||
self.bonus = scu.DictDefault(defaultvalue=0)
|
||||
# Notes dans les modules { moduleimpl_id : { etudid: note_moyenne_dans_ce_module } }
|
||||
|
@ -294,7 +297,7 @@ class NotesTable:
|
|||
for ue in self._ues:
|
||||
is_cap[ue["ue_id"]] = ue_status[ue["ue_id"]]["is_capitalized"]
|
||||
|
||||
for modimpl in self.get_modimpls():
|
||||
for modimpl in self.get_modimpls_dict():
|
||||
val = self.get_etud_mod_moy(modimpl["moduleimpl_id"], etudid)
|
||||
if is_cap[modimpl["module"]["ue_id"]]:
|
||||
t.append("-c-")
|
||||
|
@ -316,7 +319,7 @@ class NotesTable:
|
|||
self.moy_min = self.moy_max = "NA"
|
||||
|
||||
# calcul rangs (/ moyenne generale)
|
||||
self.rangs = comp_ranks(T)
|
||||
self.etud_moy_gen_ranks = comp_ranks(T)
|
||||
|
||||
self.rangs_groupes = (
|
||||
{}
|
||||
|
@ -364,7 +367,7 @@ class NotesTable:
|
|||
moy = -float(x[0])
|
||||
except (ValueError, TypeError):
|
||||
moy = 1000.0
|
||||
return (moy, self.rang_alpha[x[-1]])
|
||||
return (moy, self._rang_alpha[x[-1]])
|
||||
|
||||
def get_etudids(self, sorted=False):
|
||||
if sorted:
|
||||
|
@ -417,46 +420,17 @@ class NotesTable:
|
|||
else:
|
||||
return ' <font color="red">(%s)</font> ' % etat
|
||||
|
||||
def get_ues(self, filter_sport=False, filter_non_inscrit=False, etudid=None):
|
||||
"""liste des ue, ordonnée par numero.
|
||||
Si filter_non_inscrit, retire les UE dans lesquelles l'etudiant n'est
|
||||
inscrit à aucun module.
|
||||
def get_ues_stat_dict(self, filter_sport=False): # was get_ues()
|
||||
"""Liste des UEs, ordonnée par numero.
|
||||
Si filter_sport, retire les UE de type SPORT
|
||||
"""
|
||||
if not filter_sport and not filter_non_inscrit:
|
||||
if not filter_sport:
|
||||
return self._ues
|
||||
|
||||
if filter_sport:
|
||||
ues_src = [ue for ue in self._ues if ue["type"] != UE_SPORT]
|
||||
else:
|
||||
ues_src = self._ues
|
||||
if not filter_non_inscrit:
|
||||
return ues_src
|
||||
ues = []
|
||||
for ue in ues_src:
|
||||
if self.get_etud_ue_status(etudid, ue["ue_id"])["is_capitalized"]:
|
||||
# garde toujours les UE capitalisees
|
||||
has_note = True
|
||||
else:
|
||||
has_note = False
|
||||
# verifie que l'etud. est inscrit a au moins un module de l'UE
|
||||
# (en fait verifie qu'il a une note)
|
||||
modimpls = self.get_modimpls(ue["ue_id"])
|
||||
return [ue for ue in self._ues if ue["type"] != UE_SPORT]
|
||||
|
||||
for modi in modimpls:
|
||||
moy = self.get_etud_mod_moy(modi["moduleimpl_id"], etudid)
|
||||
try:
|
||||
float(moy)
|
||||
has_note = True
|
||||
break
|
||||
except:
|
||||
pass
|
||||
if has_note:
|
||||
ues.append(ue)
|
||||
return ues
|
||||
|
||||
def get_modimpls(self, ue_id=None):
|
||||
"liste des modules pour une UE (ou toutes si ue_id==None), triés par matières."
|
||||
def get_modimpls_dict(self, ue_id=None):
|
||||
"Liste des modules pour une UE (ou toutes si ue_id==None), triés par matières."
|
||||
if ue_id is None:
|
||||
r = self._modimpls
|
||||
else:
|
||||
|
@ -522,7 +496,7 @@ class NotesTable:
|
|||
|
||||
Les moyennes d'UE ne tiennent pas compte des capitalisations.
|
||||
"""
|
||||
ues = self.get_ues()
|
||||
ues = self.get_ues_stat_dict()
|
||||
sum_moy = 0 # la somme des moyennes générales valides
|
||||
nb_moy = 0 # le nombre de moyennes générales valides
|
||||
for ue in ues:
|
||||
|
@ -561,9 +535,9 @@ class NotesTable:
|
|||
i = 0
|
||||
for ue in ues:
|
||||
i += 1
|
||||
ue["nb_moy"] = len(ue["_notes"])
|
||||
if ue["nb_moy"] > 0:
|
||||
ue["moy"] = sum(ue["_notes"]) / ue["nb_moy"]
|
||||
ue["nb_vals"] = len(ue["_notes"])
|
||||
if ue["nb_vals"] > 0:
|
||||
ue["moy"] = sum(ue["_notes"]) / ue["nb_vals"]
|
||||
ue["max"] = max(ue["_notes"])
|
||||
ue["min"] = min(ue["_notes"])
|
||||
else:
|
||||
|
@ -591,7 +565,7 @@ class NotesTable:
|
|||
Si non inscrit, moy == 'NI' et sum_coefs==0
|
||||
"""
|
||||
assert ue_id
|
||||
modimpls = self.get_modimpls(ue_id)
|
||||
modimpls = self.get_modimpls_dict(ue_id)
|
||||
nb_notes = 0 # dans cette UE
|
||||
sum_notes = 0.0
|
||||
sum_coefs = 0.0
|
||||
|
@ -729,11 +703,12 @@ class NotesTable:
|
|||
où ue_status = {
|
||||
'est_inscrit' : True si étudiant inscrit à au moins un module de cette UE
|
||||
'moy' : moyenne, avec capitalisation eventuelle
|
||||
'capitalized_ue_id' : id de l'UE capitalisée
|
||||
'coef_ue' : coef de l'UE utilisé pour le calcul de la moyenne générale
|
||||
(la somme des coefs des modules, ou le coef d'UE capitalisée,
|
||||
ou encore le coef d'UE si l'option use_ue_coefs est active)
|
||||
'cur_moy_ue' : moyenne de l'UE en cours (sans considérer de capitalisation)
|
||||
'cur_coef_ue': coefficient de l'UE courante
|
||||
'cur_coef_ue': coefficient de l'UE courante (inutilisé ?)
|
||||
'is_capitalized' : True|False,
|
||||
'ects_pot' : (float) nb de crédits ECTS qui seraient validés (sous réserve de validation par le jury),
|
||||
'ects_pot_fond': 0. si UE non fondamentale, = ects_pot sinon,
|
||||
|
@ -767,7 +742,7 @@ class NotesTable:
|
|||
sem_ects_pot_fond = 0.0
|
||||
sem_ects_pot_pro = 0.0
|
||||
|
||||
for ue in self.get_ues():
|
||||
for ue in self.get_ues_stat_dict():
|
||||
# - On calcule la moyenne d'UE courante:
|
||||
if not block_computation:
|
||||
mu = self.comp_etud_moy_ue(etudid, ue_id=ue["ue_id"], cnx=cnx)
|
||||
|
@ -851,11 +826,11 @@ class NotesTable:
|
|||
and mu["moy"] >= self.parcours.NOTES_BARRE_VALID_UE
|
||||
):
|
||||
mu["ects_pot"] = ue["ects"] or 0.0
|
||||
if UE_is_fondamentale(ue["type"]):
|
||||
if ue_is_fondamentale(ue["type"]):
|
||||
mu["ects_pot_fond"] = mu["ects_pot"]
|
||||
else:
|
||||
mu["ects_pot_fond"] = 0.0
|
||||
if UE_is_professionnelle(ue["type"]):
|
||||
if ue_is_professionnelle(ue["type"]):
|
||||
mu["ects_pot_pro"] = mu["ects_pot"]
|
||||
else:
|
||||
mu["ects_pot_pro"] = 0.0
|
||||
|
@ -940,6 +915,7 @@ class NotesTable:
|
|||
if len(coefs_bonus_gen) == 1:
|
||||
coefs_bonus_gen = [1.0] # irrelevant, may be zero
|
||||
|
||||
# XXX attention: utilise anciens bonus_sport, évidemment
|
||||
bonus_func = ScoDocSiteConfig.get_bonus_sport_func()
|
||||
if bonus_func:
|
||||
bonus = bonus_func(
|
||||
|
@ -953,14 +929,14 @@ class NotesTable:
|
|||
|
||||
return infos
|
||||
|
||||
def get_etud_moy_gen(self, etudid):
|
||||
def get_etud_moy_gen(self, etudid): # -> float | str
|
||||
"""Moyenne generale de cet etudiant dans ce semestre.
|
||||
Prend en compte les UE capitalisées.
|
||||
Si pas de notes: 'NA'
|
||||
"""
|
||||
return self.moy_gen[etudid]
|
||||
|
||||
def get_etud_moy_infos(self, etudid):
|
||||
def get_etud_moy_infos(self, etudid): # XXX OBSOLETE
|
||||
"""Infos sur moyennes"""
|
||||
return self.etud_moy_infos[etudid]
|
||||
|
||||
|
@ -978,15 +954,18 @@ class NotesTable:
|
|||
|
||||
Return: True|False, message explicatif
|
||||
"""
|
||||
return self.parcours.check_barre_ues(
|
||||
[self.get_etud_ue_status(etudid, ue["ue_id"]) for ue in self._ues]
|
||||
)
|
||||
ue_status_list = []
|
||||
for ue in self._ues:
|
||||
ue_status = self.get_etud_ue_status(etudid, ue["ue_id"])
|
||||
if ue_status:
|
||||
ue_status_list.append(ue_status)
|
||||
return self.parcours.check_barre_ues(ue_status_list)
|
||||
|
||||
def get_table_moyennes_triees(self):
|
||||
return self.T
|
||||
|
||||
def get_etud_rang(self, etudid) -> str:
|
||||
return self.rangs.get(etudid, "999")
|
||||
return self.etud_moy_gen_ranks.get(etudid, "999")
|
||||
|
||||
def get_etud_rang_group(self, etudid, group_id):
|
||||
"""Returns rank of etud in this group and number of etuds in group.
|
||||
|
@ -1036,7 +1015,10 @@ class NotesTable:
|
|||
cnx = ndb.GetDBConnexion()
|
||||
cursor = cnx.cursor(cursor_factory=ndb.ScoDocCursor)
|
||||
cursor.execute(
|
||||
"select etudid, code, assidu, compense_formsemestre_id, event_date from scolar_formsemestre_validation where formsemestre_id=%(formsemestre_id)s and ue_id is NULL;",
|
||||
"""SELECT etudid, code, assidu, compense_formsemestre_id, event_date
|
||||
FROM scolar_formsemestre_validation
|
||||
WHERE formsemestre_id=%(formsemestre_id)s AND ue_id is NULL;
|
||||
""",
|
||||
{"formsemestre_id": self.formsemestre_id},
|
||||
)
|
||||
decisions_jury = {}
|
||||
|
@ -1162,8 +1144,14 @@ class NotesTable:
|
|||
"""
|
||||
self.ue_capitalisees = scu.DictDefault(defaultvalue=[])
|
||||
cnx = None
|
||||
semestre_id = self.sem["semestre_id"]
|
||||
for etudid in self.get_etudids():
|
||||
capital = formsemestre_get_etud_capitalisation(self.sem, etudid)
|
||||
capital = formsemestre_get_etud_capitalisation(
|
||||
self.formation["id"],
|
||||
semestre_id,
|
||||
ndb.DateDMYtoISO(self.sem["date_debut"]),
|
||||
etudid,
|
||||
)
|
||||
for ue_cap in capital:
|
||||
# Si la moyenne d'UE n'avait pas été stockée (anciennes versions de ScoDoc)
|
||||
# il faut la calculer ici et l'enregistrer
|
||||
|
@ -1175,16 +1163,18 @@ class NotesTable:
|
|||
nt_cap = sco_cache.NotesTableCache.get(
|
||||
ue_cap["formsemestre_id"]
|
||||
) # > UE capitalisees par un etud
|
||||
moy_ue_cap = nt_cap.get_etud_ue_status(etudid, ue_cap["ue_id"])[
|
||||
"moy"
|
||||
]
|
||||
ue_cap_status = nt_cap.get_etud_ue_status(etudid, ue_cap["ue_id"])
|
||||
if ue_cap_status:
|
||||
moy_ue_cap = ue_cap_status["moy"]
|
||||
else:
|
||||
moy_ue_cap = ""
|
||||
ue_cap["moy_ue"] = moy_ue_cap
|
||||
if (
|
||||
isinstance(moy_ue_cap, float)
|
||||
and moy_ue_cap >= self.parcours.NOTES_BARRE_VALID_UE
|
||||
):
|
||||
if not cnx:
|
||||
cnx = ndb.GetDBConnexion(autocommit=False)
|
||||
cnx = ndb.GetDBConnexion()
|
||||
sco_parcours_dut.do_formsemestre_validate_ue(
|
||||
cnx,
|
||||
nt_cap,
|
||||
|
@ -1329,11 +1319,7 @@ class NotesTable:
|
|||
|
||||
return self._evaluations_etats
|
||||
|
||||
def get_sem_evaluation_etat_list(self):
|
||||
"""Liste des evaluations de ce semestre, avec leur etat"""
|
||||
return self.get_evaluations_etats()
|
||||
|
||||
def get_mod_evaluation_etat_list(self, moduleimpl_id):
|
||||
def get_mod_evaluation_etat_list(self, moduleimpl_id) -> list[dict]:
|
||||
"""Liste des évaluations de ce module"""
|
||||
return [
|
||||
e
|
||||
|
@ -1352,7 +1338,7 @@ class NotesTable:
|
|||
|
||||
# Rappel des épisodes précédents: T est une liste de liste
|
||||
# Colonnes: 0 moy_gen, moy_ue1, ..., moy_ue_n, moy_mod1, ..., moy_mod_n, etudid
|
||||
ues = self.get_ues() # incluant le(s) UE de sport
|
||||
ues = self.get_ues_stat_dict() # incluant le(s) UE de sport
|
||||
for t in self.T:
|
||||
etudid = t[-1]
|
||||
if etudid in results.etud_moy_gen: # evite les démissionnaires
|
||||
|
@ -1367,4 +1353,4 @@ class NotesTable:
|
|||
# re-trie selon la nouvelle moyenne générale:
|
||||
self.T.sort(key=self._row_key)
|
||||
# Remplace aussi le rang:
|
||||
self.rangs = results.etud_moy_gen_ranks
|
||||
self.etud_moy_gen_ranks = results.etud_moy_gen_ranks
|
||||
|
|
|
@ -53,7 +53,11 @@ def _isFarFutur(jour):
|
|||
# check si jour est dans le futur "lointain"
|
||||
# pour autoriser les saisies dans le futur mais pas a plus de 6 mois
|
||||
y, m, d = [int(x) for x in jour.split("-")]
|
||||
j = datetime.date(y, m, d)
|
||||
try:
|
||||
j = datetime.date(y, m, d)
|
||||
except ValueError:
|
||||
# les dates erronées, genre année 20022, sont considéres dans le futur
|
||||
return True
|
||||
# 6 mois ~ 182 jours:
|
||||
return j - datetime.date.today() > datetime.timedelta(182)
|
||||
|
||||
|
@ -225,8 +229,11 @@ def DateRangeISO(date_beg, date_end, workable=1):
|
|||
date_end = date_beg
|
||||
r = []
|
||||
work_saturday = is_work_saturday()
|
||||
cur = ddmmyyyy(date_beg, work_saturday=work_saturday)
|
||||
end = ddmmyyyy(date_end, work_saturday=work_saturday)
|
||||
try:
|
||||
cur = ddmmyyyy(date_beg, work_saturday=work_saturday)
|
||||
end = ddmmyyyy(date_end, work_saturday=work_saturday)
|
||||
except (AttributeError, ValueError) as e:
|
||||
raise ScoValueError("date invalide !") from e
|
||||
while cur <= end:
|
||||
if (not workable) or cur.iswork():
|
||||
r.append(cur)
|
||||
|
@ -479,7 +486,7 @@ def _get_abs_description(a, cursor=None):
|
|||
)
|
||||
if Mlist:
|
||||
M = Mlist[0]
|
||||
module += "%s " % M["module"]["code"]
|
||||
module += "%s " % (M["module"]["code"] or "(module sans code)")
|
||||
|
||||
if desc:
|
||||
return "(%s) %s" % (desc, module)
|
||||
|
@ -631,7 +638,7 @@ def add_absence(
|
|||
):
|
||||
"Ajoute une absence dans la bd"
|
||||
if _isFarFutur(jour):
|
||||
raise ScoValueError("date absence trop loin dans le futur !")
|
||||
raise ScoValueError("date absence erronée ou trop loin dans le futur !")
|
||||
estjust = _toboolean(estjust)
|
||||
matin = _toboolean(matin)
|
||||
cnx = ndb.GetDBConnexion()
|
||||
|
@ -1037,7 +1044,7 @@ def get_abs_count(etudid, sem):
|
|||
|
||||
def get_abs_count_in_interval(etudid, date_debut_iso, date_fin_iso):
|
||||
"""Les comptes d'absences de cet étudiant entre ces deux dates, incluses:
|
||||
tuple (nb abs non justifiées, nb abs justifiées)
|
||||
tuple (nb abs, nb abs justifiées)
|
||||
Utilise un cache.
|
||||
"""
|
||||
key = str(etudid) + "_" + date_debut_iso + "_" + date_fin_iso
|
||||
|
|
|
@ -35,6 +35,7 @@ import datetime
|
|||
|
||||
from flask import g, url_for
|
||||
from flask_mail import Message
|
||||
from app.models.formsemestre import FormSemestre
|
||||
|
||||
import app.scodoc.notesdb as ndb
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
@ -55,27 +56,30 @@ def abs_notify(etudid, date):
|
|||
"""
|
||||
from app.scodoc import sco_abs
|
||||
|
||||
sem = retreive_current_formsemestre(etudid, date)
|
||||
if not sem:
|
||||
formsemestre = retreive_current_formsemestre(etudid, date)
|
||||
if not formsemestre:
|
||||
return # non inscrit a la date, pas de notification
|
||||
|
||||
nbabs, nbabsjust = sco_abs.get_abs_count(etudid, sem)
|
||||
do_abs_notify(sem, etudid, date, nbabs, nbabsjust)
|
||||
nbabs, nbabsjust = sco_abs.get_abs_count_in_interval(
|
||||
etudid, formsemestre.date_debut.isoformat(), formsemestre.date_fin.isoformat()
|
||||
)
|
||||
do_abs_notify(formsemestre, etudid, date, nbabs, nbabsjust)
|
||||
|
||||
|
||||
def do_abs_notify(sem, etudid, date, nbabs, nbabsjust):
|
||||
def do_abs_notify(formsemestre: FormSemestre, etudid, date, nbabs, nbabsjust):
|
||||
"""Given new counts of absences, check if notifications are requested and send them."""
|
||||
# prefs fallback to global pref if sem is None:
|
||||
if sem:
|
||||
formsemestre_id = sem["formsemestre_id"]
|
||||
if formsemestre:
|
||||
formsemestre_id = formsemestre.id
|
||||
else:
|
||||
formsemestre_id = None
|
||||
prefs = sco_preferences.SemPreferences(formsemestre_id=sem["formsemestre_id"])
|
||||
prefs = sco_preferences.SemPreferences(formsemestre_id=formsemestre_id)
|
||||
|
||||
destinations = abs_notify_get_destinations(
|
||||
sem, prefs, etudid, date, nbabs, nbabsjust
|
||||
formsemestre, prefs, etudid, date, nbabs, nbabsjust
|
||||
)
|
||||
msg = abs_notification_message(sem, prefs, etudid, nbabs, nbabsjust)
|
||||
|
||||
msg = abs_notification_message(formsemestre, prefs, etudid, nbabs, nbabsjust)
|
||||
if not msg:
|
||||
return # abort
|
||||
|
||||
|
@ -131,19 +135,19 @@ def abs_notify_send(destinations, etudid, msg, nbabs, nbabsjust, formsemestre_id
|
|||
)
|
||||
|
||||
|
||||
def abs_notify_get_destinations(sem, prefs, etudid, date, nbabs, nbabsjust):
|
||||
def abs_notify_get_destinations(
|
||||
formsemestre: FormSemestre, prefs, etudid, date, nbabs, nbabsjust
|
||||
) -> set:
|
||||
"""Returns set of destination emails to be notified"""
|
||||
formsemestre_id = sem["formsemestre_id"]
|
||||
|
||||
destinations = [] # list of email address to notify
|
||||
|
||||
if abs_notify_is_above_threshold(etudid, nbabs, nbabsjust, formsemestre_id):
|
||||
if sem and prefs["abs_notify_respsem"]:
|
||||
if abs_notify_is_above_threshold(etudid, nbabs, nbabsjust, formsemestre.id):
|
||||
if prefs["abs_notify_respsem"]:
|
||||
# notifie chaque responsable du semestre
|
||||
for responsable_id in sem["responsables"]:
|
||||
u = sco_users.user_info(responsable_id)
|
||||
if u["email"]:
|
||||
destinations.append(u["email"])
|
||||
for responsable in formsemestre.responsables:
|
||||
if responsable.email:
|
||||
destinations.append(responsable.email)
|
||||
if prefs["abs_notify_chief"] and prefs["email_chefdpt"]:
|
||||
destinations.append(prefs["email_chefdpt"])
|
||||
if prefs["abs_notify_email"]:
|
||||
|
@ -156,7 +160,7 @@ def abs_notify_get_destinations(sem, prefs, etudid, date, nbabs, nbabsjust):
|
|||
# Notification (à chaque fois) des resp. de modules ayant des évaluations
|
||||
# à cette date
|
||||
# nb: on pourrait prevoir d'utiliser un autre format de message pour ce cas
|
||||
if sem and prefs["abs_notify_respeval"]:
|
||||
if prefs["abs_notify_respeval"]:
|
||||
mods = mod_with_evals_at_date(date, etudid)
|
||||
for mod in mods:
|
||||
u = sco_users.user_info(mod["responsable_id"])
|
||||
|
@ -232,7 +236,9 @@ def user_nbdays_since_last_notif(email_addr, etudid):
|
|||
return None
|
||||
|
||||
|
||||
def abs_notification_message(sem, prefs, etudid, nbabs, nbabsjust):
|
||||
def abs_notification_message(
|
||||
formsemestre: FormSemestre, prefs, etudid, nbabs, nbabsjust
|
||||
):
|
||||
"""Mime notification message based on template.
|
||||
returns a Message instance
|
||||
or None if sending should be canceled (empty template).
|
||||
|
@ -242,13 +248,13 @@ def abs_notification_message(sem, prefs, etudid, nbabs, nbabsjust):
|
|||
etud = sco_etud.get_etud_info(etudid=etudid, filled=True)[0]
|
||||
|
||||
# Variables accessibles dans les balises du template: %(nom_variable)s :
|
||||
values = sco_bulletins.make_context_dict(sem, etud)
|
||||
values = sco_bulletins.make_context_dict(formsemestre, etud)
|
||||
|
||||
values["nbabs"] = nbabs
|
||||
values["nbabsjust"] = nbabsjust
|
||||
values["nbabsnonjust"] = nbabs - nbabsjust
|
||||
values["url_ficheetud"] = url_for(
|
||||
"scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=etudid
|
||||
"scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=etudid, _external=True
|
||||
)
|
||||
|
||||
template = prefs["abs_notification_mail_tmpl"]
|
||||
|
@ -264,9 +270,11 @@ def abs_notification_message(sem, prefs, etudid, nbabs, nbabsjust):
|
|||
return msg
|
||||
|
||||
|
||||
def retreive_current_formsemestre(etudid, cur_date):
|
||||
def retreive_current_formsemestre(etudid: int, cur_date) -> FormSemestre:
|
||||
"""Get formsemestre dans lequel etudid est (ou était) inscrit a la date indiquée
|
||||
date est une chaine au format ISO (yyyy-mm-dd)
|
||||
|
||||
Result: FormSemestre ou None si pas inscrit à la date indiquée
|
||||
"""
|
||||
req = """SELECT i.formsemestre_id
|
||||
FROM notes_formsemestre_inscription i, notes_formsemestre sem
|
||||
|
@ -278,8 +286,8 @@ def retreive_current_formsemestre(etudid, cur_date):
|
|||
if not r:
|
||||
return None
|
||||
# s'il y a plusieurs semestres, prend le premier (rarissime et non significatif):
|
||||
sem = sco_formsemestre.get_formsemestre(r[0]["formsemestre_id"])
|
||||
return sem
|
||||
formsemestre = FormSemestre.query.get(r[0]["formsemestre_id"])
|
||||
return formsemestre
|
||||
|
||||
|
||||
def mod_with_evals_at_date(date_abs, etudid):
|
||||
|
|
|
@ -32,6 +32,10 @@ import datetime
|
|||
|
||||
from flask import url_for, g, request, abort
|
||||
|
||||
from app import log
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import Identite, FormSemestre
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc import notesdb as ndb
|
||||
from app.scodoc.scolog import logdb
|
||||
|
@ -46,7 +50,6 @@ from app.scodoc import sco_groups
|
|||
from app.scodoc import sco_moduleimpl
|
||||
from app.scodoc import sco_photos
|
||||
from app.scodoc import sco_preferences
|
||||
from app import log
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
|
||||
|
||||
|
@ -71,8 +74,8 @@ def doSignaleAbsence(
|
|||
etudid: etudiant concerné. Si non spécifié, cherche dans
|
||||
les paramètres de la requête courante.
|
||||
"""
|
||||
etud = sco_etud.get_etud_info(filled=True, etudid=etudid)[0]
|
||||
etudid = etud["etudid"]
|
||||
etud = Identite.from_request(etudid)
|
||||
|
||||
if not moduleimpl_id:
|
||||
moduleimpl_id = None
|
||||
description_abs = description
|
||||
|
@ -82,7 +85,7 @@ def doSignaleAbsence(
|
|||
for jour in dates:
|
||||
if demijournee == 2:
|
||||
sco_abs.add_absence(
|
||||
etudid,
|
||||
etud.id,
|
||||
jour,
|
||||
False,
|
||||
estjust,
|
||||
|
@ -90,7 +93,7 @@ def doSignaleAbsence(
|
|||
moduleimpl_id,
|
||||
)
|
||||
sco_abs.add_absence(
|
||||
etudid,
|
||||
etud.id,
|
||||
jour,
|
||||
True,
|
||||
estjust,
|
||||
|
@ -100,7 +103,7 @@ def doSignaleAbsence(
|
|||
nbadded += 2
|
||||
else:
|
||||
sco_abs.add_absence(
|
||||
etudid,
|
||||
etud.id,
|
||||
jour,
|
||||
demijournee,
|
||||
estjust,
|
||||
|
@ -113,27 +116,30 @@ def doSignaleAbsence(
|
|||
J = ""
|
||||
else:
|
||||
J = "NON "
|
||||
M = ""
|
||||
indication_module = ""
|
||||
if moduleimpl_id and moduleimpl_id != "NULL":
|
||||
mod = sco_moduleimpl.moduleimpl_list(moduleimpl_id=moduleimpl_id)[0]
|
||||
formsemestre_id = mod["formsemestre_id"]
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id)
|
||||
ues = nt.get_ues(etudid=etudid)
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
ues = nt.get_ues_stat_dict()
|
||||
for ue in ues:
|
||||
modimpls = nt.get_modimpls(ue_id=ue["ue_id"])
|
||||
modimpls = nt.get_modimpls_dict(ue_id=ue["ue_id"])
|
||||
for modimpl in modimpls:
|
||||
if modimpl["moduleimpl_id"] == moduleimpl_id:
|
||||
M = "dans le module %s" % modimpl["module"]["code"]
|
||||
indication_module = "dans le module %s" % (
|
||||
modimpl["module"]["code"] or "(pas de code)"
|
||||
)
|
||||
H = [
|
||||
html_sco_header.sco_header(
|
||||
page_title="Signalement d'une absence pour %(nomprenom)s" % etud,
|
||||
page_title=f"Signalement d'une absence pour {etud.nomprenom}",
|
||||
),
|
||||
"""<h2>Signalement d'absences</h2>""",
|
||||
]
|
||||
if dates:
|
||||
H.append(
|
||||
"""<p>Ajout de %d absences <b>%sjustifiées</b> du %s au %s %s</p>"""
|
||||
% (nbadded, J, datedebut, datefin, M)
|
||||
% (nbadded, J, datedebut, datefin, indication_module)
|
||||
)
|
||||
else:
|
||||
H.append(
|
||||
|
@ -142,11 +148,18 @@ def doSignaleAbsence(
|
|||
)
|
||||
|
||||
H.append(
|
||||
"""<ul><li><a href="SignaleAbsenceEtud?etudid=%(etudid)s">Autre absence pour <b>%(nomprenom)s</b></a></li>
|
||||
<li><a href="CalAbs?etudid=%(etudid)s">Calendrier de ses absences</a></li>
|
||||
</ul>
|
||||
<hr>"""
|
||||
% etud
|
||||
f"""<ul>
|
||||
<li><a href="{url_for("absences.SignaleAbsenceEtud",
|
||||
scodoc_dept=g.scodoc_dept, etudid=etud.id
|
||||
)}">Autre absence pour <b>{etud.nomprenom}</b></a>
|
||||
</li>
|
||||
<li><a href="{url_for("absences.CalAbs",
|
||||
scodoc_dept=g.scodoc_dept, etudid=etud.id
|
||||
)}">Calendrier de ses absences</a>
|
||||
</li>
|
||||
</ul>
|
||||
<hr>
|
||||
"""
|
||||
)
|
||||
H.append(sco_find_etud.form_search_etud())
|
||||
H.append(html_sco_header.sco_footer())
|
||||
|
@ -171,11 +184,12 @@ def SignaleAbsenceEtud(): # etudid implied
|
|||
menu_module = ""
|
||||
else:
|
||||
formsemestre_id = etud["cursem"]["formsemestre_id"]
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
ues = nt.get_ues_stat_dict()
|
||||
require_module = sco_preferences.get_preference(
|
||||
"abs_require_module", formsemestre_id
|
||||
)
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id)
|
||||
ues = nt.get_ues(etudid=etudid)
|
||||
if require_module:
|
||||
menu_module = """
|
||||
<script type="text/javascript">
|
||||
|
@ -200,13 +214,13 @@ def SignaleAbsenceEtud(): # etudid implied
|
|||
menu_module += """<option value="" selected>(Module)</option>"""
|
||||
|
||||
for ue in ues:
|
||||
modimpls = nt.get_modimpls(ue_id=ue["ue_id"])
|
||||
modimpls = nt.get_modimpls_dict(ue_id=ue["ue_id"])
|
||||
for modimpl in modimpls:
|
||||
menu_module += (
|
||||
"""<option value="%(modimpl_id)s">%(modname)s</option>\n"""
|
||||
% {
|
||||
"modimpl_id": modimpl["moduleimpl_id"],
|
||||
"modname": modimpl["module"]["code"],
|
||||
"modname": modimpl["module"]["code"] or "",
|
||||
}
|
||||
)
|
||||
menu_module += """</select></p>"""
|
||||
|
@ -710,6 +724,7 @@ def CalAbs(etudid, sco_year=None):
|
|||
anneescolaire = int(scu.AnneeScolaire(sco_year))
|
||||
datedebut = str(anneescolaire) + "-08-01"
|
||||
datefin = str(anneescolaire + 1) + "-07-31"
|
||||
annee_courante = scu.AnneeScolaire()
|
||||
nbabs = sco_abs.count_abs(etudid=etudid, debut=datedebut, fin=datefin)
|
||||
nbabsjust = sco_abs.count_abs_just(etudid=etudid, debut=datedebut, fin=datefin)
|
||||
events = []
|
||||
|
@ -762,7 +777,7 @@ def CalAbs(etudid, sco_year=None):
|
|||
"""Année scolaire %s-%s""" % (anneescolaire, anneescolaire + 1),
|
||||
""" Changer année: <select name="sco_year" onchange="document.f.submit()">""",
|
||||
]
|
||||
for y in range(anneescolaire, anneescolaire - 10, -1):
|
||||
for y in range(annee_courante, min(annee_courante - 6, anneescolaire - 6), -1):
|
||||
H.append("""<option value="%s" """ % y)
|
||||
if y == anneescolaire:
|
||||
H.append("selected")
|
||||
|
@ -952,10 +967,10 @@ def _tables_abs_etud(
|
|||
ex.append(
|
||||
f"""<a href="{url_for('notes.moduleimpl_status',
|
||||
scodoc_dept=g.scodoc_dept, moduleimpl_id=mod["moduleimpl_id"])}
|
||||
">{mod["module"]["code"]}</a>"""
|
||||
">{mod["module"]["code"] or "(module sans code)"}</a>"""
|
||||
)
|
||||
else:
|
||||
ex.append(mod["module"]["code"])
|
||||
ex.append(mod["module"]["code"] or "(module sans code)")
|
||||
if ex:
|
||||
return ", ".join(ex)
|
||||
return ""
|
||||
|
@ -970,10 +985,10 @@ def _tables_abs_etud(
|
|||
ex.append(
|
||||
f"""<a href="{url_for('notes.moduleimpl_status',
|
||||
scodoc_dept=g.scodoc_dept, moduleimpl_id=mod["moduleimpl_id"])}
|
||||
">{mod["module"]["code"]}</a>"""
|
||||
">{mod["module"]["code"] or '(module sans code)'}</a>"""
|
||||
)
|
||||
else:
|
||||
ex.append(mod["module"]["code"])
|
||||
ex.append(mod["module"]["code"] or "(module sans code)")
|
||||
if ex:
|
||||
return ", ".join(ex)
|
||||
return ""
|
||||
|
|
|
@ -83,6 +83,7 @@ XXX A vérifier:
|
|||
import collections
|
||||
import datetime
|
||||
from functools import reduce
|
||||
import functools
|
||||
import io
|
||||
import os
|
||||
import pprint
|
||||
|
@ -95,9 +96,12 @@ from flask import send_file
|
|||
# Pour la détection auto de l'encodage des fichiers Apogée:
|
||||
from chardet import detect as chardet_detect
|
||||
|
||||
from app import log
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import FormSemestre, Identite
|
||||
from app.models.config import ScoDocSiteConfig
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app import log
|
||||
from app.scodoc.sco_exceptions import ScoValueError, ScoFormatError
|
||||
from app.scodoc.gen_tables import GenTable
|
||||
from app.scodoc.sco_vdi import ApoEtapeVDI
|
||||
|
@ -108,7 +112,6 @@ from app.scodoc.sco_codes_parcours import (
|
|||
NAR,
|
||||
RAT,
|
||||
)
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_parcours_dut
|
||||
from app.scodoc import sco_etud
|
||||
|
@ -123,7 +126,7 @@ APO_SEP = "\t"
|
|||
APO_NEWLINE = "\r\n"
|
||||
|
||||
|
||||
def _apo_fmt_note(note):
|
||||
def _apo_fmt_note(note, fmt="%3.2f"):
|
||||
"Formatte une note pour Apogée (séparateur décimal: ',')"
|
||||
# if not note and isinstance(note, float): changé le 31/1/2022, étrange ?
|
||||
# return ""
|
||||
|
@ -131,7 +134,7 @@ def _apo_fmt_note(note):
|
|||
val = float(note)
|
||||
except ValueError:
|
||||
return ""
|
||||
return ("%3.2f" % val).replace(".", APO_DECIMAL_SEP)
|
||||
return (fmt % val).replace(".", APO_DECIMAL_SEP)
|
||||
|
||||
|
||||
def guess_data_encoding(text, threshold=0.6):
|
||||
|
@ -268,6 +271,9 @@ class ApoEtud(dict):
|
|||
self.export_res_modules = export_res_modules
|
||||
self.export_res_sdj = export_res_sdj # export meme si pas de decision de jury
|
||||
self.export_res_rat = export_res_rat
|
||||
self.fmt_note = functools.partial(
|
||||
_apo_fmt_note, fmt=ScoDocSiteConfig.get_code_apo("NOTES_FMT") or "3.2f"
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return "ApoEtud( nom='%s', nip='%s' )" % (self["nom"], self["nip"])
|
||||
|
@ -370,7 +376,9 @@ class ApoEtud(dict):
|
|||
dict: with N, B, J, R keys, ou None si elt non trouvé
|
||||
"""
|
||||
etudid = self.etud["etudid"]
|
||||
nt = sco_cache.NotesTableCache.get(sem["formsemestre_id"])
|
||||
formsemestre = FormSemestre.query.get_or_404(sem["formsemestre_id"])
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
|
||||
if etudid not in nt.identdict:
|
||||
return None # etudiant non inscrit dans ce semestre
|
||||
|
||||
|
@ -412,14 +420,14 @@ class ApoEtud(dict):
|
|||
|
||||
# Elements UE
|
||||
decisions_ue = nt.get_etud_decision_ues(etudid)
|
||||
for ue in nt.get_ues():
|
||||
if code in ue["code_apogee"].split(","):
|
||||
for ue in nt.get_ues_stat_dict():
|
||||
if ue["code_apogee"] and code in ue["code_apogee"].split(","):
|
||||
if self.export_res_ues:
|
||||
if decisions_ue and ue["ue_id"] in decisions_ue:
|
||||
ue_status = nt.get_etud_ue_status(etudid, ue["ue_id"])
|
||||
code_decision_ue = decisions_ue[ue["ue_id"]]["code"]
|
||||
return dict(
|
||||
N=_apo_fmt_note(ue_status["moy"]),
|
||||
N=self.fmt_note(ue_status["moy"] if ue_status else ""),
|
||||
B=20,
|
||||
J="",
|
||||
R=ScoDocSiteConfig.get_code_apo(code_decision_ue),
|
||||
|
@ -431,13 +439,15 @@ class ApoEtud(dict):
|
|||
return VOID_APO_RES
|
||||
|
||||
# Elements Modules
|
||||
modimpls = nt.get_modimpls()
|
||||
modimpls = nt.get_modimpls_dict()
|
||||
module_code_found = False
|
||||
for modimpl in modimpls:
|
||||
if code in modimpl["module"]["code_apogee"].split(","):
|
||||
if modimpl["module"]["code_apogee"] and code in modimpl["module"][
|
||||
"code_apogee"
|
||||
].split(","):
|
||||
n = nt.get_etud_mod_moy(modimpl["moduleimpl_id"], etudid)
|
||||
if n != "NI" and self.export_res_modules:
|
||||
return dict(N=_apo_fmt_note(n), B=20, J="", R="")
|
||||
return dict(N=self.fmt_note(n), B=20, J="", R="")
|
||||
else:
|
||||
module_code_found = True
|
||||
if module_code_found:
|
||||
|
@ -447,13 +457,19 @@ class ApoEtud(dict):
|
|||
|
||||
def comp_elt_semestre(self, nt, decision, etudid):
|
||||
"""Calcul résultat apo semestre"""
|
||||
if decision is None:
|
||||
etud = Identite.query.get(etudid)
|
||||
nomprenom = etud.nomprenom if etud else "(inconnu)"
|
||||
raise ScoValueError(
|
||||
f"decision absente pour l'étudiant {nomprenom} ({etudid})"
|
||||
)
|
||||
# resultat du semestre
|
||||
decision_apo = ScoDocSiteConfig.get_code_apo(decision["code"])
|
||||
note = nt.get_etud_moy_gen(etudid)
|
||||
if decision_apo == "DEF" or decision["code"] == DEM or decision["code"] == DEF:
|
||||
note_str = "0,01" # note non nulle pour les démissionnaires
|
||||
else:
|
||||
note_str = _apo_fmt_note(note)
|
||||
note_str = self.fmt_note(note)
|
||||
return dict(N=note_str, B=20, J="", R=decision_apo, M="")
|
||||
|
||||
def comp_elt_annuel(self, etudid, cur_sem, autre_sem):
|
||||
|
@ -474,7 +490,8 @@ class ApoEtud(dict):
|
|||
# l'étudiant n'a pas de semestre courant ?!
|
||||
log("comp_elt_annuel: etudid %s has no cur_sem" % etudid)
|
||||
return VOID_APO_RES
|
||||
cur_nt = sco_cache.NotesTableCache.get(cur_sem["formsemestre_id"])
|
||||
cur_formsemestre = FormSemestre.query.get_or_404(cur_sem["formsemestre_id"])
|
||||
cur_nt: NotesTableCompat = res_sem.load_formsemestre_results(cur_formsemestre)
|
||||
cur_decision = cur_nt.get_etud_decision_sem(etudid)
|
||||
if not cur_decision:
|
||||
# pas de decision => pas de résultat annuel
|
||||
|
@ -491,7 +508,10 @@ class ApoEtud(dict):
|
|||
|
||||
decision_apo = ScoDocSiteConfig.get_code_apo(cur_decision["code"])
|
||||
|
||||
autre_nt = sco_cache.NotesTableCache.get(autre_sem["formsemestre_id"])
|
||||
autre_formsemestre = FormSemestre.query.get_or_404(autre_sem["formsemestre_id"])
|
||||
autre_nt: NotesTableCompat = res_sem.load_formsemestre_results(
|
||||
autre_formsemestre
|
||||
)
|
||||
autre_decision = autre_nt.get_etud_decision_sem(etudid)
|
||||
if not autre_decision:
|
||||
# pas de decision dans l'autre => pas de résultat annuel
|
||||
|
@ -515,7 +535,7 @@ class ApoEtud(dict):
|
|||
moy_annuelle = (note + autre_note) / 2
|
||||
except TypeError:
|
||||
moy_annuelle = ""
|
||||
note_str = _apo_fmt_note(moy_annuelle)
|
||||
note_str = self.fmt_note(moy_annuelle)
|
||||
|
||||
if code_semestre_validant(autre_decision["code"]):
|
||||
decision_apo_annuelle = decision_apo
|
||||
|
@ -552,7 +572,8 @@ class ApoEtud(dict):
|
|||
# prend le plus recent avec decision
|
||||
cur_sem = None
|
||||
for sem in cur_sems:
|
||||
nt = sco_cache.NotesTableCache.get(sem["formsemestre_id"])
|
||||
formsemestre = FormSemestre.query.get_or_404(sem["formsemestre_id"])
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
decision = nt.get_etud_decision_sem(self.etud["etudid"])
|
||||
if decision:
|
||||
cur_sem = sem
|
||||
|
@ -612,7 +633,8 @@ class ApoEtud(dict):
|
|||
else:
|
||||
autre_sem = None
|
||||
for sem in autres_sems:
|
||||
nt = sco_cache.NotesTableCache.get(sem["formsemestre_id"])
|
||||
formsemestre = FormSemestre.query.get_or_404(sem["formsemestre_id"])
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
decision = nt.get_etud_decision_sem(self.etud["etudid"])
|
||||
if decision:
|
||||
autre_sem = sem
|
||||
|
@ -945,15 +967,18 @@ class ApoData(object):
|
|||
s.add(code)
|
||||
continue
|
||||
# associé à une UE:
|
||||
nt = sco_cache.NotesTableCache.get(sem["formsemestre_id"])
|
||||
for ue in nt.get_ues():
|
||||
if code in ue["code_apogee"].split(","):
|
||||
formsemestre = FormSemestre.query.get_or_404(sem["formsemestre_id"])
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
for ue in nt.get_ues_stat_dict():
|
||||
if ue["code_apogee"] and code in ue["code_apogee"].split(","):
|
||||
s.add(code)
|
||||
continue
|
||||
# associé à un module:
|
||||
modimpls = nt.get_modimpls()
|
||||
modimpls = nt.get_modimpls_dict()
|
||||
for modimpl in modimpls:
|
||||
if code in modimpl["module"]["code_apogee"].split(","):
|
||||
if modimpl["module"]["code_apogee"] and code in modimpl["module"][
|
||||
"code_apogee"
|
||||
].split(","):
|
||||
s.add(code)
|
||||
continue
|
||||
# log('codes_by_sem=%s' % pprint.pformat(codes_by_sem))
|
||||
|
|
|
@ -70,13 +70,13 @@ from app.scodoc.sco_exceptions import (
|
|||
)
|
||||
from app.scodoc import html_sco_header
|
||||
from app.scodoc import sco_bulletins_pdf
|
||||
from app.scodoc import sco_excel
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_groups
|
||||
from app.scodoc import sco_groups_view
|
||||
from app.scodoc import sco_permissions_check
|
||||
from app.scodoc import sco_pvjury
|
||||
from app.scodoc import sco_pvpdf
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
|
||||
|
||||
class BaseArchiver(object):
|
||||
|
@ -254,7 +254,7 @@ class BaseArchiver(object):
|
|||
self.initialize()
|
||||
if not scu.is_valid_filename(filename):
|
||||
log('Archiver.get: invalid filename "%s"' % filename)
|
||||
raise ValueError("invalid filename")
|
||||
raise ScoValueError("archive introuvable (déjà supprimée ?)")
|
||||
fname = os.path.join(archive_id, filename)
|
||||
log("reading archive file %s" % fname)
|
||||
with open(fname, "rb") as f:
|
||||
|
@ -405,7 +405,6 @@ def formsemestre_archive(formsemestre_id, group_ids=[]):
|
|||
H = [
|
||||
html_sco_header.html_sem_header(
|
||||
"Archiver les PV et résultats du semestre",
|
||||
sem=sem,
|
||||
javascripts=sco_groups_view.JAVASCRIPTS,
|
||||
cssstyles=sco_groups_view.CSSSTYLES,
|
||||
init_qtip=True,
|
||||
|
@ -524,7 +523,7 @@ def formsemestre_list_archives(formsemestre_id):
|
|||
}
|
||||
L.append(a)
|
||||
|
||||
H = [html_sco_header.html_sem_header("Archive des PV et résultats ", sem)]
|
||||
H = [html_sco_header.html_sem_header("Archive des PV et résultats ")]
|
||||
if not L:
|
||||
H.append("<p>aucune archive enregistrée</p>")
|
||||
else:
|
||||
|
|
|
@ -130,21 +130,31 @@ BACS_SSP = {(t[0], t[1]): t[2:] for t in _BACS}
|
|||
BACS_S = {t[0]: t[2:] for t in _BACS}
|
||||
|
||||
|
||||
class Baccalaureat(object):
|
||||
class Baccalaureat:
|
||||
def __init__(self, bac, specialite=""):
|
||||
self.bac = bac
|
||||
self.specialite = specialite
|
||||
self._abbrev, self._type = BACS_SSP.get((bac, specialite), (None, None))
|
||||
self.bac = bac or ""
|
||||
self.specialite = specialite or ""
|
||||
self._abbrev, self._type = BACS_SSP.get(
|
||||
(self.bac, self.specialite), (None, None)
|
||||
)
|
||||
# Parfois, la specialite commence par la serie: essaye
|
||||
if self._type is None and specialite and specialite.startswith(bac):
|
||||
specialite = specialite[len(bac) :].strip(" -")
|
||||
self._abbrev, self._type = BACS_SSP.get((bac, specialite), (None, None))
|
||||
if (
|
||||
self._type is None
|
||||
and self.specialite
|
||||
and self.specialite.startswith(self.bac)
|
||||
):
|
||||
specialite = self.specialite[len(self.bac) :].strip(" -")
|
||||
self._abbrev, self._type = BACS_SSP.get(
|
||||
(self.bac, specialite), (None, None)
|
||||
)
|
||||
# Cherche la forme serie specialite
|
||||
if self._type is None and specialite:
|
||||
self._abbrev, self._type = BACS_S.get(bac + " " + specialite, (None, None))
|
||||
self._abbrev, self._type = BACS_S.get(
|
||||
self.bac + " " + specialite, (None, None)
|
||||
)
|
||||
# Cherche avec juste le bac, sans specialite
|
||||
if self._type is None:
|
||||
self._abbrev, self._type = BACS_S.get(bac, (None, None))
|
||||
self._abbrev, self._type = BACS_S.get(self.bac, (None, None))
|
||||
|
||||
def abbrev(self):
|
||||
"abbreviation for this bac"
|
||||
|
|
|
@ -28,26 +28,19 @@
|
|||
"""Génération des bulletins de notes
|
||||
|
||||
"""
|
||||
from app.models import formsemestre
|
||||
import time
|
||||
import pprint
|
||||
import email
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.base import MIMEBase
|
||||
from email.header import Header
|
||||
from reportlab.lib.colors import Color
|
||||
import urllib
|
||||
import time
|
||||
|
||||
from flask import g, request
|
||||
from flask import url_for
|
||||
from flask import flash, render_template, url_for
|
||||
from flask_login import current_user
|
||||
from flask_mail import Message
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app import email
|
||||
from app import log
|
||||
from app.but import bulletin_but
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import FormSemestre, Identite, ModuleImplInscription
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
from app.scodoc.sco_exceptions import AccessDenied, ScoValueError
|
||||
from app.scodoc import html_sco_header
|
||||
|
@ -56,9 +49,9 @@ from app.scodoc import sco_abs
|
|||
from app.scodoc import sco_abs_views
|
||||
from app.scodoc import sco_bulletins_generator
|
||||
from app.scodoc import sco_bulletins_json
|
||||
from app.scodoc import sco_bulletins_pdf
|
||||
from app.scodoc import sco_bulletins_xml
|
||||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_etud
|
||||
from app.scodoc import sco_evaluation_db
|
||||
from app.scodoc import sco_formations
|
||||
|
@ -69,7 +62,9 @@ from app.scodoc import sco_photos
|
|||
from app.scodoc import sco_preferences
|
||||
from app.scodoc import sco_pvjury
|
||||
from app.scodoc import sco_users
|
||||
from app import email
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_utils import ModuleType, fmt_note
|
||||
import app.scodoc.notesdb as ndb
|
||||
|
||||
# ----- CLASSES DE BULLETINS DE NOTES
|
||||
from app.scodoc import sco_bulletins_standard
|
||||
|
@ -81,33 +76,20 @@ from app.scodoc import sco_bulletins_legacy
|
|||
from app.scodoc import sco_bulletins_ucac # format expérimental UCAC Cameroun
|
||||
|
||||
|
||||
def make_context_dict(sem, etud):
|
||||
def make_context_dict(formsemestre: FormSemestre, etud: dict) -> dict:
|
||||
"""Construit dictionnaire avec valeurs pour substitution des textes
|
||||
(preferences bul_pdf_*)
|
||||
"""
|
||||
C = sem.copy()
|
||||
C["responsable"] = " ,".join(
|
||||
[
|
||||
sco_users.user_info(responsable_id)["prenomnom"]
|
||||
for responsable_id in sem["responsables"]
|
||||
]
|
||||
)
|
||||
|
||||
annee_debut = sem["date_debut"].split("/")[2]
|
||||
annee_fin = sem["date_fin"].split("/")[2]
|
||||
if annee_debut != annee_fin:
|
||||
annee = "%s - %s" % (annee_debut, annee_fin)
|
||||
else:
|
||||
annee = annee_debut
|
||||
C["anneesem"] = annee
|
||||
C = formsemestre.get_infos_dict()
|
||||
C["responsable"] = formsemestre.responsables_str()
|
||||
C["anneesem"] = C["annee"] # backward compat
|
||||
C.update(etud)
|
||||
# copie preferences
|
||||
# XXX devrait acceder directement à un dict de preferences, à revoir
|
||||
for name in sco_preferences.get_base_preferences().prefs_name:
|
||||
C[name] = sco_preferences.get_preference(name, sem["formsemestre_id"])
|
||||
C[name] = sco_preferences.get_preference(name, formsemestre.id)
|
||||
|
||||
# ajoute groupes et group_0, group_1, ...
|
||||
sco_groups.etud_add_group_infos(etud, sem)
|
||||
sco_groups.etud_add_group_infos(etud, formsemestre.id)
|
||||
C["groupes"] = etud["groupes"]
|
||||
n = 0
|
||||
for partition_id in etud["partitions"]:
|
||||
|
@ -128,7 +110,8 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
Le contenu du dictionnaire dépend des options (rangs, ...)
|
||||
et de la version choisie (short, long, selectedevals).
|
||||
|
||||
Cette fonction est utilisée pour les bulletins HTML et PDF, mais pas ceux en XML.
|
||||
Cette fonction est utilisée pour les bulletins CLASSIQUES (DUT, ...)
|
||||
en HTML et PDF, mais pas ceux en XML.
|
||||
"""
|
||||
from app.scodoc import sco_abs
|
||||
|
||||
|
@ -136,13 +119,14 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
raise ValueError("invalid version code !")
|
||||
|
||||
prefs = sco_preferences.SemPreferences(formsemestre_id)
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id) # > toutes notes
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
if not nt.get_etud_etat(etudid):
|
||||
raise ScoValueError("Etudiant non inscrit à ce semestre")
|
||||
I = scu.DictDefault(defaultvalue="")
|
||||
I["etudid"] = etudid
|
||||
I["formsemestre_id"] = formsemestre_id
|
||||
I["sem"] = nt.sem
|
||||
I["sem"] = formsemestre.get_infos_dict()
|
||||
I["server_name"] = request.url_root
|
||||
|
||||
# Formation et parcours
|
||||
|
@ -185,43 +169,29 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
show_mention=prefs["bul_show_mention"],
|
||||
)
|
||||
|
||||
if dpv:
|
||||
I["decision_sem"] = dpv["decisions"][0]["decision_sem"]
|
||||
else:
|
||||
I["decision_sem"] = ""
|
||||
I.update(infos)
|
||||
|
||||
I["etud_etat_html"] = nt.get_etud_etat_html(etudid)
|
||||
I["etud_etat_html"] = _get_etud_etat_html(
|
||||
formsemestre.etuds_inscriptions[etudid].etat
|
||||
)
|
||||
I["etud_etat"] = nt.get_etud_etat(etudid)
|
||||
I["filigranne"] = ""
|
||||
I["filigranne"] = sco_bulletins_pdf.get_filigranne(
|
||||
I["etud_etat"], prefs, decision_sem=I["decision_sem"]
|
||||
)
|
||||
I["demission"] = ""
|
||||
if I["etud_etat"] == "D":
|
||||
if I["etud_etat"] == scu.DEMISSION:
|
||||
I["demission"] = "(Démission)"
|
||||
I["filigranne"] = "Démission"
|
||||
elif I["etud_etat"] == sco_codes_parcours.DEF:
|
||||
I["demission"] = "(Défaillant)"
|
||||
I["filigranne"] = "Défaillant"
|
||||
elif (prefs["bul_show_temporary"] and not I["decision_sem"]) or prefs[
|
||||
"bul_show_temporary_forced"
|
||||
]:
|
||||
I["filigranne"] = prefs["bul_temporary_txt"]
|
||||
|
||||
# --- Appreciations
|
||||
cnx = ndb.GetDBConnexion()
|
||||
apprecs = sco_etud.appreciations_list(
|
||||
cnx, args={"etudid": etudid, "formsemestre_id": formsemestre_id}
|
||||
)
|
||||
I["appreciations_list"] = apprecs
|
||||
I["appreciations_txt"] = [x["date"] + ": " + x["comment"] for x in apprecs]
|
||||
I["appreciations"] = I[
|
||||
"appreciations_txt"
|
||||
] # deprecated / keep it for backward compat in templates
|
||||
I.update(get_appreciations_list(formsemestre_id, etudid))
|
||||
|
||||
# --- Notes
|
||||
ues = nt.get_ues()
|
||||
modimpls = nt.get_modimpls()
|
||||
ues = nt.get_ues_stat_dict()
|
||||
modimpls = nt.get_modimpls_dict()
|
||||
moy_gen = nt.get_etud_moy_gen(etudid)
|
||||
I["nb_inscrits"] = len(nt.rangs)
|
||||
I["nb_inscrits"] = len(nt.etud_moy_gen_ranks)
|
||||
I["moy_gen"] = scu.fmt_note(moy_gen)
|
||||
I["moy_min"] = scu.fmt_note(nt.moy_min)
|
||||
I["moy_max"] = scu.fmt_note(nt.moy_max)
|
||||
|
@ -261,23 +231,24 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
# notes en attente dans ce semestre
|
||||
rang = scu.RANG_ATTENTE_STR
|
||||
rang_gr = scu.DictDefault(defaultvalue=scu.RANG_ATTENTE_STR)
|
||||
inscriptions_counts = nt.get_inscriptions_counts()
|
||||
I["rang"] = rang
|
||||
I["rang_gr"] = rang_gr
|
||||
I["gr_name"] = gr_name
|
||||
I["ninscrits_gr"] = ninscrits_gr
|
||||
I["nbetuds"] = len(nt.rangs)
|
||||
I["nb_demissions"] = nt.nb_demissions
|
||||
I["nb_defaillants"] = nt.nb_defaillants
|
||||
I["nbetuds"] = len(nt.etud_moy_gen_ranks)
|
||||
I["nb_demissions"] = inscriptions_counts[scu.DEMISSION]
|
||||
I["nb_defaillants"] = inscriptions_counts[scu.DEF]
|
||||
if prefs["bul_show_rangs"]:
|
||||
I["rang_nt"] = "%s / %d" % (
|
||||
rang,
|
||||
I["nbetuds"] - nt.nb_demissions - nt.nb_defaillants,
|
||||
inscriptions_counts[scu.INSCRIT],
|
||||
)
|
||||
I["rang_txt"] = "Rang " + I["rang_nt"]
|
||||
else:
|
||||
I["rang_nt"], I["rang_txt"] = "", ""
|
||||
I["note_max"] = 20.0 # notes toujours sur 20
|
||||
I["bonus_sport_culture"] = nt.bonus[etudid]
|
||||
I["bonus_sport_culture"] = nt.bonus[etudid] if nt.bonus is not None else 0.0
|
||||
# Liste les UE / modules /evals
|
||||
I["ues"] = []
|
||||
I["matieres_modules"] = {}
|
||||
|
@ -285,22 +256,37 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
for ue in ues:
|
||||
u = ue.copy()
|
||||
ue_status = nt.get_etud_ue_status(etudid, ue["ue_id"])
|
||||
if (
|
||||
ModuleImplInscription.nb_inscriptions_dans_ue(
|
||||
formsemestre_id, etudid, ue["ue_id"]
|
||||
)
|
||||
== 0
|
||||
) and not ue_status["is_capitalized"]:
|
||||
# saute les UE où l'on est pas inscrit et n'avons pas de capitalisation
|
||||
continue
|
||||
|
||||
u["ue_status"] = ue_status # { 'moy', 'coef_ue', ...}
|
||||
if ue["type"] != sco_codes_parcours.UE_SPORT:
|
||||
u["cur_moy_ue_txt"] = scu.fmt_note(ue_status["cur_moy_ue"])
|
||||
else:
|
||||
x = scu.fmt_note(nt.bonus[etudid], keep_numeric=True)
|
||||
if isinstance(x, str):
|
||||
u["cur_moy_ue_txt"] = "pas de bonus"
|
||||
if nt.bonus is not None:
|
||||
x = scu.fmt_note(nt.bonus[etudid], keep_numeric=True)
|
||||
else:
|
||||
u["cur_moy_ue_txt"] = "bonus de %.3g points" % x
|
||||
x = ""
|
||||
if isinstance(x, str):
|
||||
if nt.bonus_ues is None:
|
||||
u["cur_moy_ue_txt"] = "pas de bonus"
|
||||
else:
|
||||
u["cur_moy_ue_txt"] = "bonus appliqué sur les UEs"
|
||||
else:
|
||||
u["cur_moy_ue_txt"] = f"bonus de {fmt_note(x)} points"
|
||||
if nt.bonus_ues is not None:
|
||||
u["cur_moy_ue_txt"] += " (+ues)"
|
||||
u["moy_ue_txt"] = scu.fmt_note(ue_status["moy"])
|
||||
if ue_status["coef_ue"] != None:
|
||||
u["coef_ue_txt"] = scu.fmt_coef(ue_status["coef_ue"])
|
||||
else:
|
||||
# C'est un bug:
|
||||
log("u=" + pprint.pformat(u))
|
||||
raise Exception("invalid None coef for ue")
|
||||
u["coef_ue_txt"] = "-"
|
||||
|
||||
if (
|
||||
dpv
|
||||
|
@ -330,29 +316,30 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
] = [] # modules de l'UE capitalisée (liste vide si pas capitalisée)
|
||||
if ue_status["is_capitalized"]:
|
||||
sem_origin = sco_formsemestre.get_formsemestre(ue_status["formsemestre_id"])
|
||||
u["ue_descr_txt"] = "Capitalisée le %s" % ndb.DateISOtoDMY(
|
||||
u["ue_descr_txt"] = "capitalisée le %s" % ndb.DateISOtoDMY(
|
||||
ue_status["event_date"]
|
||||
)
|
||||
u[
|
||||
"ue_descr_html"
|
||||
] = '<a href="formsemestre_bulletinetud?formsemestre_id=%s&etudid=%s" title="%s" class="bull_link">%s</a>' % (
|
||||
sem_origin["formsemestre_id"],
|
||||
etudid,
|
||||
sem_origin["titreannee"],
|
||||
u["ue_descr_txt"],
|
||||
)
|
||||
# log('cap details %s' % ue_status['moy'])
|
||||
] = f"""<a href="{ url_for( 'notes.formsemestre_bulletinetud',
|
||||
scodoc_dept=g.scodoc_dept, formsemestre_id=sem_origin['formsemestre_id'], etudid=etudid)}"
|
||||
title="{sem_origin['titreannee']}" class="bull_link"
|
||||
>{u["ue_descr_txt"]} pouet</a>
|
||||
"""
|
||||
if ue_status["moy"] != "NA" and ue_status["formsemestre_id"]:
|
||||
# detail des modules de l'UE capitalisee
|
||||
nt_cap = sco_cache.NotesTableCache.get(
|
||||
# détail des modules de l'UE capitalisée
|
||||
formsemestre_cap = FormSemestre.query.get_or_404(
|
||||
ue_status["formsemestre_id"]
|
||||
) # > toutes notes
|
||||
)
|
||||
nt_cap: NotesTableCompat = res_sem.load_formsemestre_results(
|
||||
formsemestre_cap
|
||||
)
|
||||
|
||||
u["modules_capitalized"], _ = _ue_mod_bulletin(
|
||||
etudid,
|
||||
formsemestre_id,
|
||||
ue_status["capitalized_ue_id"],
|
||||
nt_cap.get_modimpls(),
|
||||
nt_cap.get_modimpls_dict(),
|
||||
nt_cap,
|
||||
version,
|
||||
)
|
||||
|
@ -361,7 +348,7 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
)
|
||||
else:
|
||||
if prefs["bul_show_ue_rangs"] and ue["type"] != sco_codes_parcours.UE_SPORT:
|
||||
if ue_attente: # nt.get_moduleimpls_attente():
|
||||
if ue_attente or nt.ue_rangs[ue["ue_id"]][0] is None:
|
||||
u["ue_descr_txt"] = "%s/%s" % (
|
||||
scu.RANG_ATTENTE_STR,
|
||||
nt.ue_rangs[ue["ue_id"]][1],
|
||||
|
@ -379,16 +366,44 @@ def formsemestre_bulletinetud_dict(formsemestre_id, etudid, version="long"):
|
|||
I["ues"].append(u) # ne montre pas les UE si non inscrit
|
||||
|
||||
# Accès par matieres
|
||||
# En #sco92, pas d'information
|
||||
I["matieres_modules"].update(_sort_mod_by_matiere(modules, nt, etudid))
|
||||
|
||||
#
|
||||
C = make_context_dict(I["sem"], I["etud"])
|
||||
C = make_context_dict(formsemestre, I["etud"])
|
||||
C.update(I)
|
||||
#
|
||||
# log( 'C = \n%s\n' % pprint.pformat(C) ) # tres pratique pour voir toutes les infos dispo
|
||||
return C
|
||||
|
||||
|
||||
def get_appreciations_list(formsemestre_id: int, etudid: int) -> dict:
|
||||
"""Appréciations pour cet étudiant dans ce semestre"""
|
||||
cnx = ndb.GetDBConnexion()
|
||||
apprecs = sco_etud.appreciations_list(
|
||||
cnx, args={"etudid": etudid, "formsemestre_id": formsemestre_id}
|
||||
)
|
||||
d = {
|
||||
"appreciations_list": apprecs,
|
||||
"appreciations_txt": [x["date"] + ": " + x["comment"] for x in apprecs],
|
||||
}
|
||||
# deprecated / keep it for backward compat in templates:
|
||||
d["appreciations"] = d["appreciations_txt"]
|
||||
return d
|
||||
|
||||
|
||||
def _get_etud_etat_html(etat: str) -> str:
|
||||
"""chaine html représentant l'état (backward compat sco7)"""
|
||||
if etat == scu.INSCRIT: # "I"
|
||||
return ""
|
||||
elif etat == scu.DEMISSION: # "D"
|
||||
return ' <font color="red">(DEMISSIONNAIRE)</font> '
|
||||
elif etat == scu.DEF: # "DEF"
|
||||
return ' <font color="red">(DEFAILLANT)</font> '
|
||||
else:
|
||||
return ' <font color="red">(%s)</font> ' % etat
|
||||
|
||||
|
||||
def _sort_mod_by_matiere(modlist, nt, etudid):
|
||||
matmod = {} # { matiere_id : [] }
|
||||
for mod in modlist:
|
||||
|
@ -404,7 +419,9 @@ def _sort_mod_by_matiere(modlist, nt, etudid):
|
|||
return matmod
|
||||
|
||||
|
||||
def _ue_mod_bulletin(etudid, formsemestre_id, ue_id, modimpls, nt, version):
|
||||
def _ue_mod_bulletin(
|
||||
etudid, formsemestre_id, ue_id, modimpls, nt: NotesTableCompat, version
|
||||
):
|
||||
"""Infos sur les modules (et évaluations) dans une UE
|
||||
(ajoute les informations aux modimpls)
|
||||
Result: liste de modules de l'UE avec les infos dans chacun (seulement ceux où l'étudiant est inscrit).
|
||||
|
@ -479,7 +496,7 @@ def _ue_mod_bulletin(etudid, formsemestre_id, ue_id, modimpls, nt, version):
|
|||
)
|
||||
if sco_preferences.get_preference("bul_show_codemodules", formsemestre_id):
|
||||
mod["code"] = modimpl["module"]["code"]
|
||||
mod["code_html"] = link_mod + mod["code"] + "</a>"
|
||||
mod["code_html"] = link_mod + (mod["code"] or "") + "</a>"
|
||||
else:
|
||||
mod["code"] = mod["code_html"] = ""
|
||||
mod["name"] = (
|
||||
|
@ -497,7 +514,7 @@ def _ue_mod_bulletin(etudid, formsemestre_id, ue_id, modimpls, nt, version):
|
|||
% (modimpl["moduleimpl_id"], mod_descr)
|
||||
)
|
||||
if sco_preferences.get_preference("bul_show_codemodules", formsemestre_id):
|
||||
mod["code_txt"] = modimpl["module"]["code"]
|
||||
mod["code_txt"] = modimpl["module"]["code"] or ""
|
||||
mod["code_html"] = link_mod + mod["code_txt"] + "</a>"
|
||||
else:
|
||||
mod["code_txt"] = ""
|
||||
|
@ -582,14 +599,22 @@ def _ue_mod_bulletin(etudid, formsemestre_id, ue_id, modimpls, nt, version):
|
|||
e["note_txt"] = e["note_html"] = ""
|
||||
e["coef_txt"] = scu.fmt_coef(e["coefficient"])
|
||||
# Classement
|
||||
if bul_show_mod_rangs and mod["mod_moy_txt"] != "-" and not is_malus:
|
||||
if (
|
||||
bul_show_mod_rangs
|
||||
and (nt.mod_rangs is not None)
|
||||
and mod["mod_moy_txt"] != "-"
|
||||
and not is_malus
|
||||
):
|
||||
rg = nt.mod_rangs[modimpl["moduleimpl_id"]]
|
||||
if mod_attente: # nt.get_moduleimpls_attente():
|
||||
mod["mod_rang"] = scu.RANG_ATTENTE_STR
|
||||
if rg[0] is None:
|
||||
mod["mod_rang_txt"] = ""
|
||||
else:
|
||||
mod["mod_rang"] = rg[0][etudid]
|
||||
mod["mod_eff"] = rg[1] # effectif dans ce module
|
||||
mod["mod_rang_txt"] = "%s/%s" % (mod["mod_rang"], mod["mod_eff"])
|
||||
if mod_attente: # nt.get_moduleimpls_attente():
|
||||
mod["mod_rang"] = scu.RANG_ATTENTE_STR
|
||||
else:
|
||||
mod["mod_rang"] = rg[0][etudid]
|
||||
mod["mod_eff"] = rg[1] # effectif dans ce module
|
||||
mod["mod_rang_txt"] = "%s/%s" % (mod["mod_rang"], mod["mod_eff"])
|
||||
else:
|
||||
mod["mod_rang_txt"] = ""
|
||||
if mod_attente:
|
||||
|
@ -644,6 +669,7 @@ def etud_descr_situation_semestre(
|
|||
descr_defaillance : "Défaillant" ou vide si non défaillant.
|
||||
decision_jury : "Validé", "Ajourné", ... (code semestre)
|
||||
descr_decision_jury : "Décision jury: Validé" (une phrase)
|
||||
decision_sem :
|
||||
decisions_ue : noms (acronymes) des UE validées, séparées par des virgules.
|
||||
descr_decisions_ue : ' UE acquises: UE1, UE2', ou vide si pas de dec. ou si pas show_uevalid
|
||||
descr_mention : 'Mention Bien', ou vide si pas de mention ou si pas show_mention
|
||||
|
@ -653,7 +679,7 @@ def etud_descr_situation_semestre(
|
|||
|
||||
# --- Situation et décisions jury
|
||||
|
||||
# demission/inscription ?
|
||||
# démission/inscription ?
|
||||
events = sco_etud.scolar_events_list(
|
||||
cnx, args={"etudid": etudid, "formsemestre_id": formsemestre_id}
|
||||
)
|
||||
|
@ -720,11 +746,15 @@ def etud_descr_situation_semestre(
|
|||
infos["situation"] += " " + infos["descr_defaillance"]
|
||||
|
||||
dpv = sco_pvjury.dict_pvjury(formsemestre_id, etudids=[etudid])
|
||||
if dpv:
|
||||
infos["decision_sem"] = dpv["decisions"][0]["decision_sem"]
|
||||
else:
|
||||
infos["decision_sem"] = ""
|
||||
|
||||
if not show_decisions:
|
||||
return infos, dpv
|
||||
|
||||
# Decisions de jury:
|
||||
# Décisions de jury:
|
||||
pv = dpv["decisions"][0]
|
||||
dec = ""
|
||||
if pv["decision_sem_descr"]:
|
||||
|
@ -761,27 +791,23 @@ def etud_descr_situation_semestre(
|
|||
|
||||
# ------ Page bulletin
|
||||
def formsemestre_bulletinetud(
|
||||
etudid=None,
|
||||
etud: Identite = None,
|
||||
formsemestre_id=None,
|
||||
format="html",
|
||||
format=None,
|
||||
version="long",
|
||||
xml_with_decisions=False,
|
||||
force_publishing=False, # force publication meme si semestre non publie sur "portail"
|
||||
prefer_mail_perso=False,
|
||||
):
|
||||
"page bulletin de notes"
|
||||
try:
|
||||
etud = sco_etud.get_etud_info(filled=True)[0]
|
||||
etudid = etud["etudid"]
|
||||
except:
|
||||
sco_etud.log_unknown_etud()
|
||||
raise ScoValueError("étudiant inconnu")
|
||||
# API, donc erreurs admises en ScoValueError
|
||||
sem = sco_formsemestre.get_formsemestre(formsemestre_id, raise_soft_exc=True)
|
||||
format = format or "html"
|
||||
formsemestre: FormSemestre = FormSemestre.query.get(formsemestre_id)
|
||||
if not formsemestre:
|
||||
raise ScoValueError(f"semestre {formsemestre_id} inconnu !")
|
||||
|
||||
bulletin = do_formsemestre_bulletinetud(
|
||||
formsemestre_id,
|
||||
etudid,
|
||||
formsemestre,
|
||||
etud.id,
|
||||
format=format,
|
||||
version=version,
|
||||
xml_with_decisions=xml_with_decisions,
|
||||
|
@ -789,52 +815,25 @@ def formsemestre_bulletinetud(
|
|||
prefer_mail_perso=prefer_mail_perso,
|
||||
)[0]
|
||||
if format not in {"html", "pdfmail"}:
|
||||
filename = scu.bul_filename(sem, etud, format)
|
||||
filename = scu.bul_filename(formsemestre, etud, format)
|
||||
return scu.send_file(bulletin, filename, mime=scu.get_mime_suffix(format)[0])
|
||||
|
||||
sem = sco_formsemestre.get_formsemestre(formsemestre_id)
|
||||
elif format == "pdfmail":
|
||||
return ""
|
||||
H = [
|
||||
_formsemestre_bulletinetud_header_html(
|
||||
etud, etudid, sem, formsemestre_id, format, version
|
||||
),
|
||||
_formsemestre_bulletinetud_header_html(etud, formsemestre, format, version),
|
||||
bulletin,
|
||||
render_template(
|
||||
"bul_foot.html",
|
||||
appreciations=None, # déjà affichées
|
||||
css_class="bul_classic_foot",
|
||||
etud=etud,
|
||||
formsemestre=formsemestre,
|
||||
inscription_courante=etud.inscription_courante(),
|
||||
inscription_str=etud.inscription_descr()["inscription_str"],
|
||||
),
|
||||
html_sco_header.sco_footer(),
|
||||
]
|
||||
|
||||
H.append("""<p>Situation actuelle: """)
|
||||
if etud["inscription_formsemestre_id"]:
|
||||
H.append(
|
||||
f"""<a class="stdlink" href="{url_for(
|
||||
"notes.formsemestre_status",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formsemestre_id=etud["inscription_formsemestre_id"])
|
||||
}">"""
|
||||
)
|
||||
H.append(etud["inscriptionstr"])
|
||||
if etud["inscription_formsemestre_id"]:
|
||||
H.append("""</a>""")
|
||||
H.append("""</p>""")
|
||||
if sem["modalite"] == "EXT":
|
||||
H.append(
|
||||
"""<p><a
|
||||
href="formsemestre_ext_edit_ue_validations?formsemestre_id=%s&etudid=%s"
|
||||
class="stdlink">
|
||||
Editer les validations d'UE dans ce semestre extérieur
|
||||
</a></p>"""
|
||||
% (formsemestre_id, etudid)
|
||||
)
|
||||
# Place du diagramme radar
|
||||
H.append(
|
||||
"""<form id="params">
|
||||
<input type="hidden" name="etudid" id="etudid" value="%s"/>
|
||||
<input type="hidden" name="formsemestre_id" id="formsemestre_id" value="%s"/>
|
||||
</form>"""
|
||||
% (etudid, formsemestre_id)
|
||||
)
|
||||
H.append('<div id="radar_bulletin"></div>')
|
||||
|
||||
# --- Pied de page
|
||||
H.append(html_sco_header.sco_footer())
|
||||
|
||||
return "".join(H)
|
||||
|
||||
|
||||
|
@ -849,23 +848,23 @@ def can_send_bulletin_by_mail(formsemestre_id):
|
|||
|
||||
|
||||
def do_formsemestre_bulletinetud(
|
||||
formsemestre_id,
|
||||
etudid,
|
||||
formsemestre: FormSemestre,
|
||||
etudid: int,
|
||||
version="long", # short, long, selectedevals
|
||||
format="html",
|
||||
nohtml=False,
|
||||
xml_with_decisions=False, # force decisions dans XML
|
||||
force_publishing=False, # force publication meme si semestre non publie sur "portail"
|
||||
prefer_mail_perso=False, # mails envoyes sur adresse perso si non vide
|
||||
format=None,
|
||||
xml_with_decisions=False, # force décisions dans XML
|
||||
force_publishing=False, # force publication meme si semestre non publié sur "portail"
|
||||
prefer_mail_perso=False, # mails envoyés sur adresse perso si non vide
|
||||
):
|
||||
"""Génère le bulletin au format demandé.
|
||||
Retourne: (bul, filigranne)
|
||||
où bul est str ou bytes au format demandé (html, pdf, pdfmail, pdfpart, xml, json)
|
||||
et filigranne est un message à placer en "filigranne" (eg "Provisoire").
|
||||
"""
|
||||
format = format or "html"
|
||||
if format == "xml":
|
||||
bul = sco_bulletins_xml.make_xml_formsemestre_bulletinetud(
|
||||
formsemestre_id,
|
||||
formsemestre.id,
|
||||
etudid,
|
||||
xml_with_decisions=xml_with_decisions,
|
||||
force_publishing=force_publishing,
|
||||
|
@ -876,7 +875,7 @@ def do_formsemestre_bulletinetud(
|
|||
|
||||
elif format == "json":
|
||||
bul = sco_bulletins_json.make_json_formsemestre_bulletinetud(
|
||||
formsemestre_id,
|
||||
formsemestre.id,
|
||||
etudid,
|
||||
xml_with_decisions=xml_with_decisions,
|
||||
force_publishing=force_publishing,
|
||||
|
@ -884,7 +883,12 @@ def do_formsemestre_bulletinetud(
|
|||
)
|
||||
return bul, ""
|
||||
|
||||
I = formsemestre_bulletinetud_dict(formsemestre_id, etudid)
|
||||
if formsemestre.formation.is_apc():
|
||||
etudiant = Identite.query.get(etudid)
|
||||
r = bulletin_but.BulletinBUT(formsemestre)
|
||||
I = r.bulletin_etud_complet(etudiant, version=version)
|
||||
else:
|
||||
I = formsemestre_bulletinetud_dict(formsemestre.id, etudid)
|
||||
etud = I["etud"]
|
||||
|
||||
if format == "html":
|
||||
|
@ -911,16 +915,9 @@ def do_formsemestre_bulletinetud(
|
|||
elif format == "pdfmail":
|
||||
# format pdfmail: envoie le pdf par mail a l'etud, et affiche le html
|
||||
# check permission
|
||||
if not can_send_bulletin_by_mail(formsemestre_id):
|
||||
if not can_send_bulletin_by_mail(formsemestre.id):
|
||||
raise AccessDenied("Vous n'avez pas le droit d'effectuer cette opération !")
|
||||
|
||||
if nohtml:
|
||||
htm = "" # speed up if html version not needed
|
||||
else:
|
||||
htm, _ = sco_bulletins_generator.make_formsemestre_bulletinetud(
|
||||
I, version=version, format="html"
|
||||
)
|
||||
|
||||
pdfdata, filename = sco_bulletins_generator.make_formsemestre_bulletinetud(
|
||||
I, version=version, format="pdf"
|
||||
)
|
||||
|
@ -928,31 +925,18 @@ def do_formsemestre_bulletinetud(
|
|||
if prefer_mail_perso:
|
||||
recipient_addr = etud.get("emailperso", "") or etud.get("email", "")
|
||||
else:
|
||||
recipient_addr = etud["email_default"]
|
||||
recipient_addr = etud.get("email", "") or etud.get("emailperso", "")
|
||||
|
||||
if not recipient_addr:
|
||||
if nohtml:
|
||||
h = "" # permet de compter les non-envois
|
||||
else:
|
||||
h = (
|
||||
"<div class=\"boldredmsg\">%s n'a pas d'adresse e-mail !</div>"
|
||||
% etud["nomprenom"]
|
||||
) + htm
|
||||
return h, I["filigranne"]
|
||||
#
|
||||
mail_bulletin(formsemestre_id, I, pdfdata, filename, recipient_addr)
|
||||
emaillink = '<a class="stdlink" href="mailto:%s">%s</a>' % (
|
||||
recipient_addr,
|
||||
recipient_addr,
|
||||
)
|
||||
return (
|
||||
('<div class="head_message">Message mail envoyé à %s</div>' % (emaillink))
|
||||
+ htm,
|
||||
I["filigranne"],
|
||||
)
|
||||
flash(f"{etud['nomprenom']} n'a pas d'adresse e-mail !")
|
||||
return False, I["filigranne"]
|
||||
else:
|
||||
mail_bulletin(formsemestre.id, I, pdfdata, filename, recipient_addr)
|
||||
flash(f"mail envoyé à {recipient_addr}")
|
||||
|
||||
else:
|
||||
raise ValueError("do_formsemestre_bulletinetud: invalid format (%s)" % format)
|
||||
return True, I["filigranne"]
|
||||
|
||||
raise ValueError("do_formsemestre_bulletinetud: invalid format (%s)" % format)
|
||||
|
||||
|
||||
def mail_bulletin(formsemestre_id, I, pdfdata, filename, recipient_addr):
|
||||
|
@ -968,11 +952,16 @@ def mail_bulletin(formsemestre_id, I, pdfdata, filename, recipient_addr):
|
|||
intro_mail = sco_preferences.get_preference("bul_intro_mail", formsemestre_id)
|
||||
|
||||
if intro_mail:
|
||||
hea = intro_mail % {
|
||||
"nomprenom": etud["nomprenom"],
|
||||
"dept": dept,
|
||||
"webmaster": webmaster,
|
||||
}
|
||||
try:
|
||||
hea = intro_mail % {
|
||||
"nomprenom": etud["nomprenom"],
|
||||
"dept": dept,
|
||||
"webmaster": webmaster,
|
||||
}
|
||||
except KeyError as e:
|
||||
raise ScoValueError(
|
||||
"format 'Message d'accompagnement' (bul_intro_mail) invalide, revoir les réglages dans les préférences"
|
||||
) from e
|
||||
else:
|
||||
hea = ""
|
||||
|
||||
|
@ -988,81 +977,32 @@ def mail_bulletin(formsemestre_id, I, pdfdata, filename, recipient_addr):
|
|||
bcc = copy_addr.strip()
|
||||
else:
|
||||
bcc = ""
|
||||
msg = Message(subject, sender=sender, recipients=recipients, bcc=[bcc])
|
||||
msg.body = hea
|
||||
|
||||
# Attach pdf
|
||||
msg.attach(filename, scu.PDF_MIMETYPE, pdfdata)
|
||||
log("mail bulletin a %s" % recipient_addr)
|
||||
email.send_message(msg)
|
||||
email.send_email(
|
||||
subject,
|
||||
sender,
|
||||
recipients,
|
||||
bcc=[bcc],
|
||||
text_body=hea,
|
||||
attachments=[
|
||||
{"filename": filename, "mimetype": scu.PDF_MIMETYPE, "data": pdfdata}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _formsemestre_bulletinetud_header_html(
|
||||
etud,
|
||||
etudid,
|
||||
sem,
|
||||
formsemestre_id=None,
|
||||
format=None,
|
||||
version=None,
|
||||
):
|
||||
H = [
|
||||
html_sco_header.sco_header(
|
||||
page_title="Bulletin de %(nomprenom)s" % etud,
|
||||
javascripts=[
|
||||
"js/bulletin.js",
|
||||
"libjs/d3.v3.min.js",
|
||||
"js/radar_bulletin.js",
|
||||
],
|
||||
cssstyles=["css/radar_bulletin.css"],
|
||||
),
|
||||
"""<table class="bull_head"><tr><td>
|
||||
<h2><a class="discretelink" href="%s">%s</a></h2>
|
||||
"""
|
||||
% (
|
||||
url_for(
|
||||
"scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=etud["etudid"]
|
||||
),
|
||||
etud["nomprenom"],
|
||||
),
|
||||
"""
|
||||
<form name="f" method="GET" action="%s">"""
|
||||
% request.base_url,
|
||||
f"""Bulletin <span class="bull_liensemestre"><a href="{
|
||||
url_for("notes.formsemestre_status",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formsemestre_id=sem["formsemestre_id"])}
|
||||
">{sem["titremois"]}</a></span>
|
||||
<br/>"""
|
||||
% sem,
|
||||
"""<table><tr>""",
|
||||
"""<td>établi le %s (notes sur 20)</td>""" % time.strftime("%d/%m/%Y à %Hh%M"),
|
||||
"""<td><span class="rightjust">
|
||||
<input type="hidden" name="formsemestre_id" value="%s"></input>"""
|
||||
% formsemestre_id,
|
||||
"""<input type="hidden" name="etudid" value="%s"></input>""" % etudid,
|
||||
"""<input type="hidden" name="format" value="%s"></input>""" % format,
|
||||
"""<select name="version" onchange="document.f.submit()" class="noprint">""",
|
||||
]
|
||||
for (v, e) in (
|
||||
("short", "Version courte"),
|
||||
("selectedevals", "Version intermédiaire"),
|
||||
("long", "Version complète"),
|
||||
):
|
||||
if v == version:
|
||||
selected = " selected"
|
||||
else:
|
||||
selected = ""
|
||||
H.append('<option value="%s"%s>%s</option>' % (v, selected, e))
|
||||
H.append("""</select></td>""")
|
||||
# Menu
|
||||
endpoint = "notes.formsemestre_bulletinetud"
|
||||
|
||||
menuBul = [
|
||||
def make_menu_autres_operations(
|
||||
formsemestre: FormSemestre, etud: Identite, endpoint: str, version: str
|
||||
) -> str:
|
||||
etud_email = etud.get_first_email() or ""
|
||||
etud_perso = etud.get_first_email("emailperso") or ""
|
||||
menu_items = [
|
||||
{
|
||||
"title": "Réglages bulletins",
|
||||
"endpoint": "notes.formsemestre_edit_options",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
# "target_url": url_for(
|
||||
# "notes.formsemestre_bulletinetud",
|
||||
# scodoc_dept=g.scodoc_dept,
|
||||
|
@ -1070,54 +1010,52 @@ def _formsemestre_bulletinetud_header_html(
|
|||
# etudid=etudid,
|
||||
# ),
|
||||
},
|
||||
"enabled": (current_user.id in sem["responsables"])
|
||||
or current_user.has_permission(Permission.ScoImplement),
|
||||
"enabled": formsemestre.can_be_edited_by(current_user),
|
||||
},
|
||||
{
|
||||
"title": 'Version papier (pdf, format "%s")'
|
||||
% sco_bulletins_generator.bulletin_get_class_name_displayed(
|
||||
formsemestre_id
|
||||
formsemestre.id
|
||||
),
|
||||
"endpoint": endpoint,
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
"version": version,
|
||||
"format": "pdf",
|
||||
},
|
||||
},
|
||||
{
|
||||
"title": "Envoi par mail à %s" % etud["email"],
|
||||
"title": f"Envoi par mail à {etud_email}",
|
||||
"endpoint": endpoint,
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
"version": version,
|
||||
"format": "pdfmail",
|
||||
},
|
||||
# possible slt si on a un mail...
|
||||
"enabled": etud["email"] and can_send_bulletin_by_mail(formsemestre_id),
|
||||
"enabled": etud_email and can_send_bulletin_by_mail(formsemestre.id),
|
||||
},
|
||||
{
|
||||
"title": "Envoi par mail à %s (adr. personnelle)" % etud["emailperso"],
|
||||
"title": f"Envoi par mail à {etud_perso} (adr. personnelle)",
|
||||
"endpoint": endpoint,
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
"version": version,
|
||||
"format": "pdfmail",
|
||||
"prefer_mail_perso": 1,
|
||||
},
|
||||
# possible slt si on a un mail...
|
||||
"enabled": etud["emailperso"]
|
||||
and can_send_bulletin_by_mail(formsemestre_id),
|
||||
"enabled": etud_perso and can_send_bulletin_by_mail(formsemestre.id),
|
||||
},
|
||||
{
|
||||
"title": "Version json",
|
||||
"endpoint": endpoint,
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
"version": version,
|
||||
"format": "json",
|
||||
},
|
||||
|
@ -1126,8 +1064,8 @@ def _formsemestre_bulletinetud_header_html(
|
|||
"title": "Version XML",
|
||||
"endpoint": endpoint,
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
"version": version,
|
||||
"format": "xml",
|
||||
},
|
||||
|
@ -1136,20 +1074,20 @@ def _formsemestre_bulletinetud_header_html(
|
|||
"title": "Ajouter une appréciation",
|
||||
"endpoint": "notes.appreciation_add_form",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": (
|
||||
(current_user.id in sem["responsables"])
|
||||
or (current_user.has_permission(Permission.ScoEtudInscrit))
|
||||
formsemestre.can_be_edited_by(current_user)
|
||||
or current_user.has_permission(Permission.ScoEtudInscrit)
|
||||
),
|
||||
},
|
||||
{
|
||||
"title": "Enregistrer un semestre effectué ailleurs",
|
||||
"endpoint": "notes.formsemestre_ext_create_form",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": current_user.has_permission(Permission.ScoImplement),
|
||||
},
|
||||
|
@ -1157,71 +1095,72 @@ def _formsemestre_bulletinetud_header_html(
|
|||
"title": "Enregistrer une validation d'UE antérieure",
|
||||
"endpoint": "notes.formsemestre_validate_previous_ue",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre_id),
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre.id),
|
||||
},
|
||||
{
|
||||
"title": "Enregistrer note d'une UE externe",
|
||||
"endpoint": "notes.external_ue_create_form",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre_id),
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre.id),
|
||||
},
|
||||
{
|
||||
"title": "Entrer décisions jury",
|
||||
"endpoint": "notes.formsemestre_validation_etud_form",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre_id),
|
||||
"enabled": sco_permissions_check.can_validate_sem(formsemestre.id),
|
||||
},
|
||||
{
|
||||
"title": "Editer PV jury",
|
||||
"title": "Éditer PV jury",
|
||||
"endpoint": "notes.formsemestre_pvjury_pdf",
|
||||
"args": {
|
||||
"formsemestre_id": formsemestre_id,
|
||||
"etudid": etudid,
|
||||
"formsemestre_id": formsemestre.id,
|
||||
"etudid": etud.id,
|
||||
},
|
||||
"enabled": True,
|
||||
},
|
||||
]
|
||||
return htmlutils.make_menu("Autres opérations", menu_items, alone=True)
|
||||
|
||||
H.append("""<td class="bulletin_menubar"><div class="bulletin_menubar">""")
|
||||
H.append(htmlutils.make_menu("Autres opérations", menuBul, alone=True))
|
||||
H.append("""</div></td>""")
|
||||
H.append(
|
||||
'<td> <a href="%s">%s</a></td>'
|
||||
% (
|
||||
url_for(
|
||||
"notes.formsemestre_bulletinetud",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formsemestre_id=formsemestre_id,
|
||||
etudid=etudid,
|
||||
format="pdf",
|
||||
|
||||
def _formsemestre_bulletinetud_header_html(
|
||||
etud,
|
||||
formsemestre: FormSemestre,
|
||||
format=None,
|
||||
version=None,
|
||||
):
|
||||
H = [
|
||||
html_sco_header.sco_header(
|
||||
page_title=f"Bulletin de {etud.nomprenom}",
|
||||
javascripts=[
|
||||
"js/bulletin.js",
|
||||
"libjs/d3.v3.min.js",
|
||||
"js/radar_bulletin.js",
|
||||
],
|
||||
cssstyles=["css/radar_bulletin.css"],
|
||||
),
|
||||
render_template(
|
||||
"bul_head.html",
|
||||
etud=etud,
|
||||
format=format,
|
||||
formsemestre=formsemestre,
|
||||
menu_autres_operations=make_menu_autres_operations(
|
||||
etud=etud,
|
||||
formsemestre=formsemestre,
|
||||
endpoint="notes.formsemestre_bulletinetud",
|
||||
version=version,
|
||||
),
|
||||
scu.ICON_PDF,
|
||||
)
|
||||
)
|
||||
H.append("""</tr></table>""")
|
||||
#
|
||||
H.append(
|
||||
"""</form></span></td><td class="bull_photo"><a href="%s">%s</a>
|
||||
"""
|
||||
% (
|
||||
url_for("scolar.ficheEtud", scodoc_dept=g.scodoc_dept, etudid=etudid),
|
||||
sco_photos.etud_photo_html(etud, title="fiche de " + etud["nom"]),
|
||||
)
|
||||
)
|
||||
H.append(
|
||||
"""</td></tr>
|
||||
</table>
|
||||
"""
|
||||
)
|
||||
|
||||
return "".join(H)
|
||||
scu=scu,
|
||||
time=time,
|
||||
version=version,
|
||||
),
|
||||
]
|
||||
return "\n".join(H)
|
||||
|
|
|
@ -49,7 +49,14 @@ import traceback
|
|||
|
||||
|
||||
import reportlab
|
||||
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Frame, PageBreak
|
||||
from reportlab.platypus import (
|
||||
SimpleDocTemplate,
|
||||
DocIf,
|
||||
Paragraph,
|
||||
Spacer,
|
||||
Frame,
|
||||
PageBreak,
|
||||
)
|
||||
from reportlab.platypus import Table, TableStyle, Image, KeepInFrame
|
||||
|
||||
from flask import request
|
||||
|
@ -63,48 +70,16 @@ from app.scodoc import sco_pdf
|
|||
from app.scodoc.sco_pdf import PDFLOCK
|
||||
import sco_version
|
||||
|
||||
# Liste des types des classes de générateurs de bulletins PDF:
|
||||
BULLETIN_CLASSES = collections.OrderedDict()
|
||||
|
||||
|
||||
def register_bulletin_class(klass):
|
||||
BULLETIN_CLASSES[klass.__name__] = klass
|
||||
|
||||
|
||||
def bulletin_class_descriptions():
|
||||
return [x.description for x in BULLETIN_CLASSES.values()]
|
||||
|
||||
|
||||
def bulletin_class_names():
|
||||
return list(BULLETIN_CLASSES.keys())
|
||||
|
||||
|
||||
def bulletin_default_class_name():
|
||||
return bulletin_class_names()[0]
|
||||
|
||||
|
||||
def bulletin_get_class(class_name):
|
||||
return BULLETIN_CLASSES[class_name]
|
||||
|
||||
|
||||
def bulletin_get_class_name_displayed(formsemestre_id):
|
||||
"""Le nom du générateur utilisé, en clair"""
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
bul_class_name = sco_preferences.get_preference("bul_class_name", formsemestre_id)
|
||||
try:
|
||||
gen_class = bulletin_get_class(bul_class_name)
|
||||
return gen_class.description
|
||||
except:
|
||||
return "invalide ! (voir paramètres)"
|
||||
|
||||
|
||||
class BulletinGenerator(object):
|
||||
class BulletinGenerator:
|
||||
"Virtual superclass for PDF bulletin generators" ""
|
||||
# Here some helper methods
|
||||
# see sco_bulletins_standard.BulletinGeneratorStandard subclass for real methods
|
||||
supported_formats = [] # should list supported formats, eg [ 'html', 'pdf' ]
|
||||
description = "superclass for bulletins" # description for user interface
|
||||
list_in_menu = True # la classe doit-elle est montrée dans le menu de config ?
|
||||
scale_table_in_page = True # rescale la table sur 1 page
|
||||
multi_pages = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
@ -151,7 +126,7 @@ class BulletinGenerator(object):
|
|||
def get_filename(self):
|
||||
"""Build a filename to be proposed to the web client"""
|
||||
sem = sco_formsemestre.get_formsemestre(self.infos["formsemestre_id"])
|
||||
return scu.bul_filename(sem, self.infos["etud"], "pdf")
|
||||
return scu.bul_filename_old(sem, self.infos["etud"], "pdf")
|
||||
|
||||
def generate(self, format="", stand_alone=True):
|
||||
"""Return bulletin in specified format"""
|
||||
|
@ -187,29 +162,47 @@ class BulletinGenerator(object):
|
|||
from app.scodoc import sco_preferences
|
||||
|
||||
formsemestre_id = self.infos["formsemestre_id"]
|
||||
|
||||
marque_debut_bulletin = sco_pdf.DebutBulletin(
|
||||
self.infos["etud"]["nomprenom"],
|
||||
filigranne=self.infos["filigranne"],
|
||||
footer_content=f"""ScoDoc - Bulletin de {self.infos["etud"]["nomprenom"]} - {time.strftime("%d/%m/%Y %H:%M")}""",
|
||||
)
|
||||
story = []
|
||||
# partie haute du bulletin
|
||||
objects = self.bul_title_pdf() # pylint: disable=no-member
|
||||
# table des notes
|
||||
objects += self.bul_table(format="pdf") # pylint: disable=no-member
|
||||
# infos sous la table
|
||||
objects += self.bul_part_below(format="pdf") # pylint: disable=no-member
|
||||
# signatures
|
||||
objects += self.bul_signatures_pdf() # pylint: disable=no-member
|
||||
story += self.bul_title_pdf() # pylint: disable=no-member
|
||||
index_obj_debut = len(story)
|
||||
|
||||
# Réduit sur une page
|
||||
objects = [KeepInFrame(0, 0, objects, mode="shrink")]
|
||||
# table des notes
|
||||
story += self.bul_table(format="pdf") # pylint: disable=no-member
|
||||
# infos sous la table
|
||||
story += self.bul_part_below(format="pdf") # pylint: disable=no-member
|
||||
# signatures
|
||||
story += self.bul_signatures_pdf() # pylint: disable=no-member
|
||||
if self.scale_table_in_page:
|
||||
# Réduit sur une page
|
||||
story = [marque_debut_bulletin, KeepInFrame(0, 0, story, mode="shrink")]
|
||||
else:
|
||||
# Insere notre marqueur qui permet de générer les bookmarks et filigrannes:
|
||||
story.insert(index_obj_debut, marque_debut_bulletin)
|
||||
#
|
||||
# objects.append(sco_pdf.FinBulletin())
|
||||
if not stand_alone:
|
||||
objects.append(PageBreak()) # insert page break at end
|
||||
return objects
|
||||
if self.multi_pages:
|
||||
# Bulletins sur plusieurs page, force début suivant sur page impaire
|
||||
story.append(
|
||||
DocIf("doc.page%2 == 1", [PageBreak(), PageBreak()], [PageBreak()])
|
||||
)
|
||||
else:
|
||||
story.append(PageBreak()) # insert page break at end
|
||||
|
||||
return story
|
||||
else:
|
||||
# Generation du document PDF
|
||||
sem = sco_formsemestre.get_formsemestre(formsemestre_id)
|
||||
report = io.BytesIO() # in-memory document, no disk file
|
||||
document = sco_pdf.BaseDocTemplate(report)
|
||||
document.addPageTemplates(
|
||||
sco_pdf.ScolarsPageTemplate(
|
||||
sco_pdf.ScoDocPageTemplate(
|
||||
document,
|
||||
author="%s %s (E. Viennet) [%s]"
|
||||
% (sco_version.SCONAME, sco_version.SCOVERSION, self.description),
|
||||
|
@ -222,7 +215,7 @@ class BulletinGenerator(object):
|
|||
preferences=sco_preferences.SemPreferences(formsemestre_id),
|
||||
)
|
||||
)
|
||||
document.build(objects)
|
||||
document.build(story)
|
||||
data = report.getvalue()
|
||||
return data
|
||||
|
||||
|
@ -253,7 +246,7 @@ class BulletinGenerator(object):
|
|||
# ---------------------------------------------------------------------------
|
||||
def make_formsemestre_bulletinetud(
|
||||
infos,
|
||||
version="long", # short, long, selectedevals
|
||||
version=None, # short, long, selectedevals
|
||||
format="pdf", # html, pdf
|
||||
stand_alone=True,
|
||||
):
|
||||
|
@ -265,14 +258,25 @@ def make_formsemestre_bulletinetud(
|
|||
"""
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
version = version or "long"
|
||||
if not version in scu.BULLETINS_VERSIONS:
|
||||
raise ValueError("invalid version code !")
|
||||
|
||||
formsemestre_id = infos["formsemestre_id"]
|
||||
bul_class_name = sco_preferences.get_preference("bul_class_name", formsemestre_id)
|
||||
try:
|
||||
gen_class = bulletin_get_class(bul_class_name)
|
||||
except:
|
||||
|
||||
gen_class = None
|
||||
for bul_class_name in (
|
||||
sco_preferences.get_preference("bul_class_name", formsemestre_id),
|
||||
# si pas trouvé (modifs locales bizarres ,), ré-essaye avec la valeur par défaut
|
||||
bulletin_default_class_name(),
|
||||
):
|
||||
if infos.get("type") == "BUT" and format.startswith("pdf"):
|
||||
gen_class = bulletin_get_class(bul_class_name + "BUT")
|
||||
if gen_class is None:
|
||||
gen_class = bulletin_get_class(bul_class_name)
|
||||
|
||||
if gen_class is None:
|
||||
raise ValueError(
|
||||
"Type de bulletin PDF invalide (paramètre: %s)" % bul_class_name
|
||||
)
|
||||
|
@ -313,3 +317,52 @@ def make_formsemestre_bulletinetud(
|
|||
filename = bul_generator.get_filename()
|
||||
|
||||
return data, filename
|
||||
|
||||
|
||||
####
|
||||
|
||||
# Liste des types des classes de générateurs de bulletins PDF:
|
||||
BULLETIN_CLASSES = collections.OrderedDict()
|
||||
|
||||
|
||||
def register_bulletin_class(klass):
|
||||
BULLETIN_CLASSES[klass.__name__] = klass
|
||||
|
||||
|
||||
def bulletin_class_descriptions():
|
||||
return [
|
||||
BULLETIN_CLASSES[class_name].description
|
||||
for class_name in BULLETIN_CLASSES
|
||||
if BULLETIN_CLASSES[class_name].list_in_menu
|
||||
]
|
||||
|
||||
|
||||
def bulletin_class_names() -> list[str]:
|
||||
"Liste les noms des classes de bulletins à présenter à l'utilisateur"
|
||||
return [
|
||||
class_name
|
||||
for class_name in BULLETIN_CLASSES
|
||||
if BULLETIN_CLASSES[class_name].list_in_menu
|
||||
]
|
||||
|
||||
|
||||
def bulletin_default_class_name():
|
||||
return bulletin_class_names()[0]
|
||||
|
||||
|
||||
def bulletin_get_class(class_name: str) -> BulletinGenerator:
|
||||
"""La class de génération de bulletin de ce nom,
|
||||
ou None si pas trouvée
|
||||
"""
|
||||
return BULLETIN_CLASSES.get(class_name)
|
||||
|
||||
|
||||
def bulletin_get_class_name_displayed(formsemestre_id):
|
||||
"""Le nom du générateur utilisé, en clair"""
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
bul_class_name = sco_preferences.get_preference("bul_class_name", formsemestre_id)
|
||||
gen_class = bulletin_get_class(bul_class_name)
|
||||
if gen_class is None:
|
||||
return "invalide ! (voir paramètres)"
|
||||
return gen_class.description
|
||||
|
|
|
@ -32,13 +32,14 @@ import datetime
|
|||
import json
|
||||
|
||||
from app.but import bulletin_but
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models.formsemestre import FormSemestre
|
||||
from app.models.etudiants import Identite
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app.scodoc import sco_abs
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_edit_ue
|
||||
from app.scodoc import sco_evaluation_db
|
||||
from app.scodoc import sco_formsemestre
|
||||
|
@ -90,11 +91,7 @@ def formsemestre_bulletinetud_published_dict(
|
|||
etud = Identite.query.get(etudid)
|
||||
sem = sco_formsemestre.get_formsemestre(formsemestre_id)
|
||||
|
||||
if formsemestre.formation.is_apc():
|
||||
nt = bulletin_but.APCNotesTableCompat(formsemestre)
|
||||
else:
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id)
|
||||
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
d = {}
|
||||
|
||||
if (not sem["bul_hide_xml"]) or force_publishing:
|
||||
|
@ -141,7 +138,7 @@ def formsemestre_bulletinetud_published_dict(
|
|||
if not published:
|
||||
return d # stop !
|
||||
|
||||
etat_inscription = etud.etat_inscription(formsemestre.id)
|
||||
etat_inscription = etud.inscription_etat(formsemestre.id)
|
||||
if etat_inscription != scu.INSCRIT:
|
||||
d.update(dict_decision_jury(etudid, formsemestre_id, with_decisions=True))
|
||||
return d
|
||||
|
@ -153,9 +150,9 @@ def formsemestre_bulletinetud_published_dict(
|
|||
pid = partition["partition_id"]
|
||||
partitions_etud_groups[pid] = sco_groups.get_etud_groups_in_partition(pid)
|
||||
|
||||
ues = nt.get_ues()
|
||||
modimpls = nt.get_modimpls()
|
||||
nbetuds = len(nt.rangs)
|
||||
ues = nt.get_ues_stat_dict()
|
||||
modimpls = nt.get_modimpls_dict()
|
||||
nbetuds = len(nt.etud_moy_gen_ranks)
|
||||
mg = scu.fmt_note(nt.get_etud_moy_gen(etudid))
|
||||
if (
|
||||
nt.get_moduleimpls_attente()
|
||||
|
@ -192,7 +189,9 @@ def formsemestre_bulletinetud_published_dict(
|
|||
)
|
||||
|
||||
d["note_max"] = dict(value=20) # notes toujours sur 20
|
||||
d["bonus_sport_culture"] = dict(value=nt.bonus[etudid])
|
||||
d["bonus_sport_culture"] = dict(
|
||||
value=nt.bonus[etudid] if nt.bonus is not None else 0.0
|
||||
)
|
||||
|
||||
# Liste les UE / modules /evals
|
||||
d["ue"] = []
|
||||
|
@ -203,21 +202,22 @@ def formsemestre_bulletinetud_published_dict(
|
|||
ects_txt = ""
|
||||
else:
|
||||
ects_txt = f"{ue['ects']:2.3g}"
|
||||
rang, effectif = nt.get_etud_ue_rang(ue["ue_id"], etudid)
|
||||
u = dict(
|
||||
id=ue["ue_id"],
|
||||
numero=scu.quote_xml_attr(ue["numero"]),
|
||||
acronyme=scu.quote_xml_attr(ue["acronyme"]),
|
||||
titre=scu.quote_xml_attr(ue["titre"]),
|
||||
note=dict(
|
||||
value=scu.fmt_note(ue_status["cur_moy_ue"]),
|
||||
value=scu.fmt_note(ue_status["cur_moy_ue"] if ue_status else ""),
|
||||
min=scu.fmt_note(ue["min"]),
|
||||
max=scu.fmt_note(ue["max"]),
|
||||
moy=scu.fmt_note(
|
||||
ue["moy"]
|
||||
), # CM : ajout pour faire apparaitre la moyenne des UE
|
||||
),
|
||||
rang=str(nt.ue_rangs[ue["ue_id"]][0][etudid]),
|
||||
effectif=str(nt.ue_rangs[ue["ue_id"]][1]),
|
||||
rang=rang,
|
||||
effectif=effectif,
|
||||
ects=ects_txt,
|
||||
code_apogee=scu.quote_xml_attr(ue["code_apogee"]),
|
||||
)
|
||||
|
@ -254,7 +254,10 @@ def formsemestre_bulletinetud_published_dict(
|
|||
m["note"][k] = scu.fmt_note(m["note"][k])
|
||||
|
||||
u["module"].append(m)
|
||||
if sco_preferences.get_preference("bul_show_mod_rangs", formsemestre_id):
|
||||
if (
|
||||
sco_preferences.get_preference("bul_show_mod_rangs", formsemestre_id)
|
||||
and nt.mod_rangs is not None
|
||||
):
|
||||
m["rang"] = dict(
|
||||
value=nt.mod_rangs[modimpl["moduleimpl_id"]][0][etudid]
|
||||
)
|
||||
|
|
|
@ -34,17 +34,19 @@
|
|||
CE FORMAT N'EVOLUERA PLUS ET EST CONSIDERE COMME OBSOLETE.
|
||||
|
||||
"""
|
||||
from reportlab.lib.colors import Color, blue
|
||||
from reportlab.lib.units import cm, mm
|
||||
from reportlab.platypus import Paragraph, Spacer, Table
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_pdf
|
||||
from app.scodoc.sco_pdf import Color, Paragraph, Spacer, Table
|
||||
from app.scodoc.sco_pdf import blue, cm, mm
|
||||
from app.scodoc.sco_pdf import SU
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc import sco_bulletins_generator
|
||||
from app.scodoc import sco_bulletins_pdf
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
from app.scodoc import sco_pdf
|
||||
from app.scodoc.sco_pdf import SU
|
||||
from app.scodoc import sco_preferences
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
|
||||
# Important: Le nom de la classe ne doit pas changer (bien le choisir), car il sera stocké en base de données (dans les préférences)
|
||||
class BulletinGeneratorLegacy(sco_bulletins_generator.BulletinGenerator):
|
||||
|
@ -169,7 +171,7 @@ class BulletinGeneratorLegacy(sco_bulletins_generator.BulletinGenerator):
|
|||
)
|
||||
)
|
||||
|
||||
# Contenu table: UE apres UE
|
||||
# Contenu table: UE après UE
|
||||
for ue in I["ues"]:
|
||||
ue_descr = ue["ue_descr_html"]
|
||||
coef_ue = ue["coef_ue_txt"]
|
||||
|
@ -476,8 +478,8 @@ def _bulletin_pdf_table_legacy(I, version="long"):
|
|||
else:
|
||||
rang_minmax = mod["mod_rang_txt"] # vide si pas option rang
|
||||
t = [
|
||||
mod["code"],
|
||||
mod["name"],
|
||||
mod["code"] or "",
|
||||
mod["name"] or "",
|
||||
rang_minmax,
|
||||
mod["mod_moy_txt"],
|
||||
mod["mod_coef_txt"],
|
||||
|
|
|
@ -51,37 +51,39 @@ Chaque semestre peut si nécessaire utiliser un type de bulletin différent.
|
|||
|
||||
"""
|
||||
import io
|
||||
import pprint
|
||||
import pydoc
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
from pydoc import html
|
||||
|
||||
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
|
||||
|
||||
from flask import g, request
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app import log, ScoValueError
|
||||
from app.models import FormSemestre
|
||||
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_codes_parcours
|
||||
from app.scodoc import sco_pdf
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc import sco_etud
|
||||
import sco_version
|
||||
from app.scodoc.sco_logos import find_logo
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
import sco_version
|
||||
|
||||
|
||||
def pdfassemblebulletins(
|
||||
formsemestre_id,
|
||||
objects,
|
||||
bul_title,
|
||||
def assemble_bulletins_pdf(
|
||||
formsemestre_id: int,
|
||||
story: list,
|
||||
bul_title: str,
|
||||
infos,
|
||||
pagesbookmarks,
|
||||
pagesbookmarks=None,
|
||||
filigranne=None,
|
||||
server_name="",
|
||||
):
|
||||
"generate PDF document from a list of PLATYPUS objects"
|
||||
if not objects:
|
||||
"Generate PDF document from a story (list of PLATYPUS objects)."
|
||||
if not story:
|
||||
return ""
|
||||
# Paramètres de mise en page
|
||||
margins = (
|
||||
|
@ -90,11 +92,10 @@ def pdfassemblebulletins(
|
|||
sco_preferences.get_preference("right_margin", formsemestre_id),
|
||||
sco_preferences.get_preference("bottom_margin", formsemestre_id),
|
||||
)
|
||||
|
||||
report = io.BytesIO() # in-memory document, no disk file
|
||||
document = BaseDocTemplate(report)
|
||||
document = sco_pdf.BulletinDocTemplate(report)
|
||||
document.addPageTemplates(
|
||||
sco_pdf.ScolarsPageTemplate(
|
||||
sco_pdf.ScoDocPageTemplate(
|
||||
document,
|
||||
author="%s %s (E. Viennet)" % (sco_version.SCONAME, sco_version.SCOVERSION),
|
||||
title="Bulletin %s" % bul_title,
|
||||
|
@ -106,7 +107,7 @@ def pdfassemblebulletins(
|
|||
preferences=sco_preferences.SemPreferences(formsemestre_id),
|
||||
)
|
||||
)
|
||||
document.build(objects)
|
||||
document.multiBuild(story)
|
||||
data = report.getvalue()
|
||||
return data
|
||||
|
||||
|
@ -118,7 +119,8 @@ def replacement_function(match):
|
|||
if logo is not None:
|
||||
return r'<img %s src="%s"%s/>' % (match.group(2), logo.filepath, match.group(4))
|
||||
raise ScoValueError(
|
||||
'balise "%s": logo "%s" introuvable' % (html.escape(balise), html.escape(name))
|
||||
'balise "%s": logo "%s" introuvable'
|
||||
% (pydoc.html.escape(balise), pydoc.html.escape(name))
|
||||
)
|
||||
|
||||
|
||||
|
@ -139,9 +141,13 @@ def process_field(field, cdict, style, suppress_empty_pars=False, format="pdf"):
|
|||
cdict
|
||||
) # note that None values are mapped to empty strings
|
||||
except:
|
||||
log("process_field: invalid format=%s" % field)
|
||||
log(
|
||||
f"""process_field: invalid format. field={field!r}
|
||||
values={pprint.pformat(cdict)}
|
||||
"""
|
||||
)
|
||||
text = (
|
||||
"<para><i>format invalide !<i></para><para>"
|
||||
"<para><i>format invalide !</i></para><para>"
|
||||
+ traceback.format_exc()
|
||||
+ "</para>"
|
||||
)
|
||||
|
@ -171,30 +177,23 @@ def process_field(field, cdict, style, suppress_empty_pars=False, format="pdf"):
|
|||
|
||||
|
||||
def get_formsemestre_bulletins_pdf(formsemestre_id, version="selectedevals"):
|
||||
"document pdf et filename"
|
||||
"Document pdf avec tous les bulletins du semestre, et filename"
|
||||
from app.scodoc import sco_bulletins
|
||||
|
||||
cached = sco_cache.SemBulletinsPDFCache.get(str(formsemestre_id) + "_" + version)
|
||||
if cached:
|
||||
return cached[1], cached[0]
|
||||
fragments = []
|
||||
sem = sco_formsemestre.get_formsemestre(formsemestre_id)
|
||||
# Make each bulletin
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id) # > get_etudids, get_sexnom
|
||||
bookmarks = {}
|
||||
filigrannes = {}
|
||||
i = 1
|
||||
for etudid in nt.get_etudids():
|
||||
frag, filigranne = sco_bulletins.do_formsemestre_bulletinetud(
|
||||
formsemestre_id,
|
||||
etudid,
|
||||
formsemestre: FormSemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
for etud in formsemestre.get_inscrits(include_demdef=True, order=True):
|
||||
frag, _ = sco_bulletins.do_formsemestre_bulletinetud(
|
||||
formsemestre,
|
||||
etud.id,
|
||||
format="pdfpart",
|
||||
version=version,
|
||||
)
|
||||
fragments += frag
|
||||
filigrannes[i] = filigranne
|
||||
bookmarks[i] = scu.suppress_accents(nt.get_sexnom(etudid))
|
||||
i = i + 1
|
||||
#
|
||||
infos = {"DeptName": sco_preferences.get_preference("DeptName", formsemestre_id)}
|
||||
if request:
|
||||
|
@ -203,20 +202,18 @@ def get_formsemestre_bulletins_pdf(formsemestre_id, version="selectedevals"):
|
|||
server_name = ""
|
||||
try:
|
||||
sco_pdf.PDFLOCK.acquire()
|
||||
pdfdoc = pdfassemblebulletins(
|
||||
pdfdoc = assemble_bulletins_pdf(
|
||||
formsemestre_id,
|
||||
fragments,
|
||||
sem["titremois"],
|
||||
formsemestre.titre_mois(),
|
||||
infos,
|
||||
bookmarks,
|
||||
filigranne=filigrannes,
|
||||
server_name=server_name,
|
||||
)
|
||||
finally:
|
||||
sco_pdf.PDFLOCK.release()
|
||||
#
|
||||
dt = time.strftime("%Y-%m-%d")
|
||||
filename = "bul-%s-%s.pdf" % (sem["titre_num"], dt)
|
||||
date_iso = time.strftime("%Y-%m-%d")
|
||||
filename = "bul-%s-%s.pdf" % (formsemestre.titre_num(), date_iso)
|
||||
filename = scu.unescape_html(filename).replace(" ", "_").replace("&", "")
|
||||
# fill cache
|
||||
sco_cache.SemBulletinsPDFCache.set(
|
||||
|
@ -235,8 +232,9 @@ def get_etud_bulletins_pdf(etudid, version="selectedevals"):
|
|||
filigrannes = {}
|
||||
i = 1
|
||||
for sem in etud["sems"]:
|
||||
formsemestre = FormSemestre.query.get(sem["formsemestre_id"])
|
||||
frag, filigranne = sco_bulletins.do_formsemestre_bulletinetud(
|
||||
sem["formsemestre_id"],
|
||||
formsemestre,
|
||||
etudid,
|
||||
format="pdfpart",
|
||||
version=version,
|
||||
|
@ -252,7 +250,7 @@ def get_etud_bulletins_pdf(etudid, version="selectedevals"):
|
|||
server_name = ""
|
||||
try:
|
||||
sco_pdf.PDFLOCK.acquire()
|
||||
pdfdoc = pdfassemblebulletins(
|
||||
pdfdoc = assemble_bulletins_pdf(
|
||||
None,
|
||||
fragments,
|
||||
etud["nomprenom"],
|
||||
|
@ -271,3 +269,16 @@ def get_etud_bulletins_pdf(etudid, version="selectedevals"):
|
|||
)
|
||||
|
||||
return pdfdoc, filename
|
||||
|
||||
|
||||
def get_filigranne(etud_etat: str, prefs, decision_sem=None) -> str:
|
||||
"""Texte à placer en "filigranne" sur le bulletin pdf"""
|
||||
if etud_etat == scu.DEMISSION:
|
||||
return "Démission"
|
||||
elif etud_etat == sco_codes_parcours.DEF:
|
||||
return "Défaillant"
|
||||
elif (prefs["bul_show_temporary"] and not decision_sem) or prefs[
|
||||
"bul_show_temporary_forced"
|
||||
]:
|
||||
return prefs["bul_temporary_txt"]
|
||||
return ""
|
||||
|
|
|
@ -46,10 +46,13 @@ de la forme %(XXX)s sont remplacées par la valeur de XXX, pour XXX dans:
|
|||
Balises img: actuellement interdites.
|
||||
|
||||
"""
|
||||
from reportlab.platypus import KeepTogether, Paragraph, Spacer, Table
|
||||
from reportlab.lib.units import cm, mm
|
||||
from reportlab.lib.colors import Color, blue
|
||||
from app.models import FormSemestre
|
||||
from app.scodoc.sco_exceptions import ScoBugCatcher
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_pdf import Color, Paragraph, Spacer, Table
|
||||
from app.scodoc.sco_pdf import blue, cm, mm
|
||||
from app.scodoc.sco_pdf import SU
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
|
@ -66,12 +69,13 @@ from app.scodoc import sco_groups
|
|||
from app.scodoc import sco_evaluations
|
||||
from app.scodoc import gen_tables
|
||||
|
||||
# Important: Le nom de la classe ne doit pas changer (bien le choisir), car il sera stocké en base de données (dans les préférences)
|
||||
# Important: Le nom de la classe ne doit pas changer (bien le choisir),
|
||||
# car il sera stocké en base de données (dans les préférences)
|
||||
class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
||||
description = "standard ScoDoc (version 2011)" # la description doit être courte: elle apparait dans le menu de paramètrage ScoDoc
|
||||
supported_formats = ["html", "pdf"]
|
||||
|
||||
def bul_title_pdf(self):
|
||||
def bul_title_pdf(self) -> list:
|
||||
"""Génère la partie "titre" du bulletin de notes.
|
||||
Renvoie une liste d'objets platypus
|
||||
"""
|
||||
|
@ -113,11 +117,11 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
- en PDF: une liste d'objets platypus
|
||||
"""
|
||||
H = [] # html
|
||||
Op = [] # objets platypus
|
||||
story = [] # objets platypus
|
||||
# ----- ABSENCES
|
||||
if self.preferences["bul_show_abs"]:
|
||||
nbabs = self.infos["nbabs"]
|
||||
Op.append(Spacer(1, 2 * mm))
|
||||
story.append(Spacer(1, 2 * mm))
|
||||
if nbabs:
|
||||
H.append(
|
||||
"""<p class="bul_abs">
|
||||
|
@ -128,7 +132,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
"""
|
||||
% self.infos
|
||||
)
|
||||
Op.append(
|
||||
story.append(
|
||||
Paragraph(
|
||||
SU(
|
||||
"%(nbabs)s absences (1/2 journées), dont %(nbabsjust)s justifiées."
|
||||
|
@ -139,7 +143,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
)
|
||||
else:
|
||||
H.append("""<p class="bul_abs">Pas d'absences signalées.</p>""")
|
||||
Op.append(Paragraph(SU("Pas d'absences signalées."), self.CellStyle))
|
||||
story.append(Paragraph(SU("Pas d'absences signalées."), self.CellStyle))
|
||||
|
||||
# ---- APPRECIATIONS
|
||||
# le dir. des etud peut ajouter des appreciations,
|
||||
|
@ -166,10 +170,10 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
% self.infos
|
||||
)
|
||||
H.append("</div>")
|
||||
# Appreciations sur PDF:
|
||||
# Appréciations sur PDF:
|
||||
if self.infos.get("appreciations_list", False):
|
||||
Op.append(Spacer(1, 3 * mm))
|
||||
Op.append(
|
||||
story.append(Spacer(1, 3 * mm))
|
||||
story.append(
|
||||
Paragraph(
|
||||
SU("Appréciation : " + "\n".join(self.infos["appreciations_txt"])),
|
||||
self.CellStyle,
|
||||
|
@ -178,7 +182,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
|
||||
# ----- DECISION JURY
|
||||
if self.preferences["bul_show_decision"]:
|
||||
Op += sco_bulletins_pdf.process_field(
|
||||
story += sco_bulletins_pdf.process_field(
|
||||
self.preferences["bul_pdf_caption"],
|
||||
self.infos,
|
||||
self.FieldStyle,
|
||||
|
@ -194,7 +198,12 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
|
||||
# -----
|
||||
if format == "pdf":
|
||||
return Op
|
||||
if self.scale_table_in_page:
|
||||
# le scaling (pour tenir sur une page) semble incompatible avec
|
||||
# le KeepTogether()
|
||||
return story
|
||||
else:
|
||||
return [KeepTogether(story)]
|
||||
elif format == "html":
|
||||
return "\n".join(H)
|
||||
|
||||
|
@ -263,12 +272,12 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
)
|
||||
|
||||
def build_bulletin_table(self):
|
||||
"""Génère la table centrale du bulletin de notes
|
||||
Renvoie: colkeys, P, pdf_style, colWidths
|
||||
- colkeys: nom des colonnes de la table (clés)
|
||||
- table (liste de dicts de chaines de caracteres)
|
||||
- style (commandes table Platypus)
|
||||
- largeurs de colonnes pour PDF
|
||||
"""Génère la table centrale du bulletin de notes classique (pas BUT)
|
||||
Renvoie: col_keys, P, pdf_style, col_widths
|
||||
- col_keys: nom des colonnes de la table (clés)
|
||||
- table: liste de dicts de chaines de caractères
|
||||
- pdf_style: commandes table Platypus
|
||||
- col_widths: largeurs de colonnes pour PDF
|
||||
"""
|
||||
I = self.infos
|
||||
P = [] # elems pour générer table avec gen_table (liste de dicts)
|
||||
|
@ -284,28 +293,28 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
)
|
||||
with_col_moypromo = prefs["bul_show_moypromo"]
|
||||
with_col_rang = prefs["bul_show_rangs"]
|
||||
with_col_coef = prefs["bul_show_coef"]
|
||||
with_col_coef = prefs["bul_show_coef"] or prefs["bul_show_ue_coef"]
|
||||
with_col_ects = prefs["bul_show_ects"]
|
||||
|
||||
colkeys = ["titre", "module"] # noms des colonnes à afficher
|
||||
col_keys = ["titre", "module"] # noms des colonnes à afficher
|
||||
if with_col_rang:
|
||||
colkeys += ["rang"]
|
||||
col_keys += ["rang"]
|
||||
if with_col_minmax:
|
||||
colkeys += ["min"]
|
||||
col_keys += ["min"]
|
||||
if with_col_moypromo:
|
||||
colkeys += ["moy"]
|
||||
col_keys += ["moy"]
|
||||
if with_col_minmax:
|
||||
colkeys += ["max"]
|
||||
colkeys += ["note"]
|
||||
col_keys += ["max"]
|
||||
col_keys += ["note"]
|
||||
if with_col_coef:
|
||||
colkeys += ["coef"]
|
||||
col_keys += ["coef"]
|
||||
if with_col_ects:
|
||||
colkeys += ["ects"]
|
||||
col_keys += ["ects"]
|
||||
if with_col_abs:
|
||||
colkeys += ["abs"]
|
||||
col_keys += ["abs"]
|
||||
colidx = {} # { nom_colonne : indice à partir de 0 } (pour styles platypus)
|
||||
i = 0
|
||||
for k in colkeys:
|
||||
for k in col_keys:
|
||||
colidx[k] = i
|
||||
i += 1
|
||||
|
||||
|
@ -313,7 +322,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
bul_pdf_mod_colwidth = float(prefs["bul_pdf_mod_colwidth"]) * cm
|
||||
else:
|
||||
bul_pdf_mod_colwidth = None
|
||||
colWidths = {
|
||||
col_widths = {
|
||||
"titre": None,
|
||||
"module": bul_pdf_mod_colwidth,
|
||||
"min": 1.5 * cm,
|
||||
|
@ -373,10 +382,10 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
t = {
|
||||
"titre": "Moyenne générale:",
|
||||
"rang": I["rang_nt"],
|
||||
"note": I["moy_gen"],
|
||||
"min": I["moy_min"],
|
||||
"max": I["moy_max"],
|
||||
"moy": I["moy_moy"],
|
||||
"note": I.get("moy_gen", "-"),
|
||||
"min": I.get("moy_min", "-"),
|
||||
"max": I.get("moy_max", "-"),
|
||||
"moy": I.get("moy_moy", "-"),
|
||||
"abs": "%s / %s" % (nbabs, nbabsjust),
|
||||
"_css_row_class": "notes_bulletin_row_gen",
|
||||
"_titre_colspan": 2,
|
||||
|
@ -409,7 +418,8 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
# Chaque UE:
|
||||
for ue in I["ues"]:
|
||||
ue_type = None
|
||||
coef_ue = ue["coef_ue_txt"]
|
||||
coef_ue = ue["coef_ue_txt"] if prefs["bul_show_ue_coef"] else ""
|
||||
|
||||
ue_descr = ue["ue_descr_txt"]
|
||||
rowstyle = ""
|
||||
plusminus = minuslink #
|
||||
|
@ -430,7 +440,13 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
|
||||
t = {
|
||||
"titre": ue["acronyme"] + " " + ue["titre"],
|
||||
"_titre_html": plusminus + ue["acronyme"] + " " + ue["titre"],
|
||||
"_titre_html": plusminus
|
||||
+ ue["acronyme"]
|
||||
+ " "
|
||||
+ ue["titre"]
|
||||
+ ' <span class="bul_ue_descr">'
|
||||
+ ue["ue_descr_txt"]
|
||||
+ "</span>",
|
||||
"_titre_help": ue["ue_descr_txt"],
|
||||
"_titre_colspan": 2,
|
||||
"module": ue_descr,
|
||||
|
@ -465,9 +481,10 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
ects_txt = str(int(ue["ects"]))
|
||||
except:
|
||||
ects_txt = "-"
|
||||
titre = f"{ue['acronyme'] or ''} {ue['titre'] or ''}"
|
||||
t = {
|
||||
"titre": ue["acronyme"] + " " + ue["titre"],
|
||||
"_titre_html": minuslink + ue["acronyme"] + " " + ue["titre"],
|
||||
"titre": titre,
|
||||
"_titre_html": minuslink + titre,
|
||||
"_titre_colspan": 2,
|
||||
"module": ue["titre"],
|
||||
"rang": ue_descr,
|
||||
|
@ -534,7 +551,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
("BOX", (0, 0), (-1, -1), 0.4, blue), # ajoute cadre extérieur bleu:
|
||||
]
|
||||
#
|
||||
return colkeys, P, pdf_style, colWidths
|
||||
return col_keys, P, pdf_style, col_widths
|
||||
|
||||
def _list_modules(
|
||||
self,
|
||||
|
@ -585,7 +602,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
"_titre_colspan": 2,
|
||||
"rang": mod["mod_rang_txt"], # vide si pas option rang
|
||||
"note": mod["mod_moy_txt"],
|
||||
"coef": mod["mod_coef_txt"],
|
||||
"coef": mod["mod_coef_txt"] if prefs["bul_show_coef"] else "",
|
||||
"abs": mod.get(
|
||||
"mod_abs_txt", ""
|
||||
), # absent si pas option show abs module
|
||||
|
@ -619,7 +636,7 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
prefs=prefs,
|
||||
)
|
||||
|
||||
if nbeval: # boite autour des evaluations (en pdf)
|
||||
if nbeval: # boite autour des évaluations (en pdf)
|
||||
P[-1]["_pdf_style"].append(
|
||||
("BOX", (1, 1 - nbeval), (-1, 0), 0.2, self.PDF_LIGHT_GRAY)
|
||||
)
|
||||
|
@ -649,7 +666,9 @@ class BulletinGeneratorStandard(sco_bulletins_generator.BulletinGenerator):
|
|||
eval_style = ""
|
||||
t = {
|
||||
"module": '<bullet indent="2mm">•</bullet> ' + e["name"],
|
||||
"coef": "<i>" + e["coef_txt"] + "</i>",
|
||||
"coef": ("<i>" + e["coef_txt"] + "</i>")
|
||||
if prefs["bul_show_coef"]
|
||||
else "",
|
||||
"_hidden": hidden,
|
||||
"_module_target": e["target_html"],
|
||||
# '_module_help' : ,
|
||||
|
|
|
@ -32,16 +32,12 @@ On redéfini la table centrale du bulletin de note et hérite de tout le reste d
|
|||
|
||||
E. Viennet, juillet 2011
|
||||
"""
|
||||
from reportlab.lib.colors import Color
|
||||
from reportlab.lib.units import mm
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_pdf import blue, cm, mm
|
||||
from app.scodoc.sco_pdf import Color, Paragraph, Spacer, Table
|
||||
|
||||
from app.scodoc import sco_preferences
|
||||
|
||||
from app.scodoc import sco_bulletins_generator
|
||||
from app.scodoc import sco_bulletins_standard
|
||||
from app.scodoc import gen_tables
|
||||
from app.scodoc import sco_preferences
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
||||
|
||||
class BulletinGeneratorUCAC(sco_bulletins_standard.BulletinGeneratorStandard):
|
||||
|
|
|
@ -44,6 +44,8 @@ import datetime
|
|||
from xml.etree import ElementTree
|
||||
from xml.etree.ElementTree import Element
|
||||
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
import app.scodoc.sco_utils as scu
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app import log
|
||||
|
@ -152,10 +154,11 @@ def make_xml_formsemestre_bulletinetud(
|
|||
pid = partition["partition_id"]
|
||||
partitions_etud_groups[pid] = sco_groups.get_etud_groups_in_partition(pid)
|
||||
|
||||
nt = sco_cache.NotesTableCache.get(formsemestre_id) # > toutes notes
|
||||
ues = nt.get_ues()
|
||||
modimpls = nt.get_modimpls()
|
||||
nbetuds = len(nt.rangs)
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
ues = nt.get_ues_stat_dict()
|
||||
modimpls = nt.get_modimpls_dict()
|
||||
nbetuds = len(nt.etud_moy_gen_ranks)
|
||||
mg = scu.fmt_note(nt.get_etud_moy_gen(etudid))
|
||||
if (
|
||||
nt.get_moduleimpls_attente()
|
||||
|
@ -195,7 +198,12 @@ def make_xml_formsemestre_bulletinetud(
|
|||
)
|
||||
)
|
||||
doc.append(Element("note_max", value="20")) # notes toujours sur 20
|
||||
doc.append(Element("bonus_sport_culture", value=str(nt.bonus[etudid])))
|
||||
doc.append(
|
||||
Element(
|
||||
"bonus_sport_culture",
|
||||
value=str(nt.bonus[etudid] if nt.bonus is not None else 0.0),
|
||||
)
|
||||
)
|
||||
# Liste les UE / modules /evals
|
||||
for ue in ues:
|
||||
ue_status = nt.get_etud_ue_status(etudid, ue["ue_id"])
|
||||
|
@ -209,9 +217,9 @@ def make_xml_formsemestre_bulletinetud(
|
|||
)
|
||||
doc.append(x_ue)
|
||||
if ue["type"] != sco_codes_parcours.UE_SPORT:
|
||||
v = ue_status["cur_moy_ue"]
|
||||
v = ue_status["cur_moy_ue"] if ue_status else ""
|
||||
else:
|
||||
v = nt.bonus[etudid]
|
||||
v = nt.bonus[etudid] if nt.bonus is not None else 0.0
|
||||
x_ue.append(
|
||||
Element(
|
||||
"note",
|
||||
|
@ -225,8 +233,9 @@ def make_xml_formsemestre_bulletinetud(
|
|||
except (ValueError, TypeError):
|
||||
ects_txt = ""
|
||||
x_ue.append(Element("ects", value=ects_txt))
|
||||
x_ue.append(Element("rang", value=str(nt.ue_rangs[ue["ue_id"]][0][etudid])))
|
||||
x_ue.append(Element("effectif", value=str(nt.ue_rangs[ue["ue_id"]][1])))
|
||||
rang, effectif = nt.get_etud_ue_rang(ue["ue_id"], etudid)
|
||||
x_ue.append(Element("rang", value=str(rang)))
|
||||
x_ue.append(Element("effectif", value=str(effectif)))
|
||||
# Liste les modules de l'UE
|
||||
ue_modimpls = [mod for mod in modimpls if mod["module"]["ue_id"] == ue["ue_id"]]
|
||||
for modimpl in ue_modimpls:
|
||||
|
@ -243,7 +252,7 @@ def make_xml_formsemestre_bulletinetud(
|
|||
x_mod = Element(
|
||||
"module",
|
||||
id=str(modimpl["moduleimpl_id"]),
|
||||
code=str(mod["code"]),
|
||||
code=str(mod["code"] or ""),
|
||||
coefficient=str(mod["coefficient"]),
|
||||
numero=str(mod["numero"]),
|
||||
titre=scu.quote_xml_attr(mod["titre"]),
|
||||
|
@ -262,7 +271,10 @@ def make_xml_formsemestre_bulletinetud(
|
|||
moy=scu.fmt_note(modstat["moy"]),
|
||||
)
|
||||
)
|
||||
if sco_preferences.get_preference("bul_show_mod_rangs", formsemestre_id):
|
||||
if (
|
||||
sco_preferences.get_preference("bul_show_mod_rangs", formsemestre_id)
|
||||
and nt.mod_rangs is not None
|
||||
):
|
||||
x_mod.append(
|
||||
Element(
|
||||
"rang",
|
||||
|
|
|
@ -33,17 +33,12 @@
|
|||
"""
|
||||
|
||||
|
||||
# API ScoDoc8 pour les caches:
|
||||
# sco_cache.NotesTableCache.get( formsemestre_id)
|
||||
# => sco_cache.NotesTableCache.get(formsemestre_id)
|
||||
# API pour les caches:
|
||||
# sco_cache.MyCache.get( formsemestre_id)
|
||||
# => sco_cache.MyCache.get(formsemestre_id)
|
||||
#
|
||||
# sco_core.inval_cache(formsemestre_id=None, pdfonly=False, formsemestre_id_list=None)
|
||||
# => deprecated, NotesTableCache.invalidate_formsemestre(formsemestre_id=None, pdfonly=False)
|
||||
#
|
||||
#
|
||||
# Nouvelles fonctions:
|
||||
# sco_cache.NotesTableCache.delete(formsemestre_id)
|
||||
# sco_cache.NotesTableCache.delete_many(formsemestre_id_list)
|
||||
# sco_cache.MyCache.delete(formsemestre_id)
|
||||
# sco_cache.MyCache.delete_many(formsemestre_id_list)
|
||||
#
|
||||
# Bulletins PDF:
|
||||
# sco_cache.SemBulletinsPDFCache.get(formsemestre_id, version)
|
||||
|
@ -54,14 +49,13 @@
|
|||
# sco_cache.EvaluationCache.get(evaluation_id), set(evaluation_id, value), delete(evaluation_id),
|
||||
#
|
||||
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from flask import g
|
||||
|
||||
from app import log
|
||||
from app.scodoc import notesdb as ndb
|
||||
from app.scodoc import sco_utils as scu
|
||||
from app import log
|
||||
|
||||
CACHE = None # set in app.__init__.py
|
||||
|
||||
|
@ -98,8 +92,9 @@ class ScoDocCache:
|
|||
status = CACHE.set(key, value, timeout=cls.timeout)
|
||||
if not status:
|
||||
log("Error: cache set failed !")
|
||||
except:
|
||||
except Exception as exc:
|
||||
log("XXX CACHE Warning: error in set !!!")
|
||||
log(exc)
|
||||
status = None
|
||||
return status
|
||||
|
||||
|
@ -155,16 +150,6 @@ class EvaluationCache(ScoDocCache):
|
|||
cls.delete_many(evaluation_ids)
|
||||
|
||||
|
||||
class ResultatsSemestreBUTCache(ScoDocCache):
|
||||
"""Cache pour les résultats ResultatsSemestreBUT.
|
||||
Clé: formsemestre_id
|
||||
Valeur: { un paquet de dataframes }
|
||||
"""
|
||||
|
||||
prefix = "RBUT"
|
||||
timeout = 1 * 60 # ttl 1 minutes (en phase de mise au point)
|
||||
|
||||
|
||||
class AbsSemEtudCache(ScoDocCache):
|
||||
"""Cache pour les comptes d'absences d'un étudiant dans un semestre.
|
||||
Ce cache étant indépendant des semestres, le compte peut être faux lorsqu'on
|
||||
|
@ -212,45 +197,24 @@ class SemInscriptionsCache(ScoDocCache):
|
|||
duration = 12 * 60 * 60 # ttl 12h
|
||||
|
||||
|
||||
class NotesTableCache(ScoDocCache):
|
||||
"""Cache pour les NotesTable
|
||||
class TableRecapCache(ScoDocCache):
|
||||
"""Cache table recap (pour get_table_recap)
|
||||
Clé: formsemestre_id
|
||||
Valeur: NotesTable instance
|
||||
Valeur: le html (<div class="table_recap">...</div>)
|
||||
"""
|
||||
|
||||
prefix = "NT"
|
||||
prefix = "RECAP"
|
||||
duration = 12 * 60 * 60 # ttl 12h
|
||||
|
||||
@classmethod
|
||||
def get(cls, formsemestre_id, compute=True):
|
||||
"""Returns NotesTable for this formsemestre
|
||||
Search in local cache (g.nt_cache) or global app cache (eg REDIS)
|
||||
If not in cache and compute is True, build it and cache it.
|
||||
"""
|
||||
# try local cache (same request)
|
||||
if not hasattr(g, "nt_cache"):
|
||||
g.nt_cache = {}
|
||||
else:
|
||||
if formsemestre_id in g.nt_cache:
|
||||
return g.nt_cache[formsemestre_id]
|
||||
# try REDIS
|
||||
key = cls._get_key(formsemestre_id)
|
||||
nt = CACHE.get(key)
|
||||
if nt:
|
||||
g.nt_cache[formsemestre_id] = nt # cache locally (same request)
|
||||
return nt
|
||||
if not compute:
|
||||
return None
|
||||
# Recompute requested table:
|
||||
from app.scodoc import notes_table
|
||||
|
||||
t0 = time.time()
|
||||
nt = notes_table.NotesTable(formsemestre_id)
|
||||
t1 = time.time()
|
||||
_ = cls.set(formsemestre_id, nt) # cache in REDIS
|
||||
t2 = time.time()
|
||||
log(f"cached formsemestre_id={formsemestre_id} ({(t1-t0):g}s +{(t2-t1):g}s)")
|
||||
g.nt_cache[formsemestre_id] = nt
|
||||
return nt
|
||||
class TableRecapWithEvalsCache(ScoDocCache):
|
||||
"""Cache table recap (pour get_table_recap)
|
||||
Clé: formsemestre_id
|
||||
Valeur: le html (<div class="table_recap">...</div>)
|
||||
"""
|
||||
|
||||
prefix = "RECAPWITHEVALS"
|
||||
duration = 12 * 60 * 60 # ttl 12h
|
||||
|
||||
|
||||
def invalidate_formsemestre( # was inval_cache(formsemestre_id=None, pdfonly=False)
|
||||
|
@ -264,7 +228,7 @@ def invalidate_formsemestre( # was inval_cache(formsemestre_id=None, pdfonly=Fa
|
|||
if getattr(g, "defer_cache_invalidation", False):
|
||||
g.sem_to_invalidate.add(formsemestre_id)
|
||||
return
|
||||
log("inval_cache, formsemestre_id=%s pdfonly=%s" % (formsemestre_id, pdfonly))
|
||||
log("inval_cache, formsemestre_id={formsemestre_id} pdfonly={pdfonly}")
|
||||
if formsemestre_id is None:
|
||||
# clear all caches
|
||||
log("----- invalidate_formsemestre: clearing all caches -----")
|
||||
|
@ -285,21 +249,27 @@ def invalidate_formsemestre( # was inval_cache(formsemestre_id=None, pdfonly=Fa
|
|||
|
||||
if not pdfonly:
|
||||
# Delete cached notes and evaluations
|
||||
NotesTableCache.delete_many(formsemestre_ids)
|
||||
if formsemestre_id:
|
||||
for fid in formsemestre_ids:
|
||||
EvaluationCache.invalidate_sem(fid)
|
||||
if hasattr(g, "nt_cache") and fid in g.nt_cache:
|
||||
del g.nt_cache[fid]
|
||||
if (
|
||||
hasattr(g, "formsemestre_results_cache")
|
||||
and fid in g.formsemestre_results_cache
|
||||
):
|
||||
del g.formsemestre_results_cache[fid]
|
||||
|
||||
else:
|
||||
# optimization when we invalidate all evaluations:
|
||||
EvaluationCache.invalidate_all_sems()
|
||||
if hasattr(g, "nt_cache"):
|
||||
del g.nt_cache
|
||||
if hasattr(g, "formsemestre_results_cache"):
|
||||
del g.formsemestre_results_cache
|
||||
SemInscriptionsCache.delete_many(formsemestre_ids)
|
||||
ResultatsSemestreCache.delete_many(formsemestre_ids)
|
||||
ValidationsSemestreCache.delete_many(formsemestre_ids)
|
||||
TableRecapCache.delete_many(formsemestre_ids)
|
||||
TableRecapWithEvalsCache.delete_many(formsemestre_ids)
|
||||
|
||||
SemBulletinsPDFCache.invalidate_sems(formsemestre_ids)
|
||||
ResultatsSemestreBUTCache.delete_many(formsemestre_ids)
|
||||
|
||||
|
||||
class DefferedSemCacheManager:
|
||||
|
@ -322,3 +292,24 @@ class DefferedSemCacheManager:
|
|||
while g.sem_to_invalidate:
|
||||
formsemestre_id = g.sem_to_invalidate.pop()
|
||||
invalidate_formsemestre(formsemestre_id)
|
||||
|
||||
|
||||
# ---- Nouvelles classes ScoDoc 9.2
|
||||
class ResultatsSemestreCache(ScoDocCache):
|
||||
"""Cache pour les résultats ResultatsSemestre (notes et moyennes)
|
||||
Clé: formsemestre_id
|
||||
Valeur: { un paquet de dataframes }
|
||||
"""
|
||||
|
||||
prefix = "RSEM"
|
||||
timeout = 60 * 60 # ttl 1 heure (en phase de mise au point)
|
||||
|
||||
|
||||
class ValidationsSemestreCache(ScoDocCache):
|
||||
"""Cache pour les résultats de jury d'un semestre
|
||||
Clé: formsemestre_id
|
||||
Valeur: un paquet de DataFrames
|
||||
"""
|
||||
|
||||
prefix = "VSC"
|
||||
timeout = 60 * 60 # ttl 1 heure (en phase de mise au point)
|
||||
|
|
|
@ -81,11 +81,11 @@ UE_PROFESSIONNELLE = 5 # UE "professionnelle" (ISCID, ...)
|
|||
UE_OPTIONNELLE = 6 # UE non fondamentales (ILEPS, ...)
|
||||
|
||||
|
||||
def UE_is_fondamentale(ue_type):
|
||||
def ue_is_fondamentale(ue_type):
|
||||
return ue_type in (UE_STANDARD, UE_STAGE_LP, UE_PROFESSIONNELLE)
|
||||
|
||||
|
||||
def UE_is_professionnelle(ue_type):
|
||||
def ue_is_professionnelle(ue_type):
|
||||
return (
|
||||
ue_type == UE_PROFESSIONNELLE
|
||||
) # NB: les UE_PROFESSIONNELLE sont à la fois fondamentales et pro
|
||||
|
@ -141,7 +141,7 @@ BUG = "BUG"
|
|||
|
||||
ALL = "ALL"
|
||||
|
||||
# Explication des codes (de demestre ou d'UE)
|
||||
# Explication des codes (de semestre ou d'UE)
|
||||
CODES_EXPL = {
|
||||
ADC: "Validé par compensation",
|
||||
ADJ: "Validé par le Jury",
|
||||
|
@ -154,6 +154,7 @@ CODES_EXPL = {
|
|||
DEF: "Défaillant",
|
||||
NAR: "Échec, non autorisé à redoubler",
|
||||
RAT: "En attente d'un rattrapage",
|
||||
DEM: "Démission",
|
||||
}
|
||||
# Nota: ces explications sont personnalisables via le fichier
|
||||
# de config locale /opt/scodoc/var/scodoc/config/scodoc_local.py
|
||||
|
@ -169,18 +170,18 @@ CODES_SEM_REO = {NAR: 1} # reorientation
|
|||
CODES_UE_VALIDES = {ADM: True, CMP: True} # UE validée
|
||||
|
||||
|
||||
def code_semestre_validant(code):
|
||||
def code_semestre_validant(code: str) -> bool:
|
||||
"Vrai si ce CODE entraine la validation du semestre"
|
||||
return CODES_SEM_VALIDES.get(code, False)
|
||||
|
||||
|
||||
def code_semestre_attente(code):
|
||||
def code_semestre_attente(code: str) -> bool:
|
||||
"Vrai si ce CODE est un code d'attente (semestre validable plus tard par jury ou compensation)"
|
||||
return CODES_SEM_ATTENTES.get(code, False)
|
||||
|
||||
|
||||
def code_ue_validant(code):
|
||||
"Vrai si ce code entraine la validation de l'UE"
|
||||
def code_ue_validant(code: str) -> bool:
|
||||
"Vrai si ce code entraine la validation des UEs du semestre."
|
||||
return CODES_UE_VALIDES.get(code, False)
|
||||
|
||||
|
||||
|
@ -210,7 +211,7 @@ DEVENIRS_NEXT2 = {NEXT_OR_NEXT2: 1, NEXT2: 1}
|
|||
|
||||
NO_SEMESTRE_ID = -1 # code semestre si pas de semestres
|
||||
|
||||
# Regles gestion parcours
|
||||
# Règles gestion parcours
|
||||
class DUTRule(object):
|
||||
def __init__(self, rule_id, premise, conclusion):
|
||||
self.rule_id = rule_id
|
||||
|
@ -221,13 +222,13 @@ class DUTRule(object):
|
|||
def match(self, state):
|
||||
"True if state match rule premise"
|
||||
assert len(state) == len(self.premise)
|
||||
for i in range(len(state)):
|
||||
for i, stat in enumerate(state):
|
||||
prem = self.premise[i]
|
||||
if isinstance(prem, (list, tuple)):
|
||||
if not state[i] in prem:
|
||||
if not stat in prem:
|
||||
return False
|
||||
else:
|
||||
if prem != ALL and prem != state[i]:
|
||||
if prem not in (ALL, stat):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
@ -243,6 +244,7 @@ class TypeParcours(object):
|
|||
COMPENSATION_UE = True # inutilisé
|
||||
BARRE_MOY = 10.0
|
||||
BARRE_UE_DEFAULT = 8.0
|
||||
BARRE_UE_DISPLAY_WARNING = 8.0
|
||||
BARRE_UE = {}
|
||||
NOTES_BARRE_VALID_UE_TH = 10.0 # seuil pour valider UE
|
||||
NOTES_BARRE_VALID_UE = NOTES_BARRE_VALID_UE_TH - NOTES_TOLERANCE # barre sur UE
|
||||
|
@ -258,6 +260,7 @@ class TypeParcours(object):
|
|||
) # par defaut, autorise tous les types d'UE
|
||||
APC_SAE = False # Approche par compétences avec ressources et SAÉs
|
||||
USE_REFERENTIEL_COMPETENCES = False # Lien avec ref. comp.
|
||||
ECTS_FONDAMENTAUX_PER_YEAR = 0.0 # pour ISCID, deprecated
|
||||
|
||||
def check(self, formation=None):
|
||||
return True, "" # status, diagnostic_message
|
||||
|
@ -280,7 +283,7 @@ class TypeParcours(object):
|
|||
return [
|
||||
ue_status
|
||||
for ue_status in ues_status
|
||||
if ue_status["coef_ue"] > 0
|
||||
if ue_status["coef_ue"]
|
||||
and isinstance(ue_status["moy"], float)
|
||||
and ue_status["moy"] < self.get_barre_ue(ue_status["ue"]["type"])
|
||||
]
|
||||
|
@ -585,7 +588,7 @@ class ParcoursILEPS(TypeParcours):
|
|||
# SESSION_ABBRV = 'A' # A1, A2, ...
|
||||
COMPENSATION_UE = False
|
||||
UNUSED_CODES = set((ADC, ATT, ATB, ATJ))
|
||||
ALLOWED_UE_TYPES = [UE_STANDARD, UE_OPTIONNELLE]
|
||||
ALLOWED_UE_TYPES = [UE_STANDARD, UE_OPTIONNELLE, UE_SPORT]
|
||||
# Barre moy gen. pour validation semestre:
|
||||
BARRE_MOY = 10.0
|
||||
# Barre pour UE ILEPS: 8/20 pour UE standards ("fondamentales")
|
||||
|
|
|
@ -46,7 +46,9 @@ CONFIG.LOGO_HEADER_HEIGHT = 28
|
|||
#
|
||||
# server_url: URL du serveur ScoDoc
|
||||
# scodoc_name: le nom du logiciel (ScoDoc actuellement, voir sco_version.py)
|
||||
CONFIG.DEFAULT_PDF_FOOTER_TEMPLATE = "Edité par %(scodoc_name)s le %(day)s/%(month)s/%(year)s à %(hour)sh%(minute)s sur %(server_url)s"
|
||||
CONFIG.DEFAULT_PDF_FOOTER_TEMPLATE = (
|
||||
"Edité par %(scodoc_name)s le %(day)s/%(month)s/%(year)s à %(hour)sh%(minute)s"
|
||||
)
|
||||
|
||||
|
||||
# ------------- Capitalisation des UEs -------------
|
||||
|
|
|
@ -152,28 +152,3 @@ class LogoInsert(Action):
|
|||
name=self.parameters["name"],
|
||||
dept_id=dept_id,
|
||||
)
|
||||
|
||||
|
||||
class BonusSportUpdate(Action):
|
||||
"""Action: Change bonus_sport_function_name.
|
||||
bonus_sport_function_name: the new value"""
|
||||
|
||||
def __init__(self, parameters):
|
||||
super().__init__(
|
||||
f"Changement du calcul de bonus sport pour ({parameters['bonus_sport_func_name']}).",
|
||||
parameters,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def build_action(parameters):
|
||||
if (
|
||||
parameters["bonus_sport_func_name"]
|
||||
!= ScoDocSiteConfig.get_bonus_sport_func_name()
|
||||
):
|
||||
return [BonusSportUpdate(parameters)]
|
||||
return []
|
||||
|
||||
def execute(self):
|
||||
current_app.logger.info(self.message)
|
||||
ScoDocSiteConfig.set_bonus_sport_func(self.parameters["bonus_sport_func_name"])
|
||||
app.clear_scodoc_cache()
|
||||
|
|
|
@ -65,7 +65,7 @@ def formsemestre_table_estim_cost(
|
|||
Mod = M["module"]
|
||||
T.append(
|
||||
{
|
||||
"code": Mod["code"],
|
||||
"code": Mod["code"] or "",
|
||||
"titre": Mod["titre"],
|
||||
"heures_cours": Mod["heures_cours"],
|
||||
"heures_td": Mod["heures_td"] * n_group_td,
|
||||
|
|
|
@ -31,15 +31,17 @@ Rapport (table) avec dernier semestre fréquenté et débouché de chaque étudi
|
|||
import http
|
||||
from flask import url_for, g, request
|
||||
|
||||
from app import log
|
||||
from app.comp import res_sem
|
||||
from app.comp.res_compat import NotesTableCompat
|
||||
from app.models import FormSemestre
|
||||
import app.scodoc.sco_utils as scu
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app import log
|
||||
from app.scodoc.sco_exceptions import AccessDenied
|
||||
from app.scodoc.scolog import logdb
|
||||
from app.scodoc.gen_tables import GenTable
|
||||
from app.scodoc import safehtml
|
||||
from app.scodoc import html_sco_header
|
||||
from app.scodoc import sco_cache
|
||||
from app.scodoc import sco_permissions_check
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc import sco_tag_module
|
||||
|
@ -115,7 +117,7 @@ def get_etudids_with_debouche(start_year):
|
|||
|
||||
|
||||
def table_debouche_etudids(etudids, keep_numeric=True):
|
||||
"""Rapport pour ces etudiants"""
|
||||
"""Rapport pour ces étudiants"""
|
||||
L = []
|
||||
for etudid in etudids:
|
||||
etud = sco_etud.get_etud_info(filled=True, etudid=etudid)[0]
|
||||
|
@ -124,7 +126,8 @@ def table_debouche_etudids(etudids, keep_numeric=True):
|
|||
es = [(s["date_fin_iso"], i) for i, s in enumerate(sems)]
|
||||
imax = max(es)[1]
|
||||
last_sem = sems[imax]
|
||||
nt = sco_cache.NotesTableCache.get(last_sem["formsemestre_id"])
|
||||
formsemestre = FormSemestre.query.get_or_404(last_sem["formsemestre_id"])
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
row = {
|
||||
"etudid": etudid,
|
||||
"civilite": etud["civilite"],
|
||||
|
|
|
@ -56,7 +56,7 @@ def index_html(showcodes=0, showsemtable=0):
|
|||
H.append(sco_news.scolar_news_summary_html())
|
||||
|
||||
# Avertissement de mise à jour:
|
||||
H.append(sco_up_to_date.html_up_to_date_box())
|
||||
H.append("""<div id="update_warning"></div>""")
|
||||
|
||||
# Liste de toutes les sessions:
|
||||
sems = sco_formsemestre.do_formsemestre_list()
|
||||
|
@ -293,7 +293,6 @@ def delete_dept(dept_id: int):
|
|||
"create temp table formsemestres_temp as select id from notes_formsemestre where dept_id = %(dept_id)s",
|
||||
"create temp table moduleimpls_temp as select id from notes_moduleimpl where formsemestre_id in (select id from formsemestres_temp)",
|
||||
"create temp table formations_temp as select id from notes_formations where dept_id = %(dept_id)s",
|
||||
"create temp table entreprises_temp as select id from entreprises where dept_id = %(dept_id)s",
|
||||
"create temp table tags_temp as select id from notes_tags where dept_id = %(dept_id)s",
|
||||
]
|
||||
for r in reqs:
|
||||
|
@ -345,13 +344,9 @@ def delete_dept(dept_id: int):
|
|||
"delete from notes_formsemestre where dept_id = %(dept_id)s",
|
||||
"delete from scolar_news where dept_id = %(dept_id)s",
|
||||
"delete from notes_semset where dept_id = %(dept_id)s",
|
||||
"delete from entreprise_contact where entreprise_id in (select id from entreprises_temp) ",
|
||||
"delete from entreprise_correspondant where entreprise_id in (select id from entreprises_temp) ",
|
||||
"delete from entreprises where dept_id = %(dept_id)s",
|
||||
"delete from notes_formations where dept_id = %(dept_id)s",
|
||||
"delete from departement where id = %(dept_id)s",
|
||||
"drop table tags_temp",
|
||||
"drop table entreprises_temp",
|
||||
"drop table formations_temp",
|
||||
"drop table moduleimpls_temp",
|
||||
"drop table etudids_temp",
|
||||
|
|
|
@ -51,13 +51,12 @@ import fcntl
|
|||
import subprocess
|
||||
import requests
|
||||
|
||||
from flask import g, request
|
||||
from flask_login import current_user
|
||||
|
||||
import app.scodoc.notesdb as ndb
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app import log
|
||||
from app.scodoc import html_sco_header
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc import sco_users
|
||||
import sco_version
|
||||
from app.scodoc.sco_exceptions import ScoValueError
|
||||
|
@ -65,10 +64,9 @@ from app.scodoc.sco_exceptions import ScoValueError
|
|||
SCO_DUMP_LOCK = "/tmp/scodump.lock"
|
||||
|
||||
|
||||
def sco_dump_and_send_db():
|
||||
def sco_dump_and_send_db(message: str = "", request_url: str = ""):
|
||||
"""Dump base de données et l'envoie anonymisée pour debug"""
|
||||
H = [html_sco_header.sco_header(page_title="Assistance technique")]
|
||||
# get currect (dept) DB name:
|
||||
# get current (dept) DB name:
|
||||
cursor = ndb.SimpleQuery("SELECT current_database()", {})
|
||||
db_name = cursor.fetchone()[0]
|
||||
ano_db_name = "ANO" + db_name
|
||||
|
@ -94,28 +92,8 @@ def sco_dump_and_send_db():
|
|||
_anonymize_db(ano_db_name)
|
||||
|
||||
# Send
|
||||
r = _send_db(ano_db_name)
|
||||
if (
|
||||
r.status_code
|
||||
== requests.codes.INSUFFICIENT_STORAGE # pylint: disable=no-member
|
||||
):
|
||||
H.append(
|
||||
"""<p class="warning">
|
||||
Erreur: espace serveur trop plein.
|
||||
Merci de contacter <a href="mailto:{0}">{0}</a></p>""".format(
|
||||
scu.SCO_DEV_MAIL
|
||||
)
|
||||
)
|
||||
elif r.status_code == requests.codes.OK: # pylint: disable=no-member
|
||||
H.append("""<p>Opération effectuée.</p>""")
|
||||
else:
|
||||
H.append(
|
||||
"""<p class="warning">
|
||||
Erreur: code <tt>{0} {1}</tt>
|
||||
Merci de contacter <a href="mailto:{2}">{2}</a></p>""".format(
|
||||
r.status_code, r.reason, scu.SCO_DEV_MAIL
|
||||
)
|
||||
)
|
||||
r = _send_db(ano_db_name, message, request_url)
|
||||
code = r.status_code
|
||||
|
||||
finally:
|
||||
# Drop anonymized database
|
||||
|
@ -124,7 +102,8 @@ def sco_dump_and_send_db():
|
|||
fcntl.flock(x, fcntl.LOCK_UN)
|
||||
|
||||
log("sco_dump_and_send_db: done.")
|
||||
return "\n".join(H) + html_sco_header.sco_footer()
|
||||
|
||||
return code
|
||||
|
||||
|
||||
def _duplicate_db(db_name, ano_db_name):
|
||||
|
@ -173,7 +152,7 @@ def _get_scodoc_serial():
|
|||
return 0
|
||||
|
||||
|
||||
def _send_db(ano_db_name):
|
||||
def _send_db(ano_db_name: str, message: str = "", request_url: str = ""):
|
||||
"""Dump this (anonymized) database and send it to tech support"""
|
||||
log(f"dumping anonymized database {ano_db_name}")
|
||||
try:
|
||||
|
@ -182,22 +161,36 @@ def _send_db(ano_db_name):
|
|||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
log(f"sco_dump_and_send_db: exception in anonymisation: {e}")
|
||||
raise ScoValueError(f"erreur lors de l'anonymisation de la base {ano_db_name}")
|
||||
raise ScoValueError(
|
||||
f"erreur lors de l'anonymisation de la base {ano_db_name}"
|
||||
) from e
|
||||
|
||||
log("uploading anonymized dump...")
|
||||
files = {"file": (ano_db_name + ".dump", dump)}
|
||||
r = requests.post(
|
||||
scu.SCO_DUMP_UP_URL,
|
||||
files=files,
|
||||
data={
|
||||
"dept_name": sco_preferences.get_preference("DeptName"),
|
||||
"serial": _get_scodoc_serial(),
|
||||
"sco_user": str(current_user),
|
||||
"sent_by": sco_users.user_info(str(current_user))["nomcomplet"],
|
||||
"sco_version": sco_version.SCOVERSION,
|
||||
"sco_fullversion": scu.get_scodoc_version(),
|
||||
},
|
||||
)
|
||||
try:
|
||||
r = requests.post(
|
||||
scu.SCO_DUMP_UP_URL,
|
||||
files=files,
|
||||
data={
|
||||
"dept_name": getattr(g, "scodoc_dept", "-"),
|
||||
"message": message or "",
|
||||
"request_url": request_url or request.url,
|
||||
"serial": _get_scodoc_serial(),
|
||||
"sco_user": str(current_user),
|
||||
"sent_by": sco_users.user_info(str(current_user))["nomcomplet"],
|
||||
"sco_version": sco_version.SCOVERSION,
|
||||
"sco_fullversion": scu.get_scodoc_version(),
|
||||
},
|
||||
)
|
||||
except requests.exceptions.ConnectionError as exc:
|
||||
raise ScoValueError(
|
||||
"""
|
||||
Impossible de joindre le serveur d'assistance (scodoc.org).
|
||||
Veuillez contacter le service informatique de votre établissement pour
|
||||
corriger la configuration de ScoDoc. Dans la plupart des cas, il
|
||||
s'agit d'un proxy mal configuré.
|
||||
"""
|
||||
) from exc
|
||||
return r
|
||||
|
||||
|
||||
|
|
|
@ -32,7 +32,8 @@ from flask_login import current_user
|
|||
|
||||
from app import db
|
||||
from app.models import Formation, UniteEns, Matiere, Module, FormSemestre, ModuleImpl
|
||||
from app.models.notes import ScolarFormSemestreValidation
|
||||
from app.models.validations import ScolarFormSemestreValidation
|
||||
from app.scodoc.sco_codes_parcours import UE_SPORT
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc import sco_groups
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
|
@ -51,6 +52,7 @@ def html_edit_formation_apc(
|
|||
"""
|
||||
parcours = formation.get_parcours()
|
||||
assert parcours.APC_SAE
|
||||
|
||||
ressources = formation.modules.filter_by(module_type=ModuleType.RESSOURCE).order_by(
|
||||
Module.semestre_id, Module.numero, Module.code
|
||||
)
|
||||
|
@ -67,6 +69,19 @@ def html_edit_formation_apc(
|
|||
).order_by(
|
||||
Module.semestre_id, Module.module_type.desc(), Module.numero, Module.code
|
||||
)
|
||||
|
||||
ues_by_sem = {}
|
||||
ects_by_sem = {}
|
||||
for semestre_idx in semestre_ids:
|
||||
ues_by_sem[semestre_idx] = formation.ues.filter_by(
|
||||
semestre_idx=semestre_idx
|
||||
).order_by(UniteEns.semestre_idx, UniteEns.numero, UniteEns.acronyme)
|
||||
ects = [ue.ects for ue in ues_by_sem[semestre_idx]]
|
||||
if None in ects:
|
||||
ects_by_sem[semestre_idx] = '<span class="missing_ue_ects">manquant</span>'
|
||||
else:
|
||||
ects_by_sem[semestre_idx] = sum(ects)
|
||||
|
||||
arrow_up, arrow_down, arrow_none = sco_groups.get_arrow_icons_tags()
|
||||
|
||||
icons = {
|
||||
|
@ -92,19 +107,27 @@ def html_edit_formation_apc(
|
|||
editable=editable,
|
||||
tag_editable=tag_editable,
|
||||
icons=icons,
|
||||
UniteEns=UniteEns,
|
||||
ues_by_sem=ues_by_sem,
|
||||
ects_by_sem=ects_by_sem,
|
||||
),
|
||||
]
|
||||
for semestre_idx in semestre_ids:
|
||||
ressources_in_sem = ressources.filter_by(semestre_id=semestre_idx)
|
||||
saes_in_sem = saes.filter_by(semestre_id=semestre_idx)
|
||||
other_modules_in_sem = other_modules.filter_by(semestre_id=semestre_idx)
|
||||
matiere_parent = Matiere.query.filter(
|
||||
Matiere.ue_id == UniteEns.id,
|
||||
UniteEns.formation_id == formation.id,
|
||||
UniteEns.semestre_idx == semestre_idx,
|
||||
UniteEns.type != UE_SPORT,
|
||||
).first()
|
||||
H += [
|
||||
render_template(
|
||||
"pn/form_mods.html",
|
||||
formation=formation,
|
||||
titre=f"Ressources du S{semestre_idx}",
|
||||
create_element_msg="créer une nouvelle ressource",
|
||||
matiere_parent=matiere_parent,
|
||||
modules=ressources_in_sem,
|
||||
module_type=ModuleType.RESSOURCE,
|
||||
editable=editable,
|
||||
|
@ -117,6 +140,7 @@ def html_edit_formation_apc(
|
|||
formation=formation,
|
||||
titre=f"Situations d'Apprentissage et d'Évaluation (SAÉs) S{semestre_idx}",
|
||||
create_element_msg="créer une nouvelle SAÉ",
|
||||
matiere_parent=matiere_parent,
|
||||
modules=saes_in_sem,
|
||||
module_type=ModuleType.SAE,
|
||||
editable=editable,
|
||||
|
@ -142,7 +166,7 @@ def html_edit_formation_apc(
|
|||
|
||||
|
||||
def html_ue_infos(ue):
|
||||
"""page d'information sur une UE"""
|
||||
"""Page d'information sur une UE"""
|
||||
from app.views import ScoData
|
||||
|
||||
formsemestres = (
|
||||
|
@ -165,7 +189,6 @@ def html_ue_infos(ue):
|
|||
)
|
||||
return render_template(
|
||||
"pn/ue_infos.html",
|
||||
# "pn/tmp.html",
|
||||
titre=f"UE {ue.acronyme} {ue.titre}",
|
||||
ue=ue,
|
||||
formsemestres=formsemestres,
|
||||
|
|
|
@ -36,6 +36,7 @@ from app import log
|
|||
from app.models import SHORT_STR_LEN
|
||||
from app.models.formations import Formation
|
||||
from app.models.modules import Module
|
||||
from app.models.ues import UniteEns
|
||||
|
||||
import app.scodoc.notesdb as ndb
|
||||
import app.scodoc.sco_utils as scu
|
||||
|
@ -340,6 +341,7 @@ def module_move(module_id, after=0, redirect=True):
|
|||
db.session.add(module)
|
||||
db.session.add(neigh)
|
||||
db.session.commit()
|
||||
module.formation.invalidate_cached_sems()
|
||||
# redirect to ue_list page:
|
||||
if redirect:
|
||||
return flask.redirect(
|
||||
|
@ -354,16 +356,18 @@ def module_move(module_id, after=0, redirect=True):
|
|||
|
||||
def ue_move(ue_id, after=0, redirect=1):
|
||||
"""Move UE before/after previous one (decrement/increment numero)"""
|
||||
o = sco_edit_ue.ue_list({"ue_id": ue_id})[0]
|
||||
# log('ue_move %s (#%s) after=%s' % (ue_id, o['numero'], after))
|
||||
ue = UniteEns.query.get_or_404(ue_id)
|
||||
redirect = int(redirect)
|
||||
after = int(after) # 0: deplace avant, 1 deplace apres
|
||||
if after not in (0, 1):
|
||||
raise ValueError('invalid value for "after"')
|
||||
formation_id = o["formation_id"]
|
||||
others = sco_edit_ue.ue_list({"formation_id": formation_id})
|
||||
others = ue.formation.ues.order_by(UniteEns.numero).all()
|
||||
if len({o.numero for o in others}) != len(others):
|
||||
# il y a des numeros identiques !
|
||||
scu.objects_renumber(db, others)
|
||||
ue.formation.invalidate_cached_sems()
|
||||
if len(others) > 1:
|
||||
idx = [p["ue_id"] for p in others].index(ue_id)
|
||||
idx = [u.id for u in others].index(ue.id)
|
||||
neigh = None # object to swap with
|
||||
if after == 0 and idx > 0:
|
||||
neigh = others[idx - 1]
|
||||
|
@ -371,20 +375,19 @@ def ue_move(ue_id, after=0, redirect=1):
|
|||
neigh = others[idx + 1]
|
||||
if neigh: #
|
||||
# swap numero between partition and its neighbor
|
||||
# log('moving ue %s (neigh #%s)' % (ue_id, neigh['numero']))
|
||||
cnx = ndb.GetDBConnexion()
|
||||
o["numero"], neigh["numero"] = neigh["numero"], o["numero"]
|
||||
if o["numero"] == neigh["numero"]:
|
||||
neigh["numero"] -= 2 * after - 1
|
||||
sco_edit_ue._ueEditor.edit(cnx, o)
|
||||
sco_edit_ue._ueEditor.edit(cnx, neigh)
|
||||
ue.numero, neigh.numero = neigh.numero, ue.numero
|
||||
db.session.add(ue)
|
||||
db.session.add(neigh)
|
||||
db.session.commit()
|
||||
ue.formation.invalidate_cached_sems()
|
||||
|
||||
# redirect to ue_list page
|
||||
if redirect:
|
||||
return flask.redirect(
|
||||
url_for(
|
||||
"notes.ue_table",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formation_id=o["formation_id"],
|
||||
semestre_idx=o["semestre_idx"],
|
||||
formation_id=ue.formation_id,
|
||||
semestre_idx=ue.semestre_idx,
|
||||
)
|
||||
)
|
||||
|
|
|
@ -88,13 +88,14 @@ def do_matiere_create(args):
|
|||
r = _matiereEditor.create(cnx, args)
|
||||
|
||||
# news
|
||||
F = sco_formations.formation_list(args={"formation_id": ue["formation_id"]})[0]
|
||||
formation = Formation.query.get(ue["formation_id"])
|
||||
sco_news.add(
|
||||
typ=sco_news.NEWS_FORM,
|
||||
object=ue["formation_id"],
|
||||
text="Modification de la formation %(acronyme)s" % F,
|
||||
text=f"Modification de la formation {formation.acronyme}",
|
||||
max_frequency=3,
|
||||
)
|
||||
formation.invalidate_cached_sems()
|
||||
return r
|
||||
|
||||
|
||||
|
@ -195,13 +196,14 @@ def do_matiere_delete(oid):
|
|||
_matiereEditor.delete(cnx, oid)
|
||||
|
||||
# news
|
||||
F = sco_formations.formation_list(args={"formation_id": ue["formation_id"]})[0]
|
||||
formation = Formation.query.get(ue["formation_id"])
|
||||
sco_news.add(
|
||||
typ=sco_news.NEWS_FORM,
|
||||
object=ue["formation_id"],
|
||||
text="Modification de la formation %(acronyme)s" % F,
|
||||
text=f"Modification de la formation {formation.acronyme}",
|
||||
max_frequency=3,
|
||||
)
|
||||
formation.invalidate_cached_sems()
|
||||
|
||||
|
||||
def matiere_delete(matiere_id=None):
|
||||
|
|
|
@ -41,7 +41,6 @@ from app.models import FormSemestre, ModuleImpl
|
|||
|
||||
import app.scodoc.notesdb as ndb
|
||||
import app.scodoc.sco_utils as scu
|
||||
from app.scodoc.sco_utils import ModuleType
|
||||
from app.scodoc.TrivialFormulator import TrivialFormulator
|
||||
from app.scodoc.sco_permissions import Permission
|
||||
from app.scodoc.sco_exceptions import (
|
||||
|
@ -105,32 +104,38 @@ def do_module_create(args) -> int:
|
|||
r = _moduleEditor.create(cnx, args)
|
||||
|
||||
# news
|
||||
F = sco_formations.formation_list(args={"formation_id": args["formation_id"]})[0]
|
||||
formation = Formation.query.get(args["formation_id"])
|
||||
sco_news.add(
|
||||
typ=sco_news.NEWS_FORM,
|
||||
object=args["formation_id"],
|
||||
text="Modification de la formation %(acronyme)s" % F,
|
||||
object=formation.id,
|
||||
text=f"Modification de la formation {formation.acronyme}",
|
||||
max_frequency=3,
|
||||
)
|
||||
formation.invalidate_cached_sems()
|
||||
return r
|
||||
|
||||
|
||||
def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
||||
"""Création d'un module"""
|
||||
from app.scodoc import sco_formations
|
||||
from app.scodoc import sco_edit_ue
|
||||
|
||||
matiere = Matiere.query.get_or_404(matiere_id)
|
||||
if matiere is None:
|
||||
raise ScoValueError("invalid matiere !")
|
||||
ue = matiere.ue
|
||||
parcours = ue.formation.get_parcours()
|
||||
def module_create(
|
||||
matiere_id=None, module_type=None, semestre_id=None, formation_id=None
|
||||
):
|
||||
"""Formulaire de création d'un module
|
||||
Si matiere_id est spécifié, le module sera créé dans cette matière (cas normal).
|
||||
Sinon, donne le choix de l'UE de rattachement et utilise la première
|
||||
matière de cette UE (si elle n'existe pas, la crée).
|
||||
"""
|
||||
if matiere_id:
|
||||
matiere = Matiere.query.get_or_404(matiere_id)
|
||||
ue = matiere.ue
|
||||
formation = ue.formation
|
||||
else:
|
||||
formation = Formation.query.get_or_404(formation_id)
|
||||
parcours = formation.get_parcours()
|
||||
is_apc = parcours.APC_SAE
|
||||
ues = ue.formation.ues.order_by(
|
||||
ues = formation.ues.order_by(
|
||||
UniteEns.semestre_idx, UniteEns.numero, UniteEns.acronyme
|
||||
).all()
|
||||
# cherche le numero adéquat (pour placer le module en fin de liste)
|
||||
modules = matiere.ue.formation.modules.all()
|
||||
modules = formation.modules.all()
|
||||
if modules:
|
||||
default_num = max([m.numero or 0 for m in modules]) + 10
|
||||
else:
|
||||
|
@ -143,14 +148,16 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
H = [
|
||||
html_sco_header.sco_header(page_title=f"Création {object_name}"),
|
||||
]
|
||||
if is_apc:
|
||||
if not matiere_id:
|
||||
H += [
|
||||
f"""<h2>Création {object_name} dans la formation {ue.formation.acronyme}</h2>"""
|
||||
f"""<h2>Création {object_name} dans la formation {formation.acronyme}
|
||||
</h2>
|
||||
"""
|
||||
]
|
||||
else:
|
||||
H += [
|
||||
f"""<h2>Création {object_name} dans la matière {matiere.titre},
|
||||
(UE {ue.acronyme})</h2>
|
||||
(UE {ue.acronyme}), semestre {ue.semestre_idx}</h2>
|
||||
"""
|
||||
]
|
||||
|
||||
|
@ -158,7 +165,6 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
render_template(
|
||||
"scodoc/help/modules.html",
|
||||
is_apc=is_apc,
|
||||
ue=ue,
|
||||
semestre_id=semestre_id,
|
||||
)
|
||||
]
|
||||
|
@ -170,7 +176,7 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
"size": 10,
|
||||
"explanation": "code du module, ressource ou SAÉ. Exemple M1203, R2.01, ou SAÉ 3.4. Ce code doit être unique dans la formation.",
|
||||
"allow_null": False,
|
||||
"validator": lambda val, field, formation_id=ue.formation_id: check_module_code_unicity(
|
||||
"validator": lambda val, field, formation_id=formation_id: check_module_code_unicity(
|
||||
val, field, formation_id
|
||||
),
|
||||
},
|
||||
|
@ -190,36 +196,16 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
},
|
||||
),
|
||||
]
|
||||
semestres_indices = list(range(1, parcours.NB_SEM + 1))
|
||||
if is_apc: # BUT: choix de l'UE de rattachement (qui donnera le semestre)
|
||||
descr += [
|
||||
(
|
||||
"ue_id",
|
||||
{
|
||||
"input_type": "menu",
|
||||
"type": "int",
|
||||
"title": "UE de rattachement",
|
||||
"explanation": "utilisée pour la présentation dans certains documents",
|
||||
"labels": [f"{u.acronyme} {u.titre}" for u in ues],
|
||||
"allowed_values": [u.id for u in ues],
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
if is_apc:
|
||||
module_types = scu.ModuleType # tous les types
|
||||
else:
|
||||
# Formations classiques: choix du semestre
|
||||
descr += [
|
||||
(
|
||||
"semestre_id",
|
||||
{
|
||||
"input_type": "menu",
|
||||
"type": "int",
|
||||
"title": parcours.SESSION_NAME.capitalize(),
|
||||
"explanation": "%s du module" % parcours.SESSION_NAME,
|
||||
"labels": [str(x) for x in semestres_indices],
|
||||
"allowed_values": semestres_indices,
|
||||
},
|
||||
),
|
||||
]
|
||||
# ne propose pas SAE et Ressources:
|
||||
module_types = set(scu.ModuleType) - {
|
||||
scu.ModuleType.RESSOURCE,
|
||||
scu.ModuleType.SAE,
|
||||
}
|
||||
|
||||
descr += [
|
||||
(
|
||||
"module_type",
|
||||
|
@ -227,8 +213,8 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
"input_type": "menu",
|
||||
"title": "Type",
|
||||
"explanation": "",
|
||||
"labels": [x.name.capitalize() for x in scu.ModuleType],
|
||||
"allowed_values": [str(int(x)) for x in scu.ModuleType],
|
||||
"labels": [x.name.capitalize() for x in module_types],
|
||||
"allowed_values": [str(int(x)) for x in module_types],
|
||||
},
|
||||
),
|
||||
(
|
||||
|
@ -284,11 +270,33 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
),
|
||||
]
|
||||
|
||||
if matiere_id:
|
||||
descr += [
|
||||
("ue_id", {"default": ue.id, "input_type": "hidden"}),
|
||||
("matiere_id", {"default": matiere_id, "input_type": "hidden"}),
|
||||
]
|
||||
else:
|
||||
# choix de l'UE de rattachement
|
||||
descr += [
|
||||
(
|
||||
"ue_id",
|
||||
{
|
||||
"input_type": "menu",
|
||||
"type": "int",
|
||||
"title": "UE de rattachement",
|
||||
"explanation": "utilisée notamment pour les malus",
|
||||
"labels": [
|
||||
f"S{u.semestre_idx if u.semestre_idx is not None else '.'} / {u.acronyme} {u.titre}"
|
||||
for u in ues
|
||||
],
|
||||
"allowed_values": [u.id for u in ues],
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
descr += [
|
||||
# ('ects', { 'size' : 4, 'type' : 'float', 'title' : 'ECTS', 'explanation' : 'nombre de crédits ECTS (inutilisés: les crédits sont associés aux UE)' }),
|
||||
("formation_id", {"default": ue.formation_id, "input_type": "hidden"}),
|
||||
("ue_id", {"default": ue.id, "input_type": "hidden"}),
|
||||
("matiere_id", {"default": matiere.id, "input_type": "hidden"}),
|
||||
("formation_id", {"default": formation.id, "input_type": "hidden"}),
|
||||
(
|
||||
"code_apogee",
|
||||
{
|
||||
|
@ -318,12 +326,21 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
if tf[0] == 0:
|
||||
return "\n".join(H) + tf[1] + html_sco_header.sco_footer()
|
||||
else:
|
||||
if is_apc:
|
||||
# BUT: l'UE indique le semestre
|
||||
selected_ue = UniteEns.query.get(tf[2]["ue_id"])
|
||||
if selected_ue is None:
|
||||
if not matiere_id:
|
||||
# formulaire avec choix UE de rattachement
|
||||
ue = UniteEns.query.get(tf[2]["ue_id"])
|
||||
if ue is None:
|
||||
raise ValueError("UE invalide")
|
||||
tf[2]["semestre_id"] = selected_ue.semestre_idx
|
||||
matiere = ue.matieres.first()
|
||||
if matiere:
|
||||
tf[2]["matiere_id"] = matiere.id
|
||||
else:
|
||||
matiere_id = sco_edit_matiere.do_matiere_create(
|
||||
{"ue_id": ue.id, "titre": ue.titre, "numero": 1},
|
||||
)
|
||||
tf[2]["matiere_id"] = matiere_id
|
||||
|
||||
tf[2]["semestre_id"] = ue.semestre_idx
|
||||
|
||||
_ = do_module_create(tf[2])
|
||||
|
||||
|
@ -331,7 +348,7 @@ def module_create(matiere_id=None, module_type=None, semestre_id=None):
|
|||
url_for(
|
||||
"notes.ue_table",
|
||||
scodoc_dept=g.scodoc_dept,
|
||||
formation_id=ue.formation_id,
|
||||
formation_id=formation.id,
|
||||
semestre_idx=tf[2]["semestre_id"],
|
||||
)
|
||||
)
|
||||
|
@ -378,13 +395,14 @@ def do_module_delete(oid):
|
|||
_moduleEditor.delete(cnx, oid)
|
||||
|
||||
# news
|
||||
F = sco_formations.formation_list(args={"formation_id": mod["formation_id"]})[0]
|
||||
formation = module.formation
|
||||
sco_news.add(
|
||||
typ=sco_news.NEWS_FORM,
|
||||
object=mod["formation_id"],
|
||||
text="Modification de la formation %(acronyme)s" % F,
|
||||
text=f"Modification de la formation {formation.acronyme}",
|
||||
max_frequency=3,
|
||||
)
|
||||
formation.invalidate_cached_sems()
|
||||
|
||||
|
||||
def module_delete(module_id=None):
|
||||
|
@ -433,8 +451,6 @@ def module_delete(module_id=None):
|
|||
|
||||
def do_module_edit(vals: dict) -> None:
|
||||
"edit a module"
|
||||
from app.scodoc import sco_edit_formation
|
||||
|
||||
# check
|
||||
mod = module_list({"module_id": vals["module_id"]})[0]
|
||||
if module_is_locked(mod["module_id"]):
|
||||
|
@ -476,38 +492,35 @@ def module_edit(module_id=None):
|
|||
parcours = sco_codes_parcours.get_parcours_from_code(formation["type_parcours"])
|
||||
is_apc = parcours.APC_SAE # BUT
|
||||
in_use = len(a_module.modimpls.all()) > 0 # il y a des modimpls
|
||||
matieres = Matiere.query.filter(
|
||||
Matiere.ue_id == UniteEns.id, UniteEns.formation_id == formation_id
|
||||
).order_by(UniteEns.semestre_idx, UniteEns.numero, Matiere.numero)
|
||||
if in_use:
|
||||
# matières du même semestre seulement
|
||||
ues_matieres = ndb.SimpleDictFetch(
|
||||
"""SELECT ue.acronyme, mat.*, mat.id AS matiere_id
|
||||
FROM notes_matieres mat, notes_ue ue
|
||||
WHERE mat.ue_id = ue.id
|
||||
AND ue.formation_id = %(formation_id)s
|
||||
AND ue.semestre_idx = %(semestre_idx)s
|
||||
ORDER BY ue.numero, mat.numero
|
||||
""",
|
||||
{"formation_id": formation_id, "semestre_idx": a_module.ue.semestre_idx},
|
||||
)
|
||||
# restreint aux matières du même semestre
|
||||
matieres = matieres.filter(UniteEns.semestre_idx == a_module.ue.semestre_idx)
|
||||
|
||||
if is_apc:
|
||||
# ne conserve que la 1ere matière de chaque UE,
|
||||
# et celle à laquelle ce module est rattaché
|
||||
matieres = [
|
||||
mat
|
||||
for mat in matieres
|
||||
if a_module.matiere.id == mat.id or mat.id == mat.ue.matieres.first().id
|
||||
]
|
||||
mat_names = [
|
||||
"S%s / %s" % (mat.ue.semestre_idx, mat.ue.acronyme) for mat in matieres
|
||||
]
|
||||
else:
|
||||
# matières de la formation
|
||||
ues_matieres = ndb.SimpleDictFetch(
|
||||
"""SELECT ue.acronyme, mat.*, mat.id AS matiere_id
|
||||
FROM notes_matieres mat, notes_ue ue
|
||||
WHERE mat.ue_id = ue.id
|
||||
AND ue.formation_id = %(formation_id)s
|
||||
ORDER BY ue.numero, mat.numero
|
||||
""",
|
||||
{"formation_id": formation_id},
|
||||
)
|
||||
mat_names = ["%s / %s" % (x["acronyme"], x["titre"]) for x in ues_matieres]
|
||||
ue_mat_ids = ["%s!%s" % (x["ue_id"], x["matiere_id"]) for x in ues_matieres]
|
||||
mat_names = ["%s / %s" % (mat.ue.acronyme, mat.titre or "") for mat in matieres]
|
||||
|
||||
ue_mat_ids = ["%s!%s" % (mat.ue.id, mat.id) for mat in matieres]
|
||||
module["ue_matiere_id"] = "%s!%s" % (module["ue_id"], module["matiere_id"])
|
||||
|
||||
semestres_indices = list(range(1, parcours.NB_SEM + 1))
|
||||
|
||||
H = [
|
||||
html_sco_header.sco_header(
|
||||
page_title="Modification du module %(titre)s" % module,
|
||||
page_title=f"Modification du module {a_module.code or a_module.titre or ''}",
|
||||
cssstyles=["libjs/jQuery-tagEditor/jquery.tag-editor.css"],
|
||||
javascripts=[
|
||||
"libjs/jQuery-tagEditor/jquery.tag-editor.min.js",
|
||||
|
@ -515,7 +528,7 @@ def module_edit(module_id=None):
|
|||
"js/module_tag_editor.js",
|
||||
],
|
||||
),
|
||||
"""<h2>Modification du module %(titre)s""" % module,
|
||||
f"""<h2>Modification du module {a_module.code or ''} {a_module.titre or ''}""",
|
||||
""" (formation %(acronyme)s, version %(version)s)</h2>""" % formation,
|
||||
render_template(
|
||||
"scodoc/help/modules.html",
|
||||
|
@ -523,26 +536,33 @@ def module_edit(module_id=None):
|
|||
formsemestres=FormSemestre.query.filter(
|
||||
ModuleImpl.formsemestre_id == FormSemestre.id,
|
||||
ModuleImpl.module_id == module_id,
|
||||
).all(),
|
||||
)
|
||||
.order_by(FormSemestre.date_debut)
|
||||
.all(),
|
||||
),
|
||||
]
|
||||
if not unlocked:
|
||||
H.append(
|
||||
"""<div class="ue_warning"><span>Formation verrouillée, seuls certains éléments peuvent être modifiés</span></div>"""
|
||||
)
|
||||
if in_use:
|
||||
H.append(
|
||||
"""<div class="ue_warning"><span>Module déjà utilisé dans des semestres,
|
||||
soyez prudents !
|
||||
</span></div>"""
|
||||
)
|
||||
if is_apc:
|
||||
module_types = scu.ModuleType # tous les types
|
||||
else:
|
||||
# ne propose pas SAE et Ressources, sauf si déjà de ce type...
|
||||
module_types = (
|
||||
set(scu.ModuleType) - {scu.ModuleType.RESSOURCE, scu.ModuleType.SAE}
|
||||
) | {
|
||||
scu.ModuleType(a_module.module_type)
|
||||
if a_module.module_type
|
||||
else scu.ModuleType.STANDARD
|
||||
}
|
||||
|
||||
descr = [
|
||||
(
|
||||
"code",
|
||||
{
|
||||
"size": 10,
|
||||
"explanation": "code du module (doit être unique dans la formation)",
|
||||
"explanation": "code du module (issu du programme, exemple M1203 ou R2.01. Doit être unique dans la formation)",
|
||||
"allow_null": False,
|
||||
"validator": lambda val, field, formation_id=formation_id: check_module_code_unicity(
|
||||
val, field, formation_id, module_id=module_id
|
||||
|
@ -557,18 +577,24 @@ def module_edit(module_id=None):
|
|||
"input_type": "menu",
|
||||
"title": "Type",
|
||||
"explanation": "",
|
||||
"labels": [x.name.capitalize() for x in scu.ModuleType],
|
||||
"allowed_values": [str(int(x)) for x in scu.ModuleType],
|
||||
"labels": [x.name.capitalize() for x in module_types],
|
||||
"allowed_values": [str(int(x)) for x in module_types],
|
||||
"enabled": unlocked,
|
||||
},
|
||||
),
|
||||
(
|
||||
"heures_cours",
|
||||
{"size": 4, "type": "float", "explanation": "nombre d'heures de cours"},
|
||||
{
|
||||
"title": "Heures CM :",
|
||||
"size": 4,
|
||||
"type": "float",
|
||||
"explanation": "nombre d'heures de cours",
|
||||
},
|
||||
),
|
||||
(
|
||||
"heures_td",
|
||||
{
|
||||
"title": "Heures TD :",
|
||||
"size": 4,
|
||||
"type": "float",
|
||||
"explanation": "nombre d'heures de Travaux Dirigés",
|
||||
|
@ -577,6 +603,7 @@ def module_edit(module_id=None):
|
|||
(
|
||||
"heures_tp",
|
||||
{
|
||||
"title": "Heures TP :",
|
||||
"size": 4,
|
||||
"type": "float",
|
||||
"explanation": "nombre d'heures de Travaux Pratiques",
|
||||
|
@ -584,9 +611,11 @@ def module_edit(module_id=None):
|
|||
),
|
||||
]
|
||||
if is_apc:
|
||||
coefs_descr = a_module.ue_coefs_descr()
|
||||
if coefs_descr:
|
||||
coefs_descr_txt = ", ".join(["%s: %s" % x for x in coefs_descr])
|
||||
coefs_lst = a_module.ue_coefs_list()
|
||||
if coefs_lst:
|
||||
coefs_descr_txt = ", ".join(
|
||||
[f"{ue.acronyme}: {c}" for (ue, c) in coefs_lst]
|
||||
)
|
||||
else:
|
||||
coefs_descr_txt = """<span class="missing_value">non définis</span>"""
|
||||
descr += [
|
||||
|
@ -594,9 +623,9 @@ def module_edit(module_id=None):
|
|||
"ue_coefs",
|
||||
{
|
||||
"readonly": True,
|
||||
"title": "Coefficients vers les UE",
|
||||
"title": "Coefficients vers les UE ",
|
||||
"default": coefs_descr_txt,
|
||||
"explanation": "passer par la page d'édition de la formation pour modifier les coefficients",
|
||||
"explanation": " <br>(passer par la page d'édition de la formation pour modifier les coefficients)",
|
||||
},
|
||||
)
|
||||
]
|
||||
|
@ -622,7 +651,14 @@ def module_edit(module_id=None):
|
|||
{
|
||||
"input_type": "menu",
|
||||
"title": "Rattachement :" if is_apc else "Matière :",
|
||||
"explanation": "UE de rattachement, utilisée pour la présentation"
|
||||
"explanation": (
|
||||
"UE de rattachement"
|
||||
+ (
|
||||
" module utilisé, ne peut pas être changé de semestre"
|
||||
if in_use
|
||||
else ""
|
||||
)
|
||||
)
|
||||
if is_apc
|
||||
else "un module appartient à une seule matière.",
|
||||
"labels": mat_names,
|
||||
|
@ -665,7 +701,10 @@ def module_edit(module_id=None):
|
|||
{
|
||||
"title": "Code Apogée",
|
||||
"size": 25,
|
||||
"explanation": "(optionnel) code élément pédagogique Apogée ou liste de codes ELP séparés par des virgules",
|
||||
"explanation": """(optionnel) code élément pédagogique Apogée ou liste de codes ELP
|
||||
séparés par des virgules (ce code est propre à chaque établissement, se rapprocher
|
||||
du référent Apogée).
|
||||
""",
|
||||
"validator": lambda val, _: len(val) < APO_CODE_STR_LEN,
|
||||
},
|
||||
),
|
||||
|
@ -694,6 +733,7 @@ def module_edit(module_id=None):
|
|||
initvalues=module,
|
||||
submitlabel="Modifier ce module",
|
||||
)
|
||||
#
|
||||
if tf[0] == 0:
|
||||
return "\n".join(H) + tf[1] + html_sco_header.sco_footer()
|
||||
elif tf[0] == -1:
|
||||
|
@ -706,15 +746,20 @@ def module_edit(module_id=None):
|
|||
)
|
||||
)
|
||||
else:
|
||||
# l'UE peut changer
|
||||
# l'UE de rattachement peut changer
|
||||
tf[2]["ue_id"], tf[2]["matiere_id"] = tf[2]["ue_matiere_id"].split("!")
|
||||
x, y = tf[2]["ue_matiere_id"].split("!")
|
||||
tf[2]["ue_id"] = int(x)
|
||||
tf[2]["matiere_id"] = int(y)
|
||||
old_ue_id = a_module.ue.id
|
||||
new_ue_id = int(tf[2]["ue_id"])
|
||||
new_ue_id = tf[2]["ue_id"]
|
||||
if (old_ue_id != new_ue_id) and in_use:
|
||||
# pas changer de semestre un module utilisé !
|
||||
raise ScoValueError(
|
||||
"Module utilisé: il ne peut pas être changé de semestre !"
|
||||
)
|
||||
new_ue = UniteEns.query.get_or_404(new_ue_id)
|
||||
if new_ue.semestre_idx != a_module.ue.semestre_idx:
|
||||
# pas changer de semestre un module utilisé !
|
||||
raise ScoValueError(
|
||||
"Module utilisé: il ne peut pas être changé de semestre !"
|
||||
)
|
||||
# En APC, force le semestre égal à celui de l'UE
|
||||
if is_apc:
|
||||
selected_ue = UniteEns.query.get(tf[2]["ue_id"])
|
||||
|
@ -815,7 +860,7 @@ def formation_add_malus_modules(formation_id, titre=None, redirect=True):
|
|||
[
|
||||
mod
|
||||
for mod in module_list(args={"ue_id": ue["ue_id"]})
|
||||
if mod["module_type"] == ModuleType.MALUS
|
||||
if mod["module_type"] == scu.ModuleType.MALUS
|
||||
]
|
||||
)
|
||||
if nb_mod_malus == 0:
|
||||
|
@ -867,7 +912,7 @@ def ue_add_malus_module(ue_id, titre=None, code=None):
|
|||
"matiere_id": matiere_id,
|
||||
"formation_id": ue["formation_id"],
|
||||
"semestre_id": semestre_id,
|
||||
"module_type": ModuleType.MALUS,
|
||||
"module_type": scu.ModuleType.MALUS,
|
||||
},
|
||||
)
|
||||
|
||||
|
|
|
@ -29,13 +29,13 @@
|
|||
|
||||
"""
|
||||
import flask
|
||||
from flask import url_for, render_template
|
||||
from flask import flash, render_template, url_for
|
||||
from flask import g, request
|
||||
from flask_login import current_user
|
||||
|
||||
from app import db
|
||||
from app import log
|
||||
from app.models import APO_CODE_STR_LEN
|
||||
from app.models import APO_CODE_STR_LEN, SHORT_STR_LEN
|
||||
from app.models import Formation, UniteEns, ModuleImpl, Module
|
||||
from app.models.formations import Matiere
|
||||
import app.scodoc.notesdb as ndb
|
||||
|
@ -83,11 +83,13 @@ _ueEditor = ndb.EditableTable(
|
|||
"is_external",
|
||||
"code_apogee",
|
||||
"coefficient",
|
||||
"color",
|
||||
),
|
||||
sortkey="numero",
|
||||
input_formators={
|
||||
"type": ndb.int_null_is_zero,
|
||||
"is_external": ndb.bool_or_str,
|
||||
"ects": ndb.float_null_is_null,
|
||||
},
|
||||
output_formators={
|
||||
"numero": ndb.int_null_is_zero,
|
||||
|
@ -106,8 +108,6 @@ def ue_list(*args, **kw):
|
|||
|
||||
def do_ue_create(args):
|
||||
"create an ue"
|
||||
from app.scodoc import sco_formations
|
||||
|
||||
cnx = ndb.GetDBConnexion()
|
||||
# check duplicates
|
||||
ues = ue_list({"formation_id": args["formation_id"], "acronyme": args["acronyme"]})
|
||||
|
@ -116,6 +116,14 @@ def do_ue_create(args):
|
|||
f"""Acronyme d'UE "{args['acronyme']}" déjà utilisé !
|
||||
(chaque UE doit avoir un acronyme unique dans la formation)"""
|
||||
)
|
||||
if not "ue_code" in args:
|
||||
# évite les conflits de code
|
||||
while True:
|
||||
cursor = db.session.execute("select notes_newid_ucod();")
|
||||
code = cursor.fetchone()[0]
|
||||
if UniteEns.query.filter_by(ue_code=code).count() == 0:
|
||||
break
|
||||
args["ue_code"] = code
|
||||
# create
|
||||
ue_id = _ueEditor.create(cnx, args)
|
||||
|
||||
|
@ -127,13 +135,16 @@ def do_ue_create(args):
|
|||
formation = Formation.query.get(args["formation_id"])
|
||||
formation.invalidate_module_coefs()
|
||||
# news
|
||||
F = sco_formations.formation_list(args={"formation_id": args["formation_id"]})[0]
|
||||
ue = UniteEns.query.get(ue_id)
|
||||
flash(f"UE créée (code {ue.ue_code})")
|
||||
formation = Formation.query.get(args["formation_id"])
|
||||
sco_news.add(
|
||||
typ=sco_news.NEWS_FORM,
|
||||
object=args["formation_id"],
|
||||
text="Modification de la formation %(acronyme)s" % F,
|
||||
text=f"Modification de la formation {formation.acronyme}",
|
||||
max_frequency=3,
|
||||
)
|
||||
formation.invalidate_cached_sems()
|
||||
return ue_id
|
||||
|
||||
|
||||
|
@ -230,27 +241,35 @@ def do_ue_delete(ue_id, delete_validations=False, force=False):
|
|||
return None
|
||||
|
||||
|
||||
def ue_create(formation_id=None):
|
||||
"""Creation d'une UE"""
|
||||
return ue_edit(create=True, formation_id=formation_id)
|
||||
def ue_create(formation_id=None, default_semestre_idx=None):
|
||||
"""Formulaire création d'une UE"""
|
||||
return ue_edit(
|
||||
create=True,
|
||||
formation_id=formation_id,
|
||||
default_semestre_idx=default_semestre_idx,
|
||||
)
|
||||
|
||||
|
||||
def ue_edit(ue_id=None, create=False, formation_id=None):
|
||||
"""Modification ou création d'une UE"""
|
||||
def ue_edit(ue_id=None, create=False, formation_id=None, default_semestre_idx=None):
|
||||
"""Formulaire modification ou création d'une UE"""
|
||||
create = int(create)
|
||||
if not create:
|
||||
U = ue_list(args={"ue_id": ue_id})
|
||||
if not U:
|
||||
raise ScoValueError("UE inexistante !")
|
||||
U = U[0]
|
||||
formation_id = U["formation_id"]
|
||||
title = "Modification de l'UE %(titre)s" % U
|
||||
initvalues = U
|
||||
ue: UniteEns = UniteEns.query.get_or_404(ue_id)
|
||||
ue_dict = ue.to_dict()
|
||||
formation_id = ue.formation_id
|
||||
title = f"Modification de l'UE {ue.acronyme} {ue.titre}"
|
||||
initvalues = ue_dict
|
||||
submitlabel = "Modifier les valeurs"
|
||||
can_change_semestre_id = (ue.modules.count() == 0) or (ue.semestre_idx is None)
|
||||
else:
|
||||
ue = None
|
||||
title = "Création d'une UE"
|
||||
initvalues = {}
|
||||
initvalues = {
|
||||
"semestre_idx": default_semestre_idx,
|
||||
"color": ue_guess_color_default(formation_id, default_semestre_idx),
|
||||
}
|
||||
submitlabel = "Créer cette UE"
|
||||
can_change_semestre_id = True
|
||||
formation = Formation.query.get(formation_id)
|
||||
if not formation:
|
||||
raise ScoValueError(f"Formation inexistante ! (id={formation_id})")
|
||||
|
@ -277,7 +296,7 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
ue_types_names = [sco_codes_parcours.UE_TYPE_NAME[k] for k in ue_types]
|
||||
ue_types = [str(x) for x in ue_types]
|
||||
|
||||
fw = [
|
||||
form_descr = [
|
||||
("ue_id", {"input_type": "hidden"}),
|
||||
("create", {"input_type": "hidden", "default": create}),
|
||||
("formation_id", {"input_type": "hidden", "default": formation_id}),
|
||||
|
@ -286,23 +305,33 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
(
|
||||
"numero",
|
||||
{
|
||||
"size": 2,
|
||||
"size": 4,
|
||||
"explanation": "numéro (1,2,3,4) de l'UE pour l'ordre d'affichage",
|
||||
"type": "int",
|
||||
},
|
||||
),
|
||||
(
|
||||
"semestre_idx",
|
||||
{
|
||||
"input_type": "menu",
|
||||
"type": "int",
|
||||
"allow_null": False,
|
||||
"title": parcours.SESSION_NAME.capitalize(),
|
||||
"explanation": "%s de l'UE dans la formation" % parcours.SESSION_NAME,
|
||||
"labels": ["non spécifié"] + [str(x) for x in semestres_indices],
|
||||
"allowed_values": [""] + semestres_indices,
|
||||
},
|
||||
),
|
||||
]
|
||||
if can_change_semestre_id:
|
||||
form_descr += [
|
||||
(
|
||||
"semestre_idx",
|
||||
{
|
||||
"input_type": "menu",
|
||||
"type": "int",
|
||||
"allow_null": False,
|
||||
"title": parcours.SESSION_NAME.capitalize(),
|
||||
"explanation": "%s de l'UE dans la formation"
|
||||
% parcours.SESSION_NAME,
|
||||
"labels": ["non spécifié"] + [str(x) for x in semestres_indices],
|
||||
"allowed_values": [""] + semestres_indices,
|
||||
},
|
||||
),
|
||||
]
|
||||
else:
|
||||
form_descr += [
|
||||
("semestre_idx", {"default": ue.semestre_idx, "input_type": "hidden"}),
|
||||
]
|
||||
form_descr += [
|
||||
(
|
||||
"type",
|
||||
{
|
||||
|
@ -318,7 +347,8 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
"size": 4,
|
||||
"type": "float",
|
||||
"title": "ECTS",
|
||||
"explanation": "nombre de crédits ECTS",
|
||||
"explanation": "nombre de crédits ECTS (indiquer 0 si UE bonus)",
|
||||
"allow_null": not is_apc, # ects requis en APC
|
||||
},
|
||||
),
|
||||
(
|
||||
|
@ -332,7 +362,9 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
la moyenne générale</em> est activée. Par défaut, le coefficient
|
||||
d'une UE est simplement la somme des coefficients des modules dans
|
||||
lesquels l'étudiant a des notes.
|
||||
Jamais utilisé en BUT.
|
||||
""",
|
||||
"enabled": not is_apc,
|
||||
},
|
||||
),
|
||||
(
|
||||
|
@ -340,7 +372,10 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
{
|
||||
"size": 12,
|
||||
"title": "Code UE",
|
||||
"explanation": "code interne (optionnel). Toutes les UE partageant le même code (et le même code de formation) sont compatibles (compensation de semestres, capitalisation d'UE). Voir liste ci-dessous.",
|
||||
"max_length": SHORT_STR_LEN,
|
||||
"explanation": """code interne (non vide). Toutes les UE partageant le même code
|
||||
(et le même code de formation) sont compatibles (compensation de semestres, capitalisation d'UE).
|
||||
Voir liste ci-dessous.""",
|
||||
},
|
||||
),
|
||||
(
|
||||
|
@ -349,7 +384,7 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
"title": "Code Apogée",
|
||||
"size": 25,
|
||||
"explanation": "(optionnel) code élément pédagogique Apogée ou liste de codes ELP séparés par des virgules",
|
||||
"validator": lambda val, _: len(val) < APO_CODE_STR_LEN,
|
||||
"max_length": APO_CODE_STR_LEN,
|
||||
},
|
||||
),
|
||||
(
|
||||
|
@ -360,9 +395,17 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
"explanation": "réservé pour les capitalisations d'UE effectuées à l'extérieur de l'établissement",
|
||||
},
|
||||
),
|
||||
(
|
||||
"color",
|
||||
{
|
||||
"input_type": "color",
|
||||
"title": "Couleur",
|
||||
"explanation": "pour affichages",
|
||||
},
|
||||
),
|
||||
]
|
||||
if create and not parcours.UE_IS_MODULE and not is_apc:
|
||||
fw.append(
|
||||
form_descr.append(
|
||||
(
|
||||
"create_matiere",
|
||||
{
|
||||
|
@ -376,14 +419,33 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
tf = TrivialFormulator(
|
||||
request.base_url,
|
||||
scu.get_request_args(),
|
||||
fw,
|
||||
form_descr,
|
||||
initvalues=initvalues,
|
||||
submitlabel=submitlabel,
|
||||
)
|
||||
if tf[0] == 0:
|
||||
X = """<div id="ue_list_code"></div>
|
||||
"""
|
||||
return "\n".join(H) + tf[1] + X + html_sco_header.sco_footer()
|
||||
if ue and ue.modules.count() and ue.semestre_idx is not None:
|
||||
modules_div = f"""<div id="ue_list_modules">
|
||||
<div><b>{ue.modules.count()} modules sont rattachés
|
||||
à cette UE</b> du semestre S{ue.semestre_idx},
|
||||
elle ne peut donc pas être changée de semestre.</div>
|
||||
<ul>"""
|
||||
for m in ue.modules:
|
||||
modules_div += f"""<li><a class="stdlink" href="{url_for(
|
||||
"notes.module_edit",scodoc_dept=g.scodoc_dept, module_id=m.id)}">{m.code} {m.titre}</a></li>"""
|
||||
modules_div += """</ul></div>"""
|
||||
else:
|
||||
modules_div = ""
|
||||
bonus_div = """<div id="bonus_description"></div>"""
|
||||
ue_div = """<div id="ue_list_code"></div>"""
|
||||
return (
|
||||
"\n".join(H)
|
||||
+ tf[1]
|
||||
+ modules_div
|
||||
+ bonus_div
|
||||
+ ue_div
|
||||
+ html_sco_header.sco_footer()
|
||||
)
|
||||
else:
|
||||
if create:
|
||||
if not tf[2]["ue_code"]:
|
||||
|
@ -413,8 +475,10 @@ def ue_edit(ue_id=None, create=False, formation_id=None):
|
|||
"semestre_id": tf[2]["semestre_idx"],
|
||||
},
|
||||
)
|
||||
flash("UE créée")
|
||||
else:
|
||||
do_ue_edit(tf[2])
|
||||
flash("UE modifiée")
|
||||
return flask.redirect(
|
||||
url_for(
|
||||
"notes.ue_table",
|
||||
|
@ -527,19 +591,22 @@ def ue_table(formation_id=None, semestre_idx=1, msg=""): # was ue_list
|
|||
semestre_ids = range(1, parcours.NB_SEM + 1)
|
||||
# transition: on requete ici via l'ORM mais on utilise les fonctions ScoDoc7
|
||||
# basées sur des dicts
|
||||
ues_obj = UniteEns.query.filter_by(formation_id=formation_id, is_external=False)
|
||||
ues_obj = UniteEns.query.filter_by(
|
||||
formation_id=formation_id, is_external=False
|
||||
).order_by(UniteEns.semestre_idx, UniteEns.numero)
|
||||
ues_externes_obj = UniteEns.query.filter_by(
|
||||
formation_id=formation_id, is_external=True
|
||||
)
|
||||
if is_apc:
|
||||
# pour faciliter la transition des anciens programmes non APC
|
||||
# Pour faciliter la transition des anciens programmes non APC
|
||||
for ue in ues_obj:
|
||||
ue.guess_semestre_idx()
|
||||
# vérifie qu'on a bien au moins une matière dans chaque UE
|
||||
for ue in ues_obj:
|
||||
# vérifie qu'on a bien au moins une matière dans chaque UE
|
||||
if ue.matieres.count() < 1:
|
||||
mat = Matiere(ue_id=ue.id)
|
||||
db.session.add(mat)
|
||||
# donne des couleurs aux UEs crées avant
|
||||
colorie_anciennes_ues(ues_obj)
|
||||
db.session.commit()
|
||||
ues = [ue.to_dict() for ue in ues_obj]
|
||||
ues_externes = [ue.to_dict() for ue in ues_externes_obj]
|
||||
|
@ -549,7 +616,12 @@ def ue_table(formation_id=None, semestre_idx=1, msg=""): # was ue_list
|
|||
_add_ue_semestre_id(ues_externes, is_apc)
|
||||
ues.sort(key=lambda u: (u["semestre_id"], u["numero"]))
|
||||
ues_externes.sort(key=lambda u: (u["semestre_id"], u["numero"]))
|
||||
has_duplicate_ue_codes = len(set([ue["ue_code"] for ue in ues])) != len(ues)
|
||||
# Codes dupliqués (pour aider l'utilisateur)
|
||||
seen = set()
|
||||
duplicated_codes = {
|
||||
ue["ue_code"] for ue in ues if ue["ue_code"] in seen or seen.add(ue["ue_code"])
|
||||
}
|
||||
ues_with_duplicated_code = [ue for ue in ues if ue["ue_code"] in duplicated_codes]
|
||||
|
||||
has_perm_change = current_user.has_permission(Permission.ScoChangeFormation)
|
||||
# editable = (not locked) and has_perm_change
|
||||
|
@ -612,11 +684,17 @@ du programme" (menu "Semestre") si vous avez un semestre en cours);
|
|||
if msg:
|
||||
H.append('<p class="msg">' + msg + "</p>")
|
||||
|
||||
if has_duplicate_ue_codes:
|
||||
if ues_with_duplicated_code:
|
||||
H.append(
|
||||
"""<div class="ue_warning"><span>Attention: plusieurs UE de cette
|
||||
formation ont le même code. Il faut corriger cela ci-dessous,
|
||||
sinon les calculs d'ECTS seront erronés !</span></div>"""
|
||||
f"""<div class="ue_warning"><span>Attention: plusieurs UE de cette
|
||||
formation ont le même code : <tt>{
|
||||
', '.join([
|
||||
'<a class="stdlink" href="' + url_for( "notes.ue_edit", scodoc_dept=g.scodoc_dept, ue_id=ue["ue_id"] )
|
||||
+ '">' + ue["acronyme"] + " (code " + ue["ue_code"] + ")</a>"
|
||||
for ue in ues_with_duplicated_code ])
|
||||
}</tt>.
|
||||
Il faut corriger cela, sinon les capitalisations et ECTS seront
|
||||
erronés !</span></div>"""
|
||||
)
|
||||
|
||||
# Description de la formation
|
||||
|
@ -643,16 +721,23 @@ du programme" (menu "Semestre") si vous avez un semestre en cours);
|
|||
descr_refcomp = ""
|
||||
msg_refcomp = "associer à un référentiel de compétences"
|
||||
else:
|
||||
descr_refcomp = f"{formation.referentiel_competence.type_titre} {formation.referentiel_competence.specialite_long}"
|
||||
descr_refcomp = f"""Référentiel de compétences:
|
||||
<a href="{url_for('notes.refcomp_show',
|
||||
scodoc_dept=g.scodoc_dept, refcomp_id=formation.referentiel_competence.id)}">
|
||||
{formation.referentiel_competence.type_titre} {formation.referentiel_competence.specialite_long}
|
||||
</a> """
|
||||
msg_refcomp = "changer"
|
||||
H.append(
|
||||
f"""
|
||||
<ul>
|
||||
<li>{descr_refcomp} <a class="stdlink" href="{url_for('notes.refcomp_assoc_formation',
|
||||
H.append(f"""<ul><li>{descr_refcomp}""")
|
||||
if current_user.has_permission(Permission.ScoChangeFormation):
|
||||
H.append(
|
||||
f"""<a class="stdlink" href="{url_for('notes.refcomp_assoc_formation',
|
||||
scodoc_dept=g.scodoc_dept, formation_id=formation_id)
|
||||
}">{msg_refcomp}</a>
|
||||
</li>
|
||||
<li><a class="stdlink" href="{
|
||||
}">{msg_refcomp}</a>"""
|
||||
)
|
||||
|
||||
H.append(
|
||||
f"""</li>
|
||||
<li> <a class="stdlink" href="{
|
||||
url_for('notes.edit_modules_ue_coefs', scodoc_dept=g.scodoc_dept, formation_id=formation_id, semestre_idx=semestre_idx)
|
||||
}">éditer les coefficients des ressources et SAÉs</a>
|
||||
</li>
|
||||
|
@ -679,6 +764,7 @@ du programme" (menu "Semestre") si vous avez un semestre en cours);
|
|||
)
|
||||
)
|
||||
else:
|
||||
H.append('<div class="formation_classic_infos">')
|
||||
H.append(
|
||||
_ue_table_ues(
|
||||
parcours,
|
||||
|
@ -708,7 +794,7 @@ du programme" (menu "Semestre") si vous avez un semestre en cours);
|
|||
</ul>
|
||||
"""
|
||||
)
|
||||
|
||||
H.append("</div>")
|
||||
H.append("</div>") # formation_ue_list
|
||||
|
||||
if ues_externes:
|
||||
|
@ -857,10 +943,10 @@ def _ue_table_ues(
|
|||
cur_ue_semestre_id = None
|
||||
iue = 0
|
||||
for ue in ues:
|
||||
if ue["ects"]:
|
||||
ue["ects_str"] = ", %g ECTS" % ue["ects"]
|
||||
else:
|
||||
if ue["ects"] is None:
|
||||
ue["ects_str"] = ""
|
||||
else:
|
||||
ue["ects_str"] = ", %g ECTS" % ue["ects"]
|
||||
if editable:
|
||||
klass = "span_apo_edit"
|
||||
else:
|
||||
|
@ -874,13 +960,13 @@ def _ue_table_ues(
|
|||
|
||||
if cur_ue_semestre_id != ue["semestre_id"]:
|
||||
cur_ue_semestre_id = ue["semestre_id"]
|
||||
if iue > 0:
|
||||
H.append("</ul>")
|
||||
if ue["semestre_id"] == sco_codes_parcours.UE_SEM_DEFAULT:
|
||||
lab = "Pas d'indication de semestre:"
|
||||
else:
|
||||
lab = "Semestre %s:" % ue["semestre_id"]
|
||||
H.append('<div class="ue_list_tit_sem">%s</div>' % lab)
|
||||
H.append(
|
||||
'<div class="ue_list_div"><div class="ue_list_tit_sem">%s</div>' % lab
|
||||
)
|
||||
H.append('<ul class="notes_ue_list">')
|
||||
H.append('<li class="notes_ue_list">')
|
||||
if iue != 0 and editable:
|
||||
|
@ -897,7 +983,6 @@ def _ue_table_ues(
|
|||
)
|
||||
else:
|
||||
H.append(arrow_none)
|
||||
iue += 1
|
||||
ue["acro_titre"] = str(ue["acronyme"])
|
||||
if ue["titre"] != ue["acronyme"]:
|
||||
ue["acro_titre"] += " " + str(ue["titre"])
|
||||
|
@ -945,6 +1030,16 @@ def _ue_table_ues(
|
|||
delete_disabled_icon,
|
||||
)
|
||||
)
|
||||
if (iue >= len(ues) - 1) or ue["semestre_id"] != ues[iue + 1]["semestre_id"]:
|
||||
H.append(
|
||||
f"""</ul><ul><li><a href="{url_for('notes.ue_create', scodoc_dept=g.scodoc_dept,
|
||||
formation_id=ue['formation_id'], semestre_idx=ue['semestre_id'])
|
||||
}">Ajouter une UE dans le semestre {ue['semestre_id'] or ''}</a></li></ul>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
iue += 1
|
||||
|
||||
return "\n".join(H)
|
||||
|
||||
|
||||
|
@ -983,6 +1078,7 @@ def _ue_table_matieres(
|
|||
H.append(
|
||||
_ue_table_modules(
|
||||
parcours,
|
||||
ue,
|
||||
mat,
|
||||
modules,
|
||||
editable,
|
||||
|
@ -1016,6 +1112,7 @@ def _ue_table_matieres(
|
|||
|
||||
def _ue_table_modules(
|
||||
parcours,
|
||||
ue,
|
||||
mat,
|
||||
modules,
|
||||
editable,
|
||||
|
@ -1106,8 +1203,12 @@ def _ue_table_modules(
|
|||
tag_cls,
|
||||
",".join(sco_tag_module.module_tag_list(mod["module_id"])),
|
||||
)
|
||||
if ue["semestre_idx"] is not None and mod["semestre_id"] != ue["semestre_idx"]:
|
||||
warning_semestre = ' <span class="red">incohérent ?</span>'
|
||||
else:
|
||||
warning_semestre = ""
|
||||
H.append(
|
||||
" %s %s" % (parcours.SESSION_NAME, mod["semestre_id"])
|
||||
" %s %s%s" % (parcours.SESSION_NAME, mod["semestre_id"], warning_semestre)
|
||||
+ " (%s)" % heurescoef
|
||||
+ tag_edit
|
||||
)
|
||||
|
@ -1206,7 +1307,6 @@ def do_ue_edit(args, bypass_lock=False, dont_invalidate_cache=False):
|
|||
f"""Acronyme d'UE "{args['acronyme']}" déjà utilisé !
|
||||
(chaque UE doit avoir un acronyme unique dans la formation)"""
|
||||
)
|
||||
|
||||
# On ne peut pas supprimer le code UE:
|
||||
if "ue_code" in args and not args["ue_code"]:
|
||||
del args["ue_code"]
|
||||
|
@ -1345,7 +1445,7 @@ def formation_table_recap(formation_id, format="html"):
|
|||
return tab.make_page(format=format)
|
||||
|
||||
|
||||
def ue_list_semestre_ids(ue):
|
||||
def ue_list_semestre_ids(ue: dict):
|
||||
"""Liste triée des numeros de semestres des modules dans cette UE
|
||||
Il est recommandable que tous les modules d'une UE aient le même indice de semestre.
|
||||
Mais cela n'a pas toujours été le cas dans les programmes pédagogiques officiels,
|
||||
|
@ -1353,3 +1453,45 @@ def ue_list_semestre_ids(ue):
|
|||
"""
|
||||
modules = sco_edit_module.module_list(args={"ue_id": ue["ue_id"]})
|
||||
return sorted(list(set([mod["semestre_id"] for mod in modules])))
|
||||
|
||||
|
||||
UE_PALETTE = [
|
||||
"#B80004", # rouge
|
||||
"#F97B3D", # Orange Crayola
|
||||
"#FEB40B", # Honey Yellow
|
||||
"#80CB3F", # Yellow Green
|
||||
"#05162E", # Oxford Blue
|
||||
"#548687", # Steel Teal
|
||||
"#444054", # Independence
|
||||
"#889696", # Spanish Gray
|
||||
"#0CA4A5", # Viridian Green
|
||||
]
|
||||
|
||||
|
||||
def colorie_anciennes_ues(ues: list[UniteEns]) -> None:
|
||||
"""Avant ScoDoc 9.2, les ue n'avaient pas de couleurs
|
||||
Met des défauts raisonnables
|
||||
"""
|
||||
nb_colors = len(UE_PALETTE)
|
||||
index = 0
|
||||
last_sem_idx = 0
|
||||
for ue in ues:
|
||||
if ue.semestre_idx != last_sem_idx:
|
||||
index = 0
|
||||
last_sem_idx = ue.semestre_idx
|
||||
if ue.color is None:
|
||||
ue.color = UE_PALETTE[index % nb_colors]
|
||||
index += 1
|
||||
db.session.add(ue)
|
||||
|
||||
|
||||
def ue_guess_color_default(formation_id: int, default_semestre_idx: int) -> str:
|
||||
"""Un code couleur pour une nouvelle UE dans ce semestre"""
|
||||
nb_colors = len(UE_PALETTE)
|
||||
# UE existantes dans ce semestre:
|
||||
nb_ues = UniteEns.query.filter(
|
||||
UniteEns.formation_id == formation_id,
|
||||
UniteEns.semestre_idx == default_semestre_idx,
|
||||
).count()
|
||||
index = nb_ues
|
||||
return UE_PALETTE[index % nb_colors]
|
||||
|
|
|
@ -1,324 +0,0 @@
|
|||
# -*- mode: python -*-
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gestion scolarite IUT
|
||||
#
|
||||
# Copyright (c) 1999 - 2022 Emmanuel Viennet. All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
#
|
||||
# Emmanuel Viennet emmanuel.viennet@viennet.net
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
"""Fonctions sur les entreprises
|
||||
"""
|
||||
# codes anciens déplacés de ZEntreprise
|
||||
import datetime
|
||||
from operator import itemgetter
|
||||
|
||||
import app.scodoc.sco_utils as scu
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app.scodoc.notesdb import ScoDocCursor, EditableTable, DateISOtoDMY, DateDMYtoISO
|
||||
|
||||
|
||||
def _format_nom(nom):
|
||||
"formatte nom (filtre en entree db) d'une entreprise"
|
||||
if not nom:
|
||||
return nom
|
||||
return nom[0].upper() + nom[1:]
|
||||
|
||||
|
||||
class EntreprisesEditor(EditableTable):
|
||||
def delete(self, cnx, oid):
|
||||
"delete correspondants and contacts, then self"
|
||||
# first, delete all correspondants and contacts
|
||||
cursor = cnx.cursor(cursor_factory=ScoDocCursor)
|
||||
cursor.execute(
|
||||
"delete from entreprise_contact where entreprise_id=%(entreprise_id)s",
|
||||
{"entreprise_id": oid},
|
||||
)
|
||||
cursor.execute(
|
||||
"delete from entreprise_correspondant where entreprise_id=%(entreprise_id)s",
|
||||
{"entreprise_id": oid},
|
||||
)
|
||||
cnx.commit()
|
||||
EditableTable.delete(self, cnx, oid)
|
||||
|
||||
def list(
|
||||
self,
|
||||
cnx,
|
||||
args={},
|
||||
operator="and",
|
||||
test="=",
|
||||
sortkey=None,
|
||||
sort_on_contact=False,
|
||||
limit="",
|
||||
offset="",
|
||||
):
|
||||
# list, then sort on date of last contact
|
||||
R = EditableTable.list(
|
||||
self,
|
||||
cnx,
|
||||
args=args,
|
||||
operator=operator,
|
||||
test=test,
|
||||
sortkey=sortkey,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
if sort_on_contact:
|
||||
for r in R:
|
||||
c = do_entreprise_contact_list(
|
||||
args={"entreprise_id": r["entreprise_id"]},
|
||||
disable_formatting=True,
|
||||
)
|
||||
if c:
|
||||
r["date"] = max([x["date"] or datetime.date.min for x in c])
|
||||
else:
|
||||
r["date"] = datetime.date.min
|
||||
# sort
|
||||
R.sort(key=itemgetter("date"))
|
||||
for r in R:
|
||||
r["date"] = DateISOtoDMY(r["date"])
|
||||
return R
|
||||
|
||||
def list_by_etud(
|
||||
self, cnx, args={}, sort_on_contact=False, disable_formatting=False
|
||||
):
|
||||
"cherche rentreprise ayant eu contact avec etudiant"
|
||||
cursor = cnx.cursor(cursor_factory=ScoDocCursor)
|
||||
cursor.execute(
|
||||
"select E.*, I.nom as etud_nom, I.prenom as etud_prenom, C.date from entreprises E, entreprise_contact C, identite I where C.entreprise_id = E.entreprise_id and C.etudid = I.etudid and I.nom ~* %(etud_nom)s ORDER BY E.nom",
|
||||
args,
|
||||
)
|
||||
_, res = [x[0] for x in cursor.description], cursor.dictfetchall()
|
||||
R = []
|
||||
for r in res:
|
||||
r["etud_prenom"] = r["etud_prenom"] or ""
|
||||
d = {}
|
||||
for key in r:
|
||||
v = r[key]
|
||||
# format value
|
||||
if not disable_formatting and key in self.output_formators:
|
||||
v = self.output_formators[key](v)
|
||||
d[key] = v
|
||||
R.append(d)
|
||||
# sort
|
||||
if sort_on_contact:
|
||||
R.sort(key=lambda x: (x["date"] or datetime.date.min))
|
||||
|
||||
for r in R:
|
||||
r["date"] = DateISOtoDMY(r["date"] or datetime.date.min)
|
||||
return R
|
||||
|
||||
|
||||
_entreprisesEditor = EntreprisesEditor(
|
||||
"entreprises",
|
||||
"entreprise_id",
|
||||
(
|
||||
"entreprise_id",
|
||||
"nom",
|
||||
"adresse",
|
||||
"ville",
|
||||
"codepostal",
|
||||
"pays",
|
||||
"contact_origine",
|
||||
"secteur",
|
||||
"privee",
|
||||
"localisation",
|
||||
"qualite_relation",
|
||||
"plus10salaries",
|
||||
"note",
|
||||
"date_creation",
|
||||
),
|
||||
filter_dept=True,
|
||||
sortkey="nom",
|
||||
input_formators={
|
||||
"nom": _format_nom,
|
||||
"plus10salaries": bool,
|
||||
},
|
||||
)
|
||||
|
||||
# ----------- Correspondants
|
||||
_entreprise_correspEditor = EditableTable(
|
||||
"entreprise_correspondant",
|
||||
"entreprise_corresp_id",
|
||||
(
|
||||
"entreprise_corresp_id",
|
||||
"entreprise_id",
|
||||
"civilite",
|
||||
"nom",
|
||||
"prenom",
|
||||
"fonction",
|
||||
"phone1",
|
||||
"phone2",
|
||||
"mobile",
|
||||
"fax",
|
||||
"mail1",
|
||||
"mail2",
|
||||
"note",
|
||||
),
|
||||
sortkey="nom",
|
||||
)
|
||||
|
||||
|
||||
# ----------- Contacts
|
||||
_entreprise_contactEditor = EditableTable(
|
||||
"entreprise_contact",
|
||||
"entreprise_contact_id",
|
||||
(
|
||||
"entreprise_contact_id",
|
||||
"date",
|
||||
"type_contact",
|
||||
"entreprise_id",
|
||||
"entreprise_corresp_id",
|
||||
"etudid",
|
||||
"description",
|
||||
"enseignant",
|
||||
),
|
||||
sortkey="date",
|
||||
output_formators={"date": DateISOtoDMY},
|
||||
input_formators={"date": DateDMYtoISO},
|
||||
)
|
||||
|
||||
|
||||
def do_entreprise_create(args):
|
||||
"entreprise_create"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
r = _entreprisesEditor.create(cnx, args)
|
||||
return r
|
||||
|
||||
|
||||
def do_entreprise_delete(oid):
|
||||
"entreprise_delete"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprisesEditor.delete(cnx, oid)
|
||||
|
||||
|
||||
def do_entreprise_list(**kw):
|
||||
"entreprise_list"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
return _entreprisesEditor.list(cnx, **kw)
|
||||
|
||||
|
||||
def do_entreprise_list_by_etud(**kw):
|
||||
"entreprise_list_by_etud"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
return _entreprisesEditor.list_by_etud(cnx, **kw)
|
||||
|
||||
|
||||
def do_entreprise_edit(*args, **kw):
|
||||
"entreprise_edit"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprisesEditor.edit(cnx, *args, **kw)
|
||||
|
||||
|
||||
def do_entreprise_correspondant_create(args):
|
||||
"entreprise_correspondant_create"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
r = _entreprise_correspEditor.create(cnx, args)
|
||||
return r
|
||||
|
||||
|
||||
def do_entreprise_correspondant_delete(oid):
|
||||
"entreprise_correspondant_delete"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprise_correspEditor.delete(cnx, oid)
|
||||
|
||||
|
||||
def do_entreprise_correspondant_list(**kw):
|
||||
"entreprise_correspondant_list"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
return _entreprise_correspEditor.list(cnx, **kw)
|
||||
|
||||
|
||||
def do_entreprise_correspondant_edit(*args, **kw):
|
||||
"entreprise_correspondant_edit"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprise_correspEditor.edit(cnx, *args, **kw)
|
||||
|
||||
|
||||
def do_entreprise_correspondant_listnames(args={}):
|
||||
"-> liste des noms des correspondants (pour affichage menu)"
|
||||
C = do_entreprise_correspondant_list(args=args)
|
||||
return [(x["prenom"] + " " + x["nom"], str(x["entreprise_corresp_id"])) for x in C]
|
||||
|
||||
|
||||
def do_entreprise_contact_delete(oid):
|
||||
"entreprise_contact_delete"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprise_contactEditor.delete(cnx, oid)
|
||||
|
||||
|
||||
def do_entreprise_contact_list(**kw):
|
||||
"entreprise_contact_list"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
return _entreprise_contactEditor.list(cnx, **kw)
|
||||
|
||||
|
||||
def do_entreprise_contact_edit(*args, **kw):
|
||||
"entreprise_contact_edit"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
_entreprise_contactEditor.edit(cnx, *args, **kw)
|
||||
|
||||
|
||||
def do_entreprise_contact_create(args):
|
||||
"entreprise_contact_create"
|
||||
cnx = ndb.GetDBConnexion()
|
||||
r = _entreprise_contactEditor.create(cnx, args)
|
||||
return r
|
||||
|
||||
|
||||
def do_entreprise_check_etudiant(etudiant):
|
||||
"""Si etudiant est vide, ou un ETUDID valide, ou un nom unique,
|
||||
retourne (1, ETUDID).
|
||||
Sinon, retourne (0, 'message explicatif')
|
||||
"""
|
||||
etudiant = etudiant.strip().translate(
|
||||
str.maketrans("", "", "'()")
|
||||
) # suppress parens and quote from name
|
||||
if not etudiant:
|
||||
return 1, None
|
||||
cnx = ndb.GetDBConnexion()
|
||||
cursor = cnx.cursor(cursor_factory=ScoDocCursor)
|
||||
cursor.execute(
|
||||
"select etudid, nom, prenom from identite where upper(nom) ~ upper(%(etudiant)s) or etudid=%(etudiant)s",
|
||||
{"etudiant": etudiant},
|
||||
)
|
||||
r = cursor.fetchall()
|
||||
if len(r) < 1:
|
||||
return 0, 'Aucun etudiant ne correspond à "%s"' % etudiant
|
||||
elif len(r) > 10:
|
||||
return (
|
||||
0,
|
||||
"<b>%d etudiants</b> correspondent à ce nom (utilisez le code)" % len(r),
|
||||
)
|
||||
elif len(r) > 1:
|
||||
e = ['<ul class="entreprise_etud_list">']
|
||||
for x in r:
|
||||
e.append(
|
||||
"<li>%s %s (code %s)</li>" % ((x[1]).upper(), x[2] or "", x[0].strip())
|
||||
)
|
||||
e.append("</ul>")
|
||||
return (
|
||||
0,
|
||||
"Les étudiants suivants correspondent: préciser le nom complet ou le code\n"
|
||||
+ "\n".join(e),
|
||||
)
|
||||
else: # une seule reponse !
|
||||
return 1, r[0][0].strip()
|
|
@ -384,8 +384,8 @@ print apo_csv_list_stored_archives()
|
|||
|
||||
groups_infos = sco_groups_view.DisplayedGroupsInfos( [sco_groups.get_default_group(formsemestre_id)], formsemestre_id=formsemestre_id)
|
||||
|
||||
nt = sco_cache.NotesTableCache.get( formsemestre_id)
|
||||
|
||||
formsemestre = FormSemestre.query.get_or_404(formsemestre_id)
|
||||
nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
|
||||
#
|
||||
s = SemSet('NSS29902')
|
||||
apo_data = sco_apogee_csv.ApoData(open('/opt/scodoc/var/scodoc/archives/apo_csv/RT/2015-2/2016-07-10-11-26-15/V1RT.csv').read(), periode=1)
|
||||
|
|
|
@ -53,7 +53,7 @@ from app.scodoc.sco_exceptions import ScoValueError
|
|||
|
||||
|
||||
def apo_semset_maq_status(
|
||||
semset_id="",
|
||||
semset_id: int,
|
||||
allow_missing_apo=False,
|
||||
allow_missing_decisions=False,
|
||||
allow_missing_csv=False,
|
||||
|
@ -65,7 +65,7 @@ def apo_semset_maq_status(
|
|||
):
|
||||
"""Page statut / tableau de bord"""
|
||||
if not semset_id:
|
||||
raise ValueError("invalid null semset_id")
|
||||
raise ScoValueError("invalid null semset_id")
|
||||
semset = sco_semset.SemSet(semset_id=semset_id)
|
||||
semset.fill_formsemestres()
|
||||
# autorise export meme si etudiants Apo manquants:
|
||||
|
|
|
@ -33,19 +33,18 @@ import os
|
|||
import time
|
||||
from operator import itemgetter
|
||||
|
||||
from flask import url_for, g, request
|
||||
from flask_mail import Message
|
||||
from flask import url_for, g
|
||||
|
||||
from app import email
|
||||
from app import log
|
||||
|
||||
from app.models import Admission
|
||||
from app.models.etudiants import make_etud_args
|
||||
import app.scodoc.sco_utils as scu
|
||||
import app.scodoc.notesdb as ndb
|
||||
from app.scodoc.sco_exceptions import ScoGenError, ScoValueError
|
||||
from app.scodoc import safehtml
|
||||
from app.scodoc import sco_preferences
|
||||
from app.scodoc.scolog import logdb
|
||||
from app.scodoc.TrivialFormulator import TrivialFormulator
|
||||
|
||||
|
||||
def format_etud_ident(etud):
|
||||
|
@ -87,6 +86,8 @@ def force_uppercase(s):
|
|||
def format_nomprenom(etud, reverse=False):
|
||||
"""Formatte civilité/nom/prenom pour affichages: "M. Pierre Dupont"
|
||||
Si reverse, "Dupont Pierre", sans civilité.
|
||||
|
||||
DEPRECATED: utiliser Identite.nomprenom
|
||||
"""
|
||||
nom = etud.get("nom_disp", "") or etud.get("nom_usuel", "") or etud["nom"]
|
||||
prenom = format_prenom(etud["prenom"])
|
||||
|
@ -99,7 +100,9 @@ def format_nomprenom(etud, reverse=False):
|
|||
|
||||
|
||||
def format_prenom(s):
|
||||
"Formatte prenom etudiant pour affichage"
|
||||
"""Formatte prenom etudiant pour affichage
|
||||
DEPRECATED: utiliser Identite.prenom_str
|
||||
"""
|
||||
if not s:
|
||||
return ""
|
||||
frags = s.split()
|
||||
|
@ -446,7 +449,6 @@ _adresseEditor = ndb.EditableTable(
|
|||
"telephonemobile",
|
||||
"fax",
|
||||
"typeadresse",
|
||||
"entreprise_id",
|
||||
"description",
|
||||
),
|
||||
convert_null_outputs_to_empty=True,
|
||||
|
@ -590,35 +592,6 @@ etudident_edit = _etudidentEditor.edit
|
|||
etudident_create = _etudidentEditor.create
|
||||
|
||||
|
||||
def make_etud_args(etudid=None, code_nip=None, use_request=True, raise_exc=True):
|
||||
"""forme args dict pour requete recherche etudiant
|
||||
On peut specifier etudid
|
||||
ou bien (si use_request) cherche dans la requete http: etudid, code_nip, code_ine
|
||||
(dans cet ordre).
|
||||
"""
|
||||
args = None
|
||||
if etudid:
|
||||
args = {"etudid": etudid}
|
||||
elif code_nip:
|
||||
args = {"code_nip": code_nip}
|
||||
elif use_request: # use form from current request (Flask global)
|
||||
if request.method == "POST":
|
||||
vals = request.form
|
||||
elif request.method == "GET":
|
||||
vals = request.args
|
||||
else:
|
||||
vals = {}
|
||||
if "etudid" in vals:
|
||||
args = {"etudid": int(vals["etudid"])}
|
||||
elif "code_nip" in vals:
|
||||
args = {"code_nip": str(vals["code_nip"])}
|
||||
elif "code_ine" in vals:
|
||||
args = {"code_ine": str(vals["code_ine"])}
|
||||
if not args and raise_exc:
|
||||
raise ValueError("getEtudInfo: no parameter !")
|
||||
return args
|
||||
|
||||
|
||||
def log_unknown_etud():
|
||||
"""Log request: cas ou getEtudInfo n'a pas ramene de resultat"""
|
||||
etud_args = make_etud_args(raise_exc=False)
|
||||
|
@ -884,19 +857,24 @@ def list_scolog(etudid):
|
|||
return cursor.dictfetchall()
|
||||
|
||||
|
||||
def fill_etuds_info(etuds):
|
||||
def fill_etuds_info(etuds: list[dict], add_admission=True):
|
||||
"""etuds est une liste d'etudiants (mappings)
|
||||
Pour chaque etudiant, ajoute ou formatte les champs
|
||||
-> informations pour fiche etudiant ou listes diverses
|
||||
"""
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_formsemestre_inscriptions
|
||||
|
||||
Si add_admission: ajoute au dict le schamps "admission" s'il n'y sont pas déjà.
|
||||
"""
|
||||
cnx = ndb.GetDBConnexion()
|
||||
# open('/tmp/t','w').write( str(etuds) )
|
||||
for etud in etuds:
|
||||
etudid = etud["etudid"]
|
||||
etud["dept"] = g.scodoc_dept
|
||||
# Admission
|
||||
if add_admission and "nomlycee" not in etud:
|
||||
admission = (
|
||||
Admission.query.filter_by(etudid=etudid).first().to_dict(no_nulls=True)
|
||||
)
|
||||
etud.update(admission)
|
||||
#
|
||||
adrs = adresse_list(cnx, {"etudid": etudid})
|
||||
if not adrs:
|
||||
# certains "vieux" etudiants n'ont pas d'adresse
|
||||
|
@ -909,79 +887,37 @@ def fill_etuds_info(etuds):
|
|||
etud.update(adr)
|
||||
format_etud_ident(etud)
|
||||
|
||||
# Semestres dans lesquel il est inscrit
|
||||
ins = sco_formsemestre_inscriptions.do_formsemestre_inscription_list(
|
||||
{"etudid": etudid}
|
||||
)
|
||||
etud["ins"] = ins
|
||||
sems = []
|
||||
cursem = None # semestre "courant" ou il est inscrit
|
||||
for i in ins:
|
||||
sem = sco_formsemestre.get_formsemestre(i["formsemestre_id"])
|
||||
if sco_formsemestre.sem_est_courant(sem):
|
||||
cursem = sem
|
||||
curi = i
|
||||
sem["ins"] = i
|
||||
sems.append(sem)
|
||||
# trie les semestres par date de debut, le plus recent d'abord
|
||||
# (important, ne pas changer (suivi cohortes))
|
||||
sems.sort(key=itemgetter("dateord"), reverse=True)
|
||||
etud["sems"] = sems
|
||||
etud["cursem"] = cursem
|
||||
if cursem:
|
||||
etud["inscription"] = cursem["titremois"]
|
||||
etud["inscriptionstr"] = "Inscrit en " + cursem["titremois"]
|
||||
etud["inscription_formsemestre_id"] = cursem["formsemestre_id"]
|
||||
etud["etatincursem"] = curi["etat"]
|
||||
etud["situation"] = descr_situation_etud(etudid, etud["ne"])
|
||||
# XXX est-ce utile ? sco_groups.etud_add_group_infos( etud, cursem)
|
||||
else:
|
||||
if etud["sems"]:
|
||||
if etud["sems"][0]["dateord"] > time.strftime(
|
||||
"%Y-%m-%d", time.localtime()
|
||||
):
|
||||
etud["inscription"] = "futur"
|
||||
etud["situation"] = "futur élève"
|
||||
else:
|
||||
etud["inscription"] = "ancien"
|
||||
etud["situation"] = "ancien élève"
|
||||
else:
|
||||
etud["inscription"] = "non inscrit"
|
||||
etud["situation"] = etud["inscription"]
|
||||
etud["inscriptionstr"] = etud["inscription"]
|
||||
etud["inscription_formsemestre_id"] = None
|
||||
# XXXetud['partitions'] = {} # ne va pas chercher les groupes des anciens semestres
|
||||
etud["etatincursem"] = "?"
|
||||
etud.update(etud_inscriptions_infos(etudid, etud["ne"]))
|
||||
|
||||
# nettoyage champs souvents vides
|
||||
if etud["nomlycee"]:
|
||||
# nettoyage champs souvent vides
|
||||
if etud.get("nomlycee"):
|
||||
etud["ilycee"] = "Lycée " + format_lycee(etud["nomlycee"])
|
||||
if etud["villelycee"]:
|
||||
etud["ilycee"] += " (%s)" % etud["villelycee"]
|
||||
etud["ilycee"] += " (%s)" % etud.get("villelycee", "")
|
||||
etud["ilycee"] += "<br/>"
|
||||
else:
|
||||
if etud["codelycee"]:
|
||||
if etud.get("codelycee"):
|
||||
etud["ilycee"] = format_lycee_from_code(etud["codelycee"])
|
||||
else:
|
||||
etud["ilycee"] = ""
|
||||
rap = ""
|
||||
if etud["rapporteur"] or etud["commentaire"]:
|
||||
if etud.get("rapporteur") or etud.get("commentaire"):
|
||||
rap = "Note du rapporteur"
|
||||
if etud["rapporteur"]:
|
||||
if etud.get("rapporteur"):
|
||||
rap += " (%s)" % etud["rapporteur"]
|
||||
rap += ": "
|
||||
if etud["commentaire"]:
|
||||
if etud.get("commentaire"):
|
||||
rap += "<em>%s</em>" % etud["commentaire"]
|
||||
etud["rap"] = rap
|
||||
|
||||
# if etud['boursier_prec']:
|
||||
# pass
|
||||
|
||||
if etud["telephone"]:
|
||||
if etud.get("telephone"):
|
||||
etud["telephonestr"] = "<b>Tél.:</b> " + format_telephone(etud["telephone"])
|
||||
else:
|
||||
etud["telephonestr"] = ""
|
||||
if etud["telephonemobile"]:
|
||||
if etud.get("telephonemobile"):
|
||||
etud["telephonemobilestr"] = "<b>Mobile:</b> " + format_telephone(
|
||||
etud["telephonemobile"]
|
||||
)
|
||||
|
@ -989,8 +925,59 @@ def fill_etuds_info(etuds):
|
|||
etud["telephonemobilestr"] = ""
|
||||
|
||||
|
||||
def descr_situation_etud(etudid, ne=""):
|
||||
"""chaine decrivant la situation actuelle de l'etudiant"""
|
||||
def etud_inscriptions_infos(etudid: int, ne="") -> dict:
|
||||
"""Dict avec les informations sur les semestres passés et courant"""
|
||||
from app.scodoc import sco_formsemestre
|
||||
from app.scodoc import sco_formsemestre_inscriptions
|
||||
|
||||
etud = {}
|
||||
# Semestres dans lesquel il est inscrit
|
||||
ins = sco_formsemestre_inscriptions.do_formsemestre_inscription_list(
|
||||
{"etudid": etudid}
|
||||
)
|
||||
etud["ins"] = ins
|
||||
sems = []
|
||||
cursem = None # semestre "courant" ou il est inscrit
|
||||
for i in ins:
|
||||
sem = sco_formsemestre.get_formsemestre(i["formsemestre_id"])
|
||||
if sco_formsemestre.sem_est_courant(sem):
|
||||
cursem = sem
|
||||
curi = i
|
||||
sem["ins"] = i
|
||||
sems.append(sem)
|
||||
# trie les semestres par date de debut, le plus recent d'abord
|
||||
# (important, ne pas changer (suivi cohortes))
|
||||
sems.sort(key=itemgetter("dateord"), reverse=True)
|
||||
etud["sems"] = sems
|
||||
etud["cursem"] = cursem
|
||||
if cursem:
|
||||
etud["inscription"] = cursem["titremois"]
|
||||
etud["inscriptionstr"] = "Inscrit en " + cursem["titremois"]
|
||||
etud["inscription_formsemestre_id"] = cursem["formsemestre_id"]
|
||||
etud["etatincursem"] = curi["etat"]
|
||||
etud["situation"] = descr_situation_etud(etudid, ne)
|
||||
else:
|
||||
if etud["sems"]:
|
||||
if etud["sems"][0]["dateord"] > time.strftime("%Y-%m-%d", time.localtime()):
|
||||
etud["inscription"] = "futur"
|
||||
etud["situation"] = "futur élève"
|
||||
else:
|
||||
etud["inscription"] = "ancien"
|
||||
etud["situation"] = "ancien élève"
|
||||
else:
|
||||
etud["inscription"] = "non inscrit"
|
||||
etud["situation"] = etud["inscription"]
|
||||
etud["inscriptionstr"] = etud["inscription"]
|
||||
etud["inscription_formsemestre_id"] = None
|
||||
etud["etatincursem"] = "?"
|
||||
return etud
|
||||
|
||||
|
||||
def descr_situation_etud(etudid: int, ne="") -> str:
|
||||
"""Chaîne décrivant la situation actuelle de l'étudiant
|
||||
XXX Obsolete, utiliser Identite.descr_situation_etud() dans
|
||||
les nouveaux codes
|
||||
"""
|
||||
from app.scodoc import sco_formsemestre
|
||||
|
||||
cnx = ndb.GetDBConnexion()
|
||||
|
@ -1007,7 +994,7 @@ def descr_situation_etud(etudid, ne=""):
|
|||
)
|
||||
r = cursor.dictfetchone()
|
||||
if not r:
|
||||
situation = "non inscrit"
|
||||
situation = "non inscrit" + ne
|
||||
else:
|
||||
sem = sco_formsemestre.get_formsemestre(r["formsemestre_id"])
|
||||
if r["etat"] == "I":
|
||||
|
|
|
@ -222,7 +222,6 @@ def formsemestre_check_absences_html(formsemestre_id):
|
|||
H = [
|
||||
html_sco_header.html_sem_header(
|
||||
"Vérification absences aux évaluations de ce semestre",
|
||||
sem,
|
||||
),
|
||||
"""<p class="help">Vérification de la cohérence entre les notes saisies et les absences signalées.
|
||||
Sont listés tous les modules avec des évaluations.<br/>Aucune action n'est effectuée:
|
||||
|
@ -238,7 +237,11 @@ def formsemestre_check_absences_html(formsemestre_id):
|
|||
if evals:
|
||||
H.append(
|
||||
'<div class="module_check_absences"><h2><a href="moduleimpl_status?moduleimpl_id=%s">%s: %s</a></h2>'
|
||||
% (M["moduleimpl_id"], M["module"]["code"], M["module"]["abbrev"])
|
||||
% (
|
||||
M["moduleimpl_id"],
|
||||
M["module"]["code"] or "",
|
||||
M["module"]["abbrev"] or "",
|
||||
)
|
||||
)
|
||||
for E in evals:
|
||||
H.append(
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue