diff --git a/sigi/apps/utils/admin.py b/sigi/apps/utils/admin.py index 268c1c0..0696222 100644 --- a/sigi/apps/utils/admin.py +++ b/sigi/apps/utils/admin.py @@ -65,6 +65,8 @@ class CronjobAdmin(admin.ModelAdmin): "expressao_cron", "get_schedule", "get_runner", + "destinatario_email", + "digest", ) fields = [ "job_name", @@ -72,6 +74,8 @@ class CronjobAdmin(admin.ModelAdmin): "get_help", "expressao_cron", "manter_logs", + "destinatario_email", + "digest", ] readonly_fields = ("job_name", "app_name", "get_help") inlines = [JobScheduleInline] @@ -157,6 +161,7 @@ class JobScheduleAdmin(admin.ModelAdmin): "iniciado", "tempo_gasto", "get_runner", + "enviado", ] fields = [ "job", @@ -164,6 +169,7 @@ class JobScheduleAdmin(admin.ModelAdmin): "iniciar", "iniciado", "tempo_gasto", + "enviado", ] readonly_fields = fields list_filter = ("status", "job") diff --git a/sigi/apps/utils/management/jobs.py b/sigi/apps/utils/management/jobs.py index 8638bef..60fa857 100644 --- a/sigi/apps/utils/management/jobs.py +++ b/sigi/apps/utils/management/jobs.py @@ -80,14 +80,14 @@ class JobReportMixin: "output_encoding": "unicode", }, ) - send_mail( - subject=f"JOB: {self.help}", - message=rst, - from_email=settings.SERVER_EMAIL, - recipient_list=Config.get_param("EMAIL_JOBS"), - fail_silently=True, - html_message=html, - ) + # send_mail( + # subject=f"JOB: {self.help}", + # message=rst, + # from_email=settings.SERVER_EMAIL, + # recipient_list=Config.get_param("EMAIL_JOBS"), + # fail_silently=True, + # html_message=html, + # ) print(rst) def prepare_report(self, start_time, end_time): @@ -128,13 +128,13 @@ class JobReportMixin: rst, html = self.prepare_report(start_time, end_time) - if self.send_report_mail: - send_mail( - subject=f"JOB: {self.help}", - message=rst, - from_email=settings.SERVER_EMAIL, - recipient_list=Config.get_param("EMAIL_JOBS"), - fail_silently=True, - html_message=html, - ) + # if self.send_report_mail: + # send_mail( + # subject=f"JOB: {self.help}", + # message=rst, + # from_email=settings.SERVER_EMAIL, + # recipient_list=Config.get_param("EMAIL_JOBS"), + # fail_silently=True, + # html_message=html, + # ) print(rst) diff --git a/sigi/apps/utils/migrations/0005_cronjob_destinatario_email_cronjob_digest_and_more.py b/sigi/apps/utils/migrations/0005_cronjob_destinatario_email_cronjob_digest_and_more.py new file mode 100644 index 0000000..960008a --- /dev/null +++ b/sigi/apps/utils/migrations/0005_cronjob_destinatario_email_cronjob_digest_and_more.py @@ -0,0 +1,41 @@ +# Generated by Django 5.0.6 on 2024-07-30 15:53 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("utils", "0004_alter_jobschedule_options_cronjob_manter_logs"), + ] + + operations = [ + migrations.AddField( + model_name="cronjob", + name="destinatario_email", + field=models.TextField( + blank=True, + help_text="Insira um endereço de e-mail por linha.", + verbose_name="destinatário(s) de e-mail", + ), + ), + migrations.AddField( + model_name="cronjob", + name="digest", + field=models.CharField( + choices=[ + ("N", "Enviar sem digest"), + ("D", "Enviar com digest diário"), + ("S", "Enviar com digest semanal"), + ], + default="N", + max_length=1, + verbose_name="digest", + ), + ), + migrations.AddField( + model_name="jobschedule", + name="enviado", + field=models.BooleanField(default=False, verbose_name="enviado"), + ), + ] diff --git a/sigi/apps/utils/models.py b/sigi/apps/utils/models.py index 0642b11..c7f6a4c 100644 --- a/sigi/apps/utils/models.py +++ b/sigi/apps/utils/models.py @@ -9,6 +9,9 @@ from django.utils.formats import localize from django.utils.translation import gettext as _ from django_extensions.management.jobs import get_job, get_jobs from tinymce.models import HTMLField +from django.core.mail import send_mail +from django.conf import settings +from datetime import timedelta class SigiAlert(models.Model): @@ -59,6 +62,34 @@ class Cronjob(models.Model): default=30, ) + destinatario_email = models.TextField( + _("destinatário(s) de e-mail"), + help_text=_("Insira um endereço de e-mail por linha."), + blank=True, + ) + + def get_emails_list(self): + return [ + email.strip() + for email in self.destinatario_email.splitlines() + if email.strip() + ] + + def __str__(self): + return f"Destinatários: {', '.join(self.get_emails_list())}" + + DIGEST_CHOICES = [ + ("N", _("Enviar sem digest")), + ("D", _("Enviar com digest diário")), + ("S", _("Enviar com digest semanal")), + ] + digest = models.CharField( + _("digest"), + max_length=1, + choices=DIGEST_CHOICES, + default="N", + ) + class Meta: ordering = ("app_name", "job_name") verbose_name = _("Cron job") @@ -147,6 +178,7 @@ class JobSchedule(models.Model): resultado = models.TextField( _("resultado da execução"), blank=True, editable=False ) + enviado = models.BooleanField(_("enviado"), default=False) class Meta: ordering = ("-iniciar",) @@ -190,6 +222,59 @@ class JobSchedule(models.Model): self.tempo_gasto = timezone.localtime() - self.iniciado self.save() + if self.job.destinatario_email == "": + return + + if self.job.digest == "N": + send_mail( + subject=f"JOB: {self.job.job_name}", + message=self.resultado, + from_email=settings.SERVER_EMAIL, + recipient_list=self.job.get_emails_list(), + fail_silently=True, + html_message=self.resultado, + ) + self.enviado = True + self.save() + + elif self.job.digest == "D": + self.send_digest_email(frequency="daily") + + elif self.job.digest == "S": + self.send_digest_email(frequency="weekly") + + def send_digest_email(self, frequency): + """Envia email de digest diário ou semanal.""" + now = timezone.localtime() + if frequency == "daily": + start_time = now - timedelta(days=1) + elif frequency == "weekly": + start_time = now - timedelta(weeks=1) + else: + raise ValueError("Invalid frequency for digest email.") + + job_schedules = JobSchedule.objects.filter( + job=self.job, + status=JobSchedule.STATUS_CONCLUIDO, + iniciado__gte=start_time, + enviado=False, + ) + + if job_schedules.exists(): + message = "\n\n".join( + [f"{js.iniciado}: {js.resultado}" for js in job_schedules] + ) + send_mail( + subject=f"Digest JOB: {self.job.job_name} ({frequency})", + message=message, + from_email=settings.SERVER_EMAIL, + recipient_list=self.job.get_emails_list(), + fail_silently=True, + html_message=message, + ) + + job_schedules.update(enviado=True) + class Config(models.Model): PARAMETRO_CHOICES = (