Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed email module #361

Merged
merged 14 commits into from
Dec 23, 2024
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Code contributions to the release:
- Modified the module logic to dynamically select and render email templates based on user input. [#349](https://github.com/BU-ISCIII/relecov-tools/pull/349)
- Enhanced email formatting and added a default CC to bioinformatica@isciii.es. [#349](https://github.com/BU-ISCIII/relecov-tools/pull/349)
- Validate module now takes an optional argument to select the name of the sheet to check in excel file [#357](https://github.com/BU-ISCIII/relecov-tools/pull/357)
- Fixed email module [#361](https://github.com/BU-ISCIII/relecov-tools/pull/361)

#### Fixes

Expand Down
24 changes: 19 additions & 5 deletions relecov_tools/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def validate(json_file, json_schema, metadata, out_folder, excel_sheet):
"--validate-file",
required=True,
type=click.Path(exists=True),
help="Path to the validation file (validate.json)",
help="Path to the validation summary json file (validate_log_summary.json)",
)
@click.option(
"-r",
Expand All @@ -286,14 +286,22 @@ def validate(json_file, json_schema, metadata, out_folder, excel_sheet):
type=click.Path(exists=True),
help="Path to file",
)
@click.option(
"-t",
"--template_path",
type=click.Path(exists=True),
required=True,
default=None,
help="Path to relecov-tools templates folder",
)
@click.option(
"-p",
"--email-psswd",
help="Password for bioinformatica@isciii.es",
required=False,
default=None,
)
def send_mail(validate_file, receiver_email, attachments, email_psswd):
def send_mail(validate_file, receiver_email, attachments, template_path, email_psswd):
"""
Send a sample validation report by mail.
"""
Expand All @@ -305,6 +313,7 @@ def send_mail(validate_file, receiver_email, attachments, email_psswd):
)

validate_data = relecov_tools.utils.read_json_file(validate_file)
batch = os.path.basename(os.path.dirname(os.path.abspath(validate_file)))

if not validate_data:
raise ValueError("Error: Validation data could not be loaded.")
Expand All @@ -313,7 +322,7 @@ def send_mail(validate_file, receiver_email, attachments, email_psswd):

invalid_count = relecov_tools.log_summary.LogSum.get_invalid_count(validate_data)

email_sender = relecov_tools.mail.EmailSender(config)
email_sender = relecov_tools.mail.EmailSender(config, template_path)

template_choice = click.prompt(
"Select the type of template:\n1. Validation with errors\n2. Validation successful",
Expand Down Expand Up @@ -349,6 +358,7 @@ def send_mail(validate_file, receiver_email, attachments, email_psswd):
invalid_count=invalid_count,
submitting_institution_code=submitting_institution_code,
template_name=template_name,
batch=batch,
)

if email_body is None:
Expand All @@ -369,9 +379,13 @@ def send_mail(validate_file, receiver_email, attachments, email_psswd):
if not final_receiver_email:
raise ValueError("Error: Could not obtain the recipient's email address.")

subject = f"Informe de Validación de Muestras - {institution_name}"
subject = (
f"RELECOV - Informe de Validación de Muestras {batch} - {institution_name}"
)
try:
email_sender.send_email(final_receiver_email, subject, email_body, attachments)
email_sender.send_email(
final_receiver_email, subject, email_body, attachments, email_psswd
)
except Exception as e:
log.exception(f"EXCEPTION FOUND: {e}")
raise
Expand Down
13 changes: 9 additions & 4 deletions relecov_tools/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@


class EmailSender:
def __init__(self, config):
def __init__(self, config, template_path):
self.config = config
self.template_path = self.config.get("delivery_template_path_file")
self.template_path = template_path
Shettland marked this conversation as resolved.
Show resolved Hide resolved
self.yaml_cred_path = self.config.get("yaml_cred_path")

if not self.config:
Expand Down Expand Up @@ -49,6 +49,7 @@ def render_email_template(
invalid_count=None,
submitting_institution_code=None,
template_name=None,
batch=None,
):

institution_info = self.get_institution_info(submitting_institution_code)
Expand All @@ -65,6 +66,7 @@ def render_email_template(
else 0
),
"additional_info": additional_info,
"batch": batch,
}

templates_base_dir = os.path.dirname(self.template_path)
Expand All @@ -74,7 +76,7 @@ def render_email_template(

return email_template

def send_email(self, receiver_email, subject, body, attachments):
def send_email(self, receiver_email, subject, body, attachments, email_psswd):

if not isinstance(receiver_email, list):
raise ValueError(
Expand All @@ -90,7 +92,10 @@ def send_email(self, receiver_email, subject, body, attachments):
return

sender_email = self.config["email_host_user"]
email_password = credentials.get("email_password")

email_password = (
email_psswd if email_psswd else credentials.get("email_password")
)

if not email_password:
print("The e-mail password could not be found.")
Expand Down
12 changes: 5 additions & 7 deletions relecov_tools/templates/jinja_template_with_errors.j2
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@

Asunto: Informe de Validación de Muestras - {{ submitting_institution }}

Estimado/a responsable de la subida de datos de secuenciación del {{ submitting_institution }},

Le informamos que tras el proceso de validación de los datos enviados, el número de muestras que ha sido imposible validar es de {{ invalid_count }}.
Le informamos que tras el proceso de validación de los datos procesados a fecha {{ batch }}, el número de muestras que no ha sido posible validar es de {{ invalid_count }}.
Las muestras no han superado el proceso de validación debido a errores o faltas de información en los datos proporcionados. Le solicitamos que revise los detalles de cada muestra para subsanar los problemas.
Adjunto a este correo encontrará un documento en formato Excel con información detallada sobre los errores o la información faltante para cada muestra. Le pedimos que proceda a realizar las correcciones necesarias y a reenviar los datos.
En la carpete del SFTP existe una carpeta llamada {{ batch }}_invalid_samples con un excel de metadatos a subsanar con los errores mencionados en el excel adjunto al correo y los .fastq asociados. Una vez subsanados los errores, se puede renombrar la carpeta quitando `_invalid_samples` del nombre, o notificarnoslo en respuesta a este correo para que nos encarguemos nosotros.

{{additional_info}}
Notas adicionales: {{additional_info}}

En caso de cualquier duda o aclaración, no dude en ponerse en contacto con el equipo técnico.
En caso de cualquier duda o aclaración, no dude en ponerse en contacto con el equipo técnico empleando este mismo hilo de correos.

Atentamente,

Equipo Relecov
Equipo RELECOV
Loading