Export to Excel Pédiatrie
dashboard.export_to_excel_pedia
Functions
export_to_excel_pedia(env, date)
Exporte des données vers un fichier Excel concernant la situation hospitalière en pédiatrie.
Cette fonction utilise une instance de DateTimeManager pour obtenir les informations de date et d'heure d'exécution requises. Elle importe des fichiers CSV et un modèle Excel, traite les données pour générer des récapitulatifs au niveau des régions et des départements ainsi que des évolutions des capacités en lits installés.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Notes
- Assurez-vous que le dossier d'exportation existe avant l'exécution de cette fonction.
- Les fichiers CSV attendus doivent respecter une certaine structure afin que la fonction puisse les traiter correctement.
- Utilise les modules 'openpyxl' pour le traitement Excel et 'pandas' pour la manipulation des données.
Exemple d'utilisation: fire.Fire(export_to_excel_pedia)
Source code in dashboard/export_to_excel_pedia.py
def export_to_excel_pedia(env:str, date) -> None:
"""
Exporte des données vers un fichier Excel concernant la situation hospitalière en pédiatrie.
Cette fonction utilise une instance de DateTimeManager pour obtenir les informations de date et
d'heure d'exécution requises. Elle importe des fichiers CSV et un modèle Excel, traite les
données pour générer des récapitulatifs au niveau des régions et des départements ainsi que
des évolutions des capacités en lits installés.
Args:
env (str): L'environnement de connexion à la base de données qui contient les informations nécessaires.
date (str): La date pour laquelle les données doivent être exportées, au format 'YYYY-MM-DD'.
Returns:
None: La fonction ne retourne pas de valeur. Elle génère un fichier Excel dans un dossier
spécifié, contenant les données formatées.
Raises:
OSError: Si une erreur survient lors de la suppression d'un ancien fichier Excel.
Pandas.errors.EmptyDataError: Si les fichiers CSV sont vides ou introuvables.
Exception: Pour toute autre exception qui pourrait survenir lors du traitement des données.
Notes:
- Assurez-vous que le dossier d'exportation existe avant l'exécution de cette fonction.
- Les fichiers CSV attendus doivent respecter une certaine structure afin que la fonction puisse
les traiter correctement.
- Utilise les modules 'openpyxl' pour le traitement Excel et 'pandas' pour la manipulation des données.
Exemple d'utilisation:
fire.Fire(export_to_excel_pedia)
"""
# Création d'une instance DateTimeManager
_dt_manager = DateTimeManager(date)
# Variables à exporter pour compatibilité avec vos anciens imports
hour_exec = _dt_manager.execution_hour
today = _dt_manager.today
today_Ymd_short = _dt_manager.today_Ymd_short
today_Ymd_long = _dt_manager.today_Ymd_long
today_jmA = _dt_manager.today_jmA
prev_day_Ymd_short = _dt_manager.prev_day_Ymd_short
prev_day_Ymd_long = _dt_manager.prev_day_Ymd_long
# On exporte le mapping des mois sous le nom "month" ou "month_const"
month = _dt_manager.MONTH_NAMES # ou utilisez "month_const" si vous préférez
month_const = _dt_manager.MONTH_NAMES
PRINT_TODAY = _dt_manager.print_today
PRINT_PREV_DAY = _dt_manager.print_prev_day
PREV_FILE_DATE = _dt_manager.prev_file_date
FILE_DATE = _dt_manager.file_date
PRINT_XLSX_DATETIME = _dt_manager.print_xlsx_datetime
# --------------- TDB Pediatrie --------------
logger.info("Importation des fichiers CSV et du template Excel")
#%% ------------------ Importation des csv ----------------------
xfile = openpyxl.load_workbook(f'{metadata_dir}/template_pediatrie.xlsx')
recap_dep = pd.read_csv(f"{csv_dir}/recap_dep_pedia.csv", dtype={"departement": "str"})
recap_region = pd.read_csv(f"{csv_dir}/recap_region_pedia.csv")
recap_tot = pd.read_csv(f"{csv_dir}/recap_tot_pedia.csv")
ss_cat = ['rea_neonat', 'rea_pediatrie', 'surveillance_continue_pediatrie', 'usi_pediatrie']
recap_dep = recap_dep[recap_dep['sous_categorie_lit'].isin(ss_cat)]
recap_region = recap_region[recap_region['sous_categorie_lit'].isin(ss_cat)]
recap_tot = recap_tot[recap_tot['sous_categorie_lit'].isin(ss_cat)]
#%% ------------------ Sheet 1 ---------------------------------
logger.info("Traitement de la feuille 'Régions'")
recap_region["region_lib"] = [mapping_regions[i] for i in recap_region["region"]]
sheet = xfile.get_sheet_by_name('Régions')
sheet.cell(row=1, column=5,
value=f"{PRINT_XLSX_DATETIME} - Situation hospitalière en pédiatrie - France")
sheet.cell(row=4, column=1,
value=f"Source : ROR ({today_jmA})")
sheet.cell(row=14, column=1,
value=f"Données sur les lits disponibles à date : extraction du ROR à {hour_exec}h chaque jour.")
for cat in recap_region["sous_categorie_lit"].unique():
i, j = pos_regions_pedia[cat]
tmp_cate = recap_region[recap_region["sous_categorie_lit"] == cat].reset_index(drop=True)
for new_reg in np.array(REGIONS)[~np.isin(REGIONS, tmp_cate["region"].unique())]:
new_row = pd.DataFrame([{"region_lib": mapping_regions[new_reg]}])
tmp_cate = pd.concat([tmp_cate, new_row], ignore_index=True)
tmp_cate.index = tmp_cate["region_lib"]
tmp_cate = tmp_cate.loc[ordre_regions]
for reg in tmp_cate["region_lib"].unique():
tmp = tmp_cate[tmp_cate["region_lib"] == reg]
for k, row in tmp.iterrows():
sheet.cell(row=i, column=j, value=row["lit_capacite_tot"])
sheet.cell(row=i, column=j + 1, value=row["fraicheur"])
sheet.cell(row=i, column=j + 2, value=row["lit_dispo"])
sheet.cell(row=i, column=j + 3, value=row["taux_occ"])
i = i + 1
# ----------------- Total regions -------------------------------
for cat in recap_tot["sous_categorie_lit"].unique():
[i, j] = pos_tot_pedia[cat]
tmp_cate = recap_tot[recap_tot["sous_categorie_lit"] == cat].reset_index(drop=True)
sheet.cell(row=i, column=j, value=tmp_cate["lit_capacite_tot"].iloc[0])
sheet.cell(row=i, column=j + 1, value=tmp_cate["fraicheur"].iloc[0])
sheet.cell(row=i, column=j + 2, value=tmp_cate["lit_dispo"].iloc[0])
sheet.cell(row=i, column=j + 3, value=tmp_cate["taux_occ"].iloc[0])
# ------------------ GUA + MAY -----------------
sheet.cell(row=35, column=2, value="ND")
#%% ------------------ Sheet 2 ---------------------------------
logger.info("Traitement de la feuille 'Départements'")
sheet2 = xfile.get_sheet_by_name('Départements')
sheet2.cell(row=1, column=2,
value=f"{PRINT_XLSX_DATETIME} - Situation hospitalières en pédiatrie - France")
sheet2.cell(row=4, column=1,
value=f"Source : ROR ({today_jmA})")
sheet2.cell(row=14, column=1,
value=f"Données sur les lits disponibles à date : extraction du ROR à {hour_exec}h chaque jour.")
# ------------- Departements ------------------------------
recap_dep["dep_lib"] = mapping_departement.loc[recap_dep["departement"], "nom_departement"].to_list()
for cat in recap_dep["sous_categorie_lit"].unique():
i, j = pos_dep_pedia[cat]
tmp_cate = recap_dep[recap_dep["sous_categorie_lit"] == cat].reset_index(drop=True)
for new_dep in np.array(ordre_dep)[~np.isin(ordre_dep, tmp_cate["dep_lib"].unique())]:
new_row = pd.DataFrame([{"dep_lib": new_dep}])
tmp_cate = pd.concat([tmp_cate, new_row], ignore_index=True)
tmp_cate.index = tmp_cate["dep_lib"]
tmp_cate = tmp_cate.loc[ordre_dep]
for dep in tmp_cate["dep_lib"].unique():
tmp = tmp_cate[tmp_cate["dep_lib"] == dep]
sheet2.cell(row=i, column=j, value=tmp["lit_capacite_tot"].iloc[0])
sheet2.cell(row=i, column=j + 1, value=tmp["fraicheur"].iloc[0])
sheet2.cell(row=i, column=j + 2, value=tmp["lit_dispo"].iloc[0])
sheet2.cell(row=i, column=j + 3, value=tmp["taux_occ"].iloc[0])
i = i + 1
# ----------------- Total Département -------------------------------
for cat in recap_tot["sous_categorie_lit"].unique():
[i, j] = pos_tot_dep_pedia[cat]
tmp_cate = recap_tot[recap_tot["sous_categorie_lit"] == cat].reset_index(drop=True)
sheet2.cell(row=i, column=j, value=tmp_cate["lit_capacite_tot"].iloc[0])
sheet2.cell(row=i, column=j + 1, value=tmp_cate["fraicheur"].iloc[0])
sheet2.cell(row=i, column=j + 2, value=tmp_cate["lit_dispo"].iloc[0])
sheet2.cell(row=i, column=j + 3, value=tmp_cate["taux_occ"].iloc[0])
# ------------------ GUA + MAY -----------------
sheet2.cell(row=118, column=3, value="ND")
#%% ------------------ Sheet 3 ---------------------------------
logger.info("Traitement de la feuille 'Evolution_Capacites'")
sheet = xfile.get_sheet_by_name('Evolution_Capacites')
df = req2table(f"SELECT * FROM table_union WHERE categorie_lit::text = 'pediatrie' AND capacite_extract_datetime::date = '{prev_day_Ymd_long}' AND h_exec='{hour_exec}'",
env)
if df.shape[0] == 0:
req = f"SELECT MAX(capacite_extract_datetime::date) FROM table_union WHERE categorie_lit::text = 'pediatrie' AND capacite_extract_datetime < '{prev_day_Ymd_long}' AND h_exec='{hour_exec}'"
prev_day_Ymd_short = req2table(req, env)['max'].iloc[0]
df = req2table(f"SELECT * FROM table_union WHERE categorie_lit::text = 'pediatrie' AND capacite_extract_datetime::date = '{prev_day_Ymd_long}' AND h_exec='{hour_exec}'",
env)
PRINT_PREV_DAY = f"{prev_day_Ymd_short.strftime('%d')} {month[prev_day_Ymd_short.strftime('%m')]} {prev_day_Ymd_short.strftime('%Y')}"
df["date"] = pd.to_datetime(df["capacite_extract_datetime"].dt.date)
df = df[~df["lit_capacite"].isnull()]
df = df[df["sous_categorie_lit"] != "rea_brules"]
df = df[(df["region"] != "IDF") | (df["lit_capacite"] != 100)]
df.loc[df['sous_categorie_lit'] == 'rea_mixte', 'sous_categorie_lit'] = 'rea_pediatrie'
df.loc[df['sous_categorie_lit'] == 'rea_brules_possible_pediatrie', 'sous_categorie_lit'] = 'rea_pediatrie'
df.loc[df['sous_categorie_lit'] == 'usc_brules_possible_pediatrie', 'sous_categorie_lit'] = 'surveillance_continue_pediatrie'
# aggrégation niveau region
df_region = df
tmp = df_region.groupby(["region", "sous_categorie_lit"])["lit_capacite"].sum().reset_index(name="lit_capacite_prec")
tmp = tmp[tmp['sous_categorie_lit'].isin(ss_cat)]
recap_region = recap_region.merge(tmp, on=["sous_categorie_lit", "region"], how="outer")
recap_region["region_lib"] = [mapping_regions[i] for i in recap_region["region"]]
# Total
tmp = df_region.groupby(["sous_categorie_lit"])["lit_capacite"].sum().reset_index(name="lit_capacite_prec")
recap_tot = recap_tot.merge(tmp, on=["sous_categorie_lit"], how="left")
sheet.cell(row=1, column=3,
value=f"{PRINT_XLSX_DATETIME} - Situation hospitalière - France")
sheet.cell(row=3, column=1,
value=f"Evolution des capacités en lits installés entre le {PRINT_PREV_DAY} et le {PRINT_TODAY}")
sheet.cell(row=4, column=1,
value=f"Source : ROR ({today_jmA})")
for j in [2, 4, 6, 8]:
sheet.cell(row=11, column=j + 1, value=today.strftime("%d-%m-%Y"))
sheet.cell(row=11, column=j, value=prev_day_Ymd_short.strftime("%d-%m-%Y"))
for cat in recap_region["sous_categorie_lit"].unique():
i, j = pos_regions_evolution_pedia[cat]
tmp_cate = recap_region[recap_region["sous_categorie_lit"] == cat].reset_index(drop=True)
for new_reg in np.array(REGIONS)[~np.isin(REGIONS, tmp_cate["region"].unique())]:
new_row = pd.DataFrame([{"region_lib": mapping_regions[new_reg]}])
tmp_cate = pd.concat([tmp_cate, new_row], ignore_index=True)
tmp_cate.index = tmp_cate["region_lib"]
tmp_cate = tmp_cate.loc[ordre_regions]
for reg in tmp_cate["region_lib"].unique():
tmp = tmp_cate[tmp_cate["region_lib"] == reg]
for k, row in tmp.iterrows():
sheet.cell(row=i, column=j + 1, value=row["lit_capacite_tot"])
sheet.cell(row=i, column=j, value=row["lit_capacite_prec"])
i = i + 1
# ----------------- Total regions -------------------------------
for cat in recap_tot["sous_categorie_lit"].unique():
[i, j] = pos_tot_evolution_pedia[cat]
tmp_cate = recap_tot[recap_tot["sous_categorie_lit"] == cat].reset_index(drop=True)
sheet.cell(row=i, column=j + 1, value=tmp_cate["lit_capacite_tot"].iloc[0])
sheet.cell(row=i, column=j, value=tmp_cate["lit_capacite_prec"].iloc[0])
# ------------------ GUA + MAY -----------------
sheet.cell(row=29, column=2, value="ND")
#%% ----------------------- Export -------------------
logger.info("Exportation du fichier Excel")
export_path = f"{DOSSIER_DIFFUSION}/{PREV_FILE_DATE}_TDB_pediatrie.xlsx"
if os.path.exists(export_path):
try:
os.remove(export_path)
logger.info("Ancien fichier supprimé: {}", export_path)
except OSError as e:
logger.error("Erreur lors de la suppression de {}: {}", export_path, e)
filename = f"{DOSSIER_DIFFUSION}/{FILE_DATE}_TDB_pediatrie.xlsx"
xfile.save(filename)
logger.info("Fichier Excel sauvegardé: {}", filename)