Browse Source

adição de digest email

pull/178/head
lucasmndc 5 months ago
parent
commit
36241668b0
  1. 6
      sigi/apps/utils/admin.py
  2. 34
      sigi/apps/utils/management/jobs.py
  3. 41
      sigi/apps/utils/migrations/0005_cronjob_destinatario_email_cronjob_digest_and_more.py
  4. 85
      sigi/apps/utils/models.py

6
sigi/apps/utils/admin.py

@ -65,6 +65,8 @@ class CronjobAdmin(admin.ModelAdmin):
"expressao_cron", "expressao_cron",
"get_schedule", "get_schedule",
"get_runner", "get_runner",
"destinatario_email",
"digest",
) )
fields = [ fields = [
"job_name", "job_name",
@ -72,6 +74,8 @@ class CronjobAdmin(admin.ModelAdmin):
"get_help", "get_help",
"expressao_cron", "expressao_cron",
"manter_logs", "manter_logs",
"destinatario_email",
"digest",
] ]
readonly_fields = ("job_name", "app_name", "get_help") readonly_fields = ("job_name", "app_name", "get_help")
inlines = [JobScheduleInline] inlines = [JobScheduleInline]
@ -157,6 +161,7 @@ class JobScheduleAdmin(admin.ModelAdmin):
"iniciado", "iniciado",
"tempo_gasto", "tempo_gasto",
"get_runner", "get_runner",
"enviado",
] ]
fields = [ fields = [
"job", "job",
@ -164,6 +169,7 @@ class JobScheduleAdmin(admin.ModelAdmin):
"iniciar", "iniciar",
"iniciado", "iniciado",
"tempo_gasto", "tempo_gasto",
"enviado",
] ]
readonly_fields = fields readonly_fields = fields
list_filter = ("status", "job") list_filter = ("status", "job")

34
sigi/apps/utils/management/jobs.py

@ -80,14 +80,14 @@ class JobReportMixin:
"output_encoding": "unicode", "output_encoding": "unicode",
}, },
) )
send_mail( # send_mail(
subject=f"JOB: {self.help}", # subject=f"JOB: {self.help}",
message=rst, # message=rst,
from_email=settings.SERVER_EMAIL, # from_email=settings.SERVER_EMAIL,
recipient_list=Config.get_param("EMAIL_JOBS"), # recipient_list=Config.get_param("EMAIL_JOBS"),
fail_silently=True, # fail_silently=True,
html_message=html, # html_message=html,
) # )
print(rst) print(rst)
def prepare_report(self, start_time, end_time): def prepare_report(self, start_time, end_time):
@ -128,13 +128,13 @@ class JobReportMixin:
rst, html = self.prepare_report(start_time, end_time) rst, html = self.prepare_report(start_time, end_time)
if self.send_report_mail: # if self.send_report_mail:
send_mail( # send_mail(
subject=f"JOB: {self.help}", # subject=f"JOB: {self.help}",
message=rst, # message=rst,
from_email=settings.SERVER_EMAIL, # from_email=settings.SERVER_EMAIL,
recipient_list=Config.get_param("EMAIL_JOBS"), # recipient_list=Config.get_param("EMAIL_JOBS"),
fail_silently=True, # fail_silently=True,
html_message=html, # html_message=html,
) # )
print(rst) print(rst)

41
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"),
),
]

85
sigi/apps/utils/models.py

@ -9,6 +9,9 @@ from django.utils.formats import localize
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from django_extensions.management.jobs import get_job, get_jobs from django_extensions.management.jobs import get_job, get_jobs
from tinymce.models import HTMLField 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): class SigiAlert(models.Model):
@ -59,6 +62,34 @@ class Cronjob(models.Model):
default=30, 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: class Meta:
ordering = ("app_name", "job_name") ordering = ("app_name", "job_name")
verbose_name = _("Cron job") verbose_name = _("Cron job")
@ -147,6 +178,7 @@ class JobSchedule(models.Model):
resultado = models.TextField( resultado = models.TextField(
_("resultado da execução"), blank=True, editable=False _("resultado da execução"), blank=True, editable=False
) )
enviado = models.BooleanField(_("enviado"), default=False)
class Meta: class Meta:
ordering = ("-iniciar",) ordering = ("-iniciar",)
@ -190,6 +222,59 @@ class JobSchedule(models.Model):
self.tempo_gasto = timezone.localtime() - self.iniciado self.tempo_gasto = timezone.localtime() - self.iniciado
self.save() 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): class Config(models.Model):
PARAMETRO_CHOICES = ( PARAMETRO_CHOICES = (

Loading…
Cancel
Save