Skip to content

Commit

Permalink
Merge pull request #57 from hacf-fr/bug/moyenne_generale
Browse files Browse the repository at this point in the history
Bug/moyenne generale
  • Loading branch information
Giga77 authored Jan 21, 2025
2 parents 2f307c3 + b1e8f3c commit 30ed28f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 35 deletions.
33 changes: 22 additions & 11 deletions custom_components/ecole_directe/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
logger=_LOGGER,
name=entry.title,
update_interval=timedelta(
minutes=entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)
minutes=entry.options.get(
"refresh_interval", DEFAULT_REFRESH_INTERVAL)
),
)
self.config_entry = entry
Expand Down Expand Up @@ -151,7 +152,8 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
self.config_entry.options.get("decode_html", False),
)

self.data[f"{eleve.get_fullname_lower()}_homework"] = homeworks
self.data[f"{
eleve.get_fullname_lower()}_homework"] = homeworks

self.compare_data(
previous_data,
Expand Down Expand Up @@ -205,14 +207,18 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
eleve,
year_data,
self.hass.config.config_dir,
self.config_entry.options.get("notes_affichees", GRADES_TO_DISPLAY)
self.config_entry.options.get(
"notes_affichees", GRADES_TO_DISPLAY)
)
disciplines = grades_evaluations["disciplines"]
self.data[f"{eleve.get_fullname_lower()}_disciplines"] = disciplines
self.data[f"{
eleve.get_fullname_lower()}_disciplines"] = disciplines
for discipline in disciplines:
self.data[f"{eleve.get_fullname_lower()}_{discipline["name"]}"] = discipline
self.data[f"{eleve.get_fullname_lower()}_{
discipline["name"]}"] = discipline

self.data[f"{eleve.get_fullname_lower()}_moyenne_generale"] = grades_evaluations["moyenne_generale"]
self.data[f"{eleve.get_fullname_lower(
)}_moyenne_generale"] = grades_evaluations["moyenne_generale"]

self.data[f"{eleve.get_fullname_lower()}_grades"] = (
grades_evaluations["grades"]
Expand All @@ -236,7 +242,8 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
eleve,
)
except Exception as ex:
_LOGGER.warning("Error getting grades from ecole directe: %s", ex)
_LOGGER.warning(
"Error getting grades from ecole directe: %s", ex)

if DEBUG_ON or "EDT" in eleve.modules:
try:
Expand Down Expand Up @@ -281,15 +288,17 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
)
self.data[f"{eleve.get_fullname_lower()}_timetable_period"] = list(
filter(
lambda lesson: lesson["start"].date() >= current_week_begin
lambda lesson: lesson["start"].date(
) >= current_week_begin
and lesson["start"].date() <= current_week_end,
lessons,
)
)
self.data[f"{eleve.get_fullname_lower()}_timetable_period_1"] = (
list(
filter(
lambda lesson: lesson["start"].date() >= next_week_begin
lambda lesson: lesson["start"].date(
) >= next_week_begin
and lesson["start"].date() <= next_week_end,
lessons,
)
Expand All @@ -306,7 +315,8 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
)

except Exception as ex:
_LOGGER.warning("Error getting Lessons from ecole directe: %s", ex)
_LOGGER.warning(
"Error getting Lessons from ecole directe: %s", ex)

if DEBUG_ON or "VIE_SCOLAIRE" in eleve.modules:
try:
Expand Down Expand Up @@ -378,7 +388,8 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
self.hass.config.config_dir,
)
except Exception as ex:
_LOGGER.warning("Error getting messages from ecole directe: %s", ex)
_LOGGER.warning(
"Error getting messages from ecole directe: %s", ex)

return self.data

Expand Down
58 changes: 34 additions & 24 deletions custom_components/ecole_directe/ecole_directe_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def get_response(token, url, payload, file_path):
payload = "data={}"

_LOGGER.debug("URL: [%s] - Payload: [%s]", url, payload)
response = requests.post(url, data=payload, headers=get_headers(token), timeout=120)
response = requests.post(
url, data=payload, headers=get_headers(token), timeout=120)

try:
resp_json = response.json()
Expand All @@ -71,7 +72,8 @@ def get_response(token, url, payload, file_path):
json.dump(resp_json, f, ensure_ascii=False, indent=4)

except Exception as ex:
raise RequestError(f"Error with URL:[{url}]: {response.content}") from ex
raise RequestError(f"Error with URL:[{url}]: {
response.content}") from ex

if "code" not in resp_json:
raise RequestError(f"Error with URL:[{url}]: json:[{resp_json}]")
Expand All @@ -82,7 +84,8 @@ def get_response(token, url, payload, file_path):

if resp_json["code"] != 200:
raise RequestError(
f"Error with URL:[{url}] - Code {resp_json["code"]}: {resp_json["message"]}"
f"Error with URL:[{url}] - Code {resp_json["code"]
}: {resp_json["message"]}"
)

_LOGGER.debug("%s", resp_json)
Expand Down Expand Up @@ -134,7 +137,8 @@ def __init__(self, data):
if "eleves" in data["data"]["accounts"][0]["profile"]:
for eleve in data["data"]["accounts"][0]["profile"]["eleves"]:
self.eleves.append(
EDEleve(eleve, data["data"]["accounts"][0]["nomEtablissement"])
EDEleve(eleve, data["data"]
["accounts"][0]["nomEtablissement"])
)


Expand Down Expand Up @@ -177,8 +181,8 @@ def get_fullname_lower(self) -> str | None:
"""Student fullname lowercase"""
return f"{re.sub("[^A-Za-z]", "_",
self.eleve_firstname.lower())
}_{
re.sub("[^A-Za-z]", "_", self.eleve_lastname.lower())}"
}_{
re.sub("[^A-Za-z]", "_", self.eleve_lastname.lower())}"

def get_fullname(self) -> str | None:
"""Student fullname"""
Expand Down Expand Up @@ -254,7 +258,8 @@ def get_ecoledirecte_session(data, config_path, hass) -> EDSession | None:
rep = []
propositions = qcm["propositions"]
for proposition in propositions:
rep.append(base64.b64decode(proposition).decode("utf-8"))
rep.append(base64.b64decode(
proposition).decode("utf-8"))

qcm_json[question] = rep

Expand Down Expand Up @@ -475,7 +480,7 @@ def clean_html(raw_html):
return cleantext


def get_grades_evaluations(token, eleve, annee_scolaire, config_path, grades_dispaly = GRADES_TO_DISPLAY):
def get_grades_evaluations(token, eleve, annee_scolaire, config_path, grades_dispaly=GRADES_TO_DISPLAY):
"""get grades"""

if DEBUG_ON:
Expand Down Expand Up @@ -505,22 +510,24 @@ def get_grades_evaluations(token, eleve, annee_scolaire, config_path, grades_dis
if "periodes" in data:
data["periodes"].sort(key=operator.itemgetter("dateDebut"))
for periode_json in data["periodes"]:
if "trimestre" not in periode_json["periode"].lower():
continue
if datetime.now() < datetime.strptime(
periode_json["dateDebut"], "%Y-%m-%d"
):
continue
if datetime.now() > datetime.strptime(periode_json["dateFin"], "%Y-%m-%d"):
continue
response["disciplines"] = get_disciplines_periode(periode_json)
if periode_json["ensembleMatieres"]:
response["moyenne_generale"] = {
"moyenneGenerale": periode_json["ensembleMatieres"].get("moyenneGenerale", "").replace(",","."),
"moyenneClasse": periode_json["ensembleMatieres"].get("moyenneClasse", "").replace(",","."),
"moyenneMin": periode_json["ensembleMatieres"].get("moyenneMin", "").replace(",","."),
"moyenneMax": periode_json["ensembleMatieres"].get("moyenneMax", "").replace(",","."),
"dateCalcul": periode_json["ensembleMatieres"].get("dateCalcul", ""),
}

if "ensembleMatieres" in periode_json:
if "moyenneGenerale" in periode_json["ensembleMatieres"]:
response["moyenne_generale"] = {
"moyenneGenerale": periode_json["ensembleMatieres"].get("moyenneGenerale", "").replace(",", "."),
"moyenneClasse": periode_json["ensembleMatieres"].get("moyenneClasse", "").replace(",", "."),
"moyenneMin": periode_json["ensembleMatieres"].get("moyenneMin", "").replace(",", "."),
"moyenneMax": periode_json["ensembleMatieres"].get("moyenneMax", "").replace(",", "."),
"dateCalcul": periode_json["ensembleMatieres"].get("dateCalcul", ""),
}
break

if "notes" in data:
Expand Down Expand Up @@ -580,10 +587,10 @@ def get_disciplines_periode(data):
for discipline_json in data["ensembleMatieres"]["disciplines"]:
discipline = {
"name": discipline_json.get("discipline", "").lower(),
"moyenne": discipline_json.get("moyenne", "").replace(",","."),
"moyenneClasse": discipline_json.get("moyenneClasse", "").replace(",","."),
"moyenneMin": discipline_json.get("moyenneMin", "").replace(",","."),
"moyenneMax": discipline_json.get("moyenneMax", "").replace(",","."),
"moyenne": discipline_json.get("moyenne", "").replace(",", "."),
"moyenneClasse": discipline_json.get("moyenneClasse", "").replace(",", "."),
"moyenneMin": discipline_json.get("moyenneMin", "").replace(",", "."),
"moyenneMax": discipline_json.get("moyenneMax", "").replace(",", "."),
"appreciations": discipline_json.get("appreciations", ""),
}
disciplines.append(discipline)
Expand Down Expand Up @@ -649,7 +656,8 @@ def get_vie_scolaire(token, eleve, config_path):

if DEBUG_ON:
# Opening JSON file
f = open(config_path + INTEGRATION_PATH + "test/test_vie_scolaire.json")
f = open(config_path + INTEGRATION_PATH +
"test/test_vie_scolaire.json")
json_resp = json.load(f)
else:
json_resp = get_response(
Expand Down Expand Up @@ -738,7 +746,8 @@ def get_lessons(token, eleve, date_debut, date_fin, config_path, lunch_break_tim
json_resp = get_response(
token,
f"{APIURL}/E/{eleve.eleve_id}/emploidutemps.awp?verbe=get&v={APIVERSION}",
f"data={{'dateDebut': '{date_debut}','dateFin': '{date_fin}','avecTrous': false}}",
f"data={{'dateDebut': '{date_debut}','dateFin': '{
date_fin}','avecTrous': false}}",
f"{config_path + INTEGRATION_PATH}{eleve.eleve_id}_get_lessons.json",
)

Expand Down Expand Up @@ -796,7 +805,8 @@ def get_formulaires(token, account_type, id_entity, config_path):
"""Get formulaires"""

payload = (
'data={"typeEntity": "' + account_type + '","idEntity":' + str(id_entity) + "}"
'data={"typeEntity": "' + account_type +
'","idEntity":' + str(id_entity) + "}"
)
json_resp = get_response(
token,
Expand Down

0 comments on commit 30ed28f

Please sign in to comment.