Modifie l'implémentation des préférences pour ScoDoc 9

This commit is contained in:
Emmanuel Viennet 2021-09-07 22:03:33 +02:00
parent af77a2a389
commit 998f28d4a4
3 changed files with 243 additions and 214 deletions

View File

@ -147,6 +147,52 @@ def get_preference(name, formsemestre_id=None):
return get_base_preferences().get(formsemestre_id, name)
def _convert_pref_type(p, pref_spec):
"""p est une ligne de la bd
{'id': , 'dept_id': , 'name': '', 'value': '', 'formsemestre_id': }
converti la valeur chane en le type désiré spécifié par pref_spec
"""
if "type" in pref_spec:
typ = pref_spec["type"]
if typ == "float":
# special case for float values (where NULL means 0)
if p["value"]:
p["value"] = float(p["value"])
else:
p["value"] = 0.0
else:
func = eval(typ)
p["value"] = func(p["value"])
if pref_spec.get("input_type", None) == "boolcheckbox":
# boolcheckbox: la valeur stockée en base est une chaine "0" ou "1"
# que l'on ressort en True|False
if p["value"]:
try:
p["value"] = bool(int(p["value"]))
except ValueError:
log(
f"""Warning: invalid value for boolean pref in db: '{p["value"]}'"""
)
p["value"] = False
else:
p["value"] = False # NULL (backward compat)
def _get_pref_default_value_from_config(name, pref_spec):
"""get default value store in application level config.
If not found, use defalut value hardcoded in pref_spec.
"""
# XXX va changer avec la nouvelle base
# search in scu.CONFIG
if hasattr(scu.CONFIG, name):
value = getattr(scu.CONFIG, name)
log("sco_preferences: found default value in config for %s=%s" % (name, value))
else:
# uses hardcoded default
value = pref_spec["initvalue"]
return value
PREF_CATEGORIES = (
# sur page "Paramètres"
("general", {}),
@ -472,9 +518,15 @@ class BasePreferences(object):
--- Ceci est un message de notification automatique issu de ScoDoc ---
L'étudiant %(nomprenom)s
L'étudiant %(nomprenom)s
L'étudiant %(nomprenom)s
inscrit en %(inscription)s)
inscrit en %(inscription)s)
inscrit en %(inscription)s)
a cumulé %(nbabsjust)s absences justifiées
a cumulé %(nbabsjust)s absences justifiées
a cumulé %(nbabsjust)s absences justifiées
et %(nbabsnonjust)s absences NON justifiées.
Le compte a pu changer depuis cet envoi, voir la fiche sur %(url_ficheetud)s.
@ -829,9 +881,13 @@ class BasePreferences(object):
Vu l'arrêté du 3 août 2005 relatif au diplôme universitaire de technologie et notamment son article 4 et 6;
</para>
<para><bullet>-</bullet>
<para><bullet>-</bullet>
<para><bullet>-</bullet>
vu l'arrêté n° %(Decnum)s du Président de l'%(UnivName)s;
</para>
<para><bullet>-</bullet>
<para><bullet>-</bullet>
<para><bullet>-</bullet>
vu la délibération de la commission %(Type)s en date du %(Date)s présidée par le Chef du département;
""",
"title": """Paragraphe d'introduction sur le PV""",
@ -981,6 +1037,8 @@ class BasePreferences(object):
<para spaceBefore="10mm" fontSize="14" leftindent="0">
Le jury de %(type_jury_abbrv)s du département %(DeptName)s
s'est réuni le %(date_jury)s.
s'est réuni le %(date_jury)s.
s'est réuni le %(date_jury)s.
</para>
<para fontSize="14" leftindent="0">Les décisions vous concernant sont :
</para>
@ -1799,8 +1857,7 @@ class BasePreferences(object):
def load(self):
"""Load all preferences from db"""
log(f"loading preferences for dept_id={self.dept_id}")
try:
scu.GSL.acquire()
cnx = ndb.GetDBConnexion()
preflist = self._editor.list(cnx, {"dept_id": self.dept_id})
self.prefs = {None: {}} # { formsemestre_id (or None) : { name : value } }
@ -1811,38 +1868,11 @@ class BasePreferences(object):
# Ignore les noms de préférences non utilisés dans le code:
if p["name"] not in self.prefs_dict:
continue
# Convert types:
if (
p["name"] in self.prefs_dict
and "type" in self.prefs_dict[p["name"]]
):
typ = self.prefs_dict[p["name"]]["type"]
if typ == "float":
# special case for float values (where NULL means 0)
if p["value"]:
p["value"] = float(p["value"])
else:
p["value"] = 0.0
else:
func = eval(typ)
p["value"] = func(p["value"])
if (
p["name"] in self.prefs_dict
and self.prefs_dict[p["name"]].get("input_type", None)
== "boolcheckbox"
):
# boolcheckbox: la valeur stockée en base est une chaine "0" ou "1"
# que l'on ressort en True|False
if p["value"]:
try:
p["value"] = bool(int(p["value"]))
except ValueError:
log(
f"""Warning: invalid value for boolean pref in db: '{p["value"]}'"""
)
p["value"] = False
else:
p["value"] = False # NULL (backward compat)
if p["name"] in self.prefs_dict:
_convert_pref_type(p, self.prefs_dict[p["name"]])
self.prefs[p["formsemestre_id"]][p["name"]] = p["value"]
# add defaults for missing prefs
@ -1850,17 +1880,7 @@ class BasePreferences(object):
name = pref[0]
# search preferences in configuration file
if name and name[0] != "_" and name not in self.prefs[None]:
# search in scu.CONFIG
if hasattr(scu.CONFIG, name):
value = getattr(scu.CONFIG, name)
log(
"sco_preferences: found default value in config for %s=%s"
% (name, value)
)
else:
# uses hardcoded default
value = pref[1]["initvalue"]
value = _get_pref_default_value_from_config(name, pref[1])
self.default[name] = value
self.prefs[None][name] = value
log("creating missing preference for %s=%s" % (name, value))
@ -1868,19 +1888,26 @@ class BasePreferences(object):
self._editor.create(
cnx, {"dept_id": self.dept_id, "name": name, "value": value}
)
finally:
scu.GSL.release()
def get(self, formsemestre_id, name):
"""Returns preference value.
If no value defined for this semestre, returns global value.
If global_lookup, when no value defined for this semestre, returns global value.
"""
if formsemestre_id in self.prefs and name in self.prefs[formsemestre_id]:
return self.prefs[formsemestre_id][name]
elif name in self.prefs[None]:
return self.prefs[None][name]
else:
params = {
"dept_id": self.dept_id,
"name": name,
"formsemestre_id": formsemestre_id,
}
cnx = ndb.GetDBConnexion()
plist = self._editor.list(cnx, params)
if not plist:
del params["formsemestre_id"]
plist = self._editor.list(cnx, params)
if not plist:
return self.default[name]
p = plist[0]
_convert_pref_type(p, self.prefs_dict[name])
return p["value"]
def __contains__(self, item):
return item in self.prefs[None]
@ -1890,18 +1917,17 @@ class BasePreferences(object):
def is_global(self, formsemestre_id, name):
"True if name if not defined for semestre"
if (
not (formsemestre_id in self.prefs)
or not name in self.prefs[formsemestre_id]
):
return True
else:
return False
params = {
"dept_id": self.dept_id,
"name": name,
"formsemestre_id": formsemestre_id,
}
cnx = ndb.GetDBConnexion()
plist = self._editor.list(cnx, params)
return len(plist) == 0
def save(self, formsemestre_id=None, name=None):
"""Write one or all (if name is None) values to db"""
try:
scu.GSL.acquire()
modif = False
cnx = ndb.GetDBConnexion()
if name is None:
@ -1909,7 +1935,7 @@ class BasePreferences(object):
else:
names = [name]
for name in names:
value = self.get(formsemestre_id, name)
value = self.prefs[formsemestre_id][name]
if self.prefs_dict[name].get("input_type", None) == "boolcheckbox":
# repasse les booleens en chaines "0":"1"
value = "1" if value else "0"
@ -1938,8 +1964,12 @@ class BasePreferences(object):
log("create pref sem=%s %s=%s" % (formsemestre_id, name, value))
else:
# edit existing value
if pdb[0]["value"] != str(value) and (
pdb[0]["value"] or str(value)
existing_value = pdb[0]["value"] # old stored value
if (
(existing_value != value)
and (existing_value != str(value))
and (existing_value or str(value))
):
self._editor.edit(
cnx,
@ -1956,8 +1986,6 @@ class BasePreferences(object):
# les preferences peuvent affecter les PDF cachés et les notes calculées:
if modif:
sco_cache.invalidate_formsemestre()
finally:
scu.GSL.release()
def set(self, formsemestre_id, name, value):
if not name or name[0] == "_" or name not in self.prefs_name:
@ -1972,8 +2000,7 @@ class BasePreferences(object):
def delete(self, formsemestre_id, name):
if not formsemestre_id:
raise ScoException()
try:
scu.GSL.acquire()
if formsemestre_id in self.prefs and name in self.prefs[formsemestre_id]:
del self.prefs[formsemestre_id][name]
cnx = ndb.GetDBConnexion()
@ -1985,13 +2012,12 @@ class BasePreferences(object):
assert pdb[0]["dept_id"] == self.dept_id
self._editor.delete(cnx, pdb[0]["pref_id"])
sco_cache.invalidate_formsemestre() # > modif preferences
finally:
scu.GSL.release()
def edit(self, REQUEST):
"""HTML dialog: edit global preferences"""
from app.scodoc import html_sco_header
self.load()
H = [
html_sco_header.sco_header(page_title="Préférences"),
"<h2>Préférences globales pour %s</h2>" % scu.ScoURL(),

View File

@ -40,11 +40,11 @@ from app.scodoc.sco_exceptions import ScoValueError
random.seed(12345) # tests reproductibles
DEMO_DIR = Config.SCODOC_DIR + "/tools/demo/"
NOMS = [x.strip() for x in open(DEMO_DIR + "/noms.txt").readlines()]
PRENOMS_H = [x.strip() for x in open(DEMO_DIR + "/prenoms-h.txt").readlines()]
PRENOMS_F = [x.strip() for x in open(DEMO_DIR + "/prenoms-f.txt").readlines()]
PRENOMS_X = [x.strip() for x in open(DEMO_DIR + "/prenoms-x.txt").readlines()]
NOMS_DIR = Config.SCODOC_DIR + "/tools/fakeportal/nomsprenoms"
NOMS = [x.strip() for x in open(NOMS_DIR + "/noms.txt").readlines()]
PRENOMS_H = [x.strip() for x in open(NOMS_DIR + "/prenoms-h.txt").readlines()]
PRENOMS_F = [x.strip() for x in open(NOMS_DIR + "/prenoms-f.txt").readlines()]
PRENOMS_X = [x.strip() for x in open(NOMS_DIR + "/prenoms-x.txt").readlines()]
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):

View File

@ -73,6 +73,8 @@ def test_preferences(test_client):
assert len(prefs2) == len(prefs)
prefs2.set(None, "abs_notification_mail_tmpl", "toto")
assert prefs2.get(None, "abs_notification_mail_tmpl") == "toto"
# Vérifie que les prefs sont bien sur un seul département:
app.set_sco_dept(current_dept.acronym)
assert prefs.get(None, "abs_notification_mail_tmpl") != "toto"
orm_val = (
ScoPreference.query.filter_by(dept_id=d.id, name="abs_notification_mail_tmpl")
@ -82,6 +84,7 @@ def test_preferences(test_client):
assert orm_val == "toto"
# --- Preferences d'un semestre
# rejoue ce test pour avoir un semestre créé
app.set_sco_dept("D2")
test_sco_basic.run_sco_basic()
sem = sco_formsemestre.do_formsemestre_list()[0]
formsemestre_id = sem["formsemestre_id"]