From f2c7e7a0d57dbd60640a5981e3d9e9e575f798dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 22 Mar 2024 15:32:10 -0300 Subject: [PATCH] =?UTF-8?q?Estrutura=20de=20parametriza=C3=A7=C3=A3o=20do?= =?UTF-8?q?=20SIGI.=20Gertiq=20#174105?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../eventos/jobs/daily/encerra_inscricao.py | 61 +++++++++++-------- sigi/apps/utils/admin.py | 8 ++- sigi/apps/utils/management/jobs.py | 18 ++++-- sigi/apps/utils/migrations/0003_config.py | 26 ++++++++ sigi/apps/utils/models.py | 42 ++++++++++++- sigi/menu_conf.yaml | 3 +- 6 files changed, 125 insertions(+), 33 deletions(-) create mode 100644 sigi/apps/utils/migrations/0003_config.py diff --git a/sigi/apps/eventos/jobs/daily/encerra_inscricao.py b/sigi/apps/eventos/jobs/daily/encerra_inscricao.py index 87b2e65..437ba6e 100644 --- a/sigi/apps/eventos/jobs/daily/encerra_inscricao.py +++ b/sigi/apps/eventos/jobs/daily/encerra_inscricao.py @@ -4,6 +4,7 @@ from django.conf import settings from django.utils import timezone from django.utils.translation import gettext as _ from sigi.apps.utils.management.jobs import JobReportMixin +from sigi.apps.utils.models import Config from sigi.apps.eventos.models import Evento INSCRICOES_ENCERRADAS = _("INSCRIÇÕES ENCERRADAS") @@ -16,9 +17,10 @@ class Job(JobReportMixin, DailyJob): report_data = [] def do_job(self): + dias_a_retroagir = int(Config.get_param("ENCERRA_INSCRICAO")[0]) self.report_data = [] hoje = timezone.localtime().replace(hour=23, minute=59, second=59) - retroagir = hoje - timezone.timedelta(days=30) + retroagir = hoje - timezone.timedelta(days=dias_a_retroagir) encerrar_inscricao = ( Evento.objects.exclude(publicar=False) @@ -26,13 +28,18 @@ class Job(JobReportMixin, DailyJob): .exclude(chave_inscricao=INSCRICOES_ENCERRADAS) ) - self.report_data.append(_("Inscrições encerradas")) - self.report_data.append("---------------------") - self.report_data.append("") + self.report_data.extend( + [ + "", + "", + _("Inscrições encerradas"), + "---------------------", + "", + ] + ) self.report_data.extend( [f"{e.nome} ({e.id})" for e in encerrar_inscricao] ) - self.report_data.append("") total_encerrar = encerrar_inscricao.update( chave_inscricao=INSCRICOES_ENCERRADAS @@ -42,27 +49,33 @@ class Job(JobReportMixin, DailyJob): data_termino__lte=retroagir ) - self.report_data.append(_("Despublicados")) - self.report_data.append("-------------") - self.report_data.append("") + self.report_data.extend( + [ + "", + "", + _("Despublicados"), + "-------------", + "", + ] + ) self.report_data.extend([f"{e.nome} ({e.id})" for e in despublicar]) - self.report_data.append("") total_despublicar = despublicar.update(publicar=False) - self.report_data.append(_("RESUMO")) - self.report_data.append("------") - self.report_data.append("") - self.report_data.append( - _( - "* Total de eventos alterados para inscrições encerradas: " - f"{total_encerrar}" - ) - ) - self.report_data.append( - _( - "* Total de eventos despublicados do portal: " - f"{total_despublicar}" - ) + self.report_data.extend( + [ + "", + "", + _("RESUMO"), + "------", + "", + _( + "* Total de eventos alterados para inscrições encerradas: " + f"{total_encerrar}" + ), + _( + "* Total de eventos despublicados do portal: " + f"{total_despublicar}" + ), + ] ) - self.report_data.append("") diff --git a/sigi/apps/utils/admin.py b/sigi/apps/utils/admin.py index 5279135..3130a4d 100644 --- a/sigi/apps/utils/admin.py +++ b/sigi/apps/utils/admin.py @@ -10,7 +10,7 @@ from django.utils.translation import gettext as _ from django_extensions.management.jobs import get_job, get_jobs from tinymce.models import HTMLField from tinymce.widgets import AdminTinyMCE -from sigi.apps.utils.models import SigiAlert, Cronjob, JobSchedule +from sigi.apps.utils.models import SigiAlert, Cronjob, JobSchedule, Config class JobScheduleInline(admin.TabularInline): @@ -212,3 +212,9 @@ class JobScheduleAdmin(admin.ModelAdmin): messages.SUCCESS, ) return redirect("admin:utils_jobschedule_change", object_id=object_id) + + +@admin.register(Config) +class ConfigAdmin(admin.ModelAdmin): + list_display = ["parametro", "valor"] + list_filter = ["parametro"] diff --git a/sigi/apps/utils/management/jobs.py b/sigi/apps/utils/management/jobs.py index 8eb64ca..8638bef 100644 --- a/sigi/apps/utils/management/jobs.py +++ b/sigi/apps/utils/management/jobs.py @@ -1,11 +1,13 @@ import datetime import docutils.core import traceback +from django.conf import settings from django.contrib.admin.models import LogEntry, ADDITION, CHANGE from django.contrib.contenttypes.models import ContentType -from django.core.mail import mail_admins +from django.core.mail import send_mail from django.template.loader import render_to_string from django_extensions.management.jobs import BaseJob +from sigi.apps.utils.models import Config class MisconfiguredError(Exception): @@ -78,11 +80,13 @@ class JobReportMixin: "output_encoding": "unicode", }, ) - mail_admins( - subject=self.help, + send_mail( + subject=f"JOB: {self.help}", message=rst, - html_message=html, + from_email=settings.SERVER_EMAIL, + recipient_list=Config.get_param("EMAIL_JOBS"), fail_silently=True, + html_message=html, ) print(rst) @@ -125,10 +129,12 @@ class JobReportMixin: rst, html = self.prepare_report(start_time, end_time) if self.send_report_mail: - mail_admins( + send_mail( subject=f"JOB: {self.help}", message=rst, - html_message=html, + 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/0003_config.py b/sigi/apps/utils/migrations/0003_config.py new file mode 100644 index 0000000..a1d7732 --- /dev/null +++ b/sigi/apps/utils/migrations/0003_config.py @@ -0,0 +1,26 @@ +# Generated by Django 4.2.7 on 2024-03-21 11:34 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('utils', '0002_cronjob_jobschedule'), + ] + + operations = [ + migrations.CreateModel( + name='Config', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('parametro', models.CharField(choices=[('ENCERRA_INSCRICAO', 'Encerra inscrições de oficinas no Portal'), ('EMAIL_JOBS', 'E-mail de jobs')], max_length=100, verbose_name='parâmetro')), + ('valor', models.CharField(max_length=200, verbose_name='valor do parâmettro')), + ], + options={ + 'verbose_name': 'Parâmetro de configuração', + 'verbose_name_plural': 'Parâmetros de configuração', + 'ordering': ('parametro',), + }, + ), + ] diff --git a/sigi/apps/utils/models.py b/sigi/apps/utils/models.py index 46c4af4..dbe7879 100644 --- a/sigi/apps/utils/models.py +++ b/sigi/apps/utils/models.py @@ -9,7 +9,6 @@ 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 sigi.apps.utils.management.jobs import JobReportMixin class SigiAlert(models.Model): @@ -182,3 +181,44 @@ class JobSchedule(models.Model): self.status = JobSchedule.STATUS_CONCLUIDO self.tempo_gasto = timezone.localtime() - self.iniciado self.save() + + +class Config(models.Model): + PARAMETRO_CHOICES = ( + ("ENCERRA_INSCRICAO", _("Encerra inscrições de oficinas no Portal")), + ("EMAIL_JOBS", _("E-mail de jobs")), + ) + DEFAULTS = { + "ENCERRA_INSCRICAO": "30", + "EMAIL_JOBS": "sigi@interlegis.leg.br", + } + parametro = models.CharField( + _("parâmetro"), max_length=100, choices=PARAMETRO_CHOICES + ) + valor = models.CharField(_("valor do parâmettro"), max_length=200) + + class Meta: + ordering = ("parametro",) + verbose_name = _("Parâmetro de configuração") + verbose_name_plural = _("Parâmetros de configuração") + + def __str__(self): + return f"{self.get_parametro_display()}: {self.valor}" + + @classmethod + def get_param(cls, parametro): + if parametro not in cls.DEFAULTS: + raise cls.DoesNotExist( + _( + f"Não existe o parâmetro '{parametro}'. " + f"As opções são {', '.join(cls.DEFAULTS.keys())}." + ) + ) + valores = list( + cls.objects.filter(parametro=parametro).values_list( + "valor", flat=True + ) + ) + if not valores: + valores.append(cls.DEFAULTS[parametro]) + return valores diff --git a/sigi/menu_conf.yaml b/sigi/menu_conf.yaml index f657305..0e47259 100644 --- a/sigi/menu_conf.yaml +++ b/sigi/menu_conf.yaml @@ -23,7 +23,8 @@ admin_menu: - title: Jobs agendados view_name: admin:utils_jobschedule_changelist querystr: status__exact=A - + - title: Configurações + view_name: admin:utils_config_changelist main_menu: - title: Municípios icon: location_city