Browse Source

Estrutura de parametrização do SIGI. Gertiq #174105

pull/172/head
Sesóstris Vieira 9 months ago
parent
commit
f2c7e7a0d5
  1. 61
      sigi/apps/eventos/jobs/daily/encerra_inscricao.py
  2. 8
      sigi/apps/utils/admin.py
  3. 18
      sigi/apps/utils/management/jobs.py
  4. 26
      sigi/apps/utils/migrations/0003_config.py
  5. 42
      sigi/apps/utils/models.py
  6. 3
      sigi/menu_conf.yaml

61
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 import timezone
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from sigi.apps.utils.management.jobs import JobReportMixin from sigi.apps.utils.management.jobs import JobReportMixin
from sigi.apps.utils.models import Config
from sigi.apps.eventos.models import Evento from sigi.apps.eventos.models import Evento
INSCRICOES_ENCERRADAS = _("INSCRIÇÕES ENCERRADAS") INSCRICOES_ENCERRADAS = _("INSCRIÇÕES ENCERRADAS")
@ -16,9 +17,10 @@ class Job(JobReportMixin, DailyJob):
report_data = [] report_data = []
def do_job(self): def do_job(self):
dias_a_retroagir = int(Config.get_param("ENCERRA_INSCRICAO")[0])
self.report_data = [] self.report_data = []
hoje = timezone.localtime().replace(hour=23, minute=59, second=59) 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 = ( encerrar_inscricao = (
Evento.objects.exclude(publicar=False) Evento.objects.exclude(publicar=False)
@ -26,13 +28,18 @@ class Job(JobReportMixin, DailyJob):
.exclude(chave_inscricao=INSCRICOES_ENCERRADAS) .exclude(chave_inscricao=INSCRICOES_ENCERRADAS)
) )
self.report_data.append(_("Inscrições encerradas")) self.report_data.extend(
self.report_data.append("---------------------") [
self.report_data.append("") "",
"",
_("Inscrições encerradas"),
"---------------------",
"",
]
)
self.report_data.extend( self.report_data.extend(
[f"{e.nome} ({e.id})" for e in encerrar_inscricao] [f"{e.nome} ({e.id})" for e in encerrar_inscricao]
) )
self.report_data.append("")
total_encerrar = encerrar_inscricao.update( total_encerrar = encerrar_inscricao.update(
chave_inscricao=INSCRICOES_ENCERRADAS chave_inscricao=INSCRICOES_ENCERRADAS
@ -42,27 +49,33 @@ class Job(JobReportMixin, DailyJob):
data_termino__lte=retroagir data_termino__lte=retroagir
) )
self.report_data.append(_("Despublicados")) self.report_data.extend(
self.report_data.append("-------------") [
self.report_data.append("") "",
"",
_("Despublicados"),
"-------------",
"",
]
)
self.report_data.extend([f"{e.nome} ({e.id})" for e in despublicar]) self.report_data.extend([f"{e.nome} ({e.id})" for e in despublicar])
self.report_data.append("")
total_despublicar = despublicar.update(publicar=False) total_despublicar = despublicar.update(publicar=False)
self.report_data.append(_("RESUMO")) self.report_data.extend(
self.report_data.append("------") [
self.report_data.append("") "",
self.report_data.append( "",
_( _("RESUMO"),
"* Total de eventos alterados para inscrições encerradas: " "------",
f"{total_encerrar}" "",
) _(
) "* Total de eventos alterados para inscrições encerradas: "
self.report_data.append( f"{total_encerrar}"
_( ),
"* Total de eventos despublicados do portal: " _(
f"{total_despublicar}" "* Total de eventos despublicados do portal: "
) f"{total_despublicar}"
),
]
) )
self.report_data.append("")

8
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 django_extensions.management.jobs import get_job, get_jobs
from tinymce.models import HTMLField from tinymce.models import HTMLField
from tinymce.widgets import AdminTinyMCE 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): class JobScheduleInline(admin.TabularInline):
@ -212,3 +212,9 @@ class JobScheduleAdmin(admin.ModelAdmin):
messages.SUCCESS, messages.SUCCESS,
) )
return redirect("admin:utils_jobschedule_change", object_id=object_id) return redirect("admin:utils_jobschedule_change", object_id=object_id)
@admin.register(Config)
class ConfigAdmin(admin.ModelAdmin):
list_display = ["parametro", "valor"]
list_filter = ["parametro"]

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

@ -1,11 +1,13 @@
import datetime import datetime
import docutils.core import docutils.core
import traceback import traceback
from django.conf import settings
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE from django.contrib.admin.models import LogEntry, ADDITION, CHANGE
from django.contrib.contenttypes.models import ContentType 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.template.loader import render_to_string
from django_extensions.management.jobs import BaseJob from django_extensions.management.jobs import BaseJob
from sigi.apps.utils.models import Config
class MisconfiguredError(Exception): class MisconfiguredError(Exception):
@ -78,11 +80,13 @@ class JobReportMixin:
"output_encoding": "unicode", "output_encoding": "unicode",
}, },
) )
mail_admins( send_mail(
subject=self.help, subject=f"JOB: {self.help}",
message=rst, message=rst,
html_message=html, from_email=settings.SERVER_EMAIL,
recipient_list=Config.get_param("EMAIL_JOBS"),
fail_silently=True, fail_silently=True,
html_message=html,
) )
print(rst) print(rst)
@ -125,10 +129,12 @@ 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:
mail_admins( send_mail(
subject=f"JOB: {self.help}", subject=f"JOB: {self.help}",
message=rst, message=rst,
html_message=html, from_email=settings.SERVER_EMAIL,
recipient_list=Config.get_param("EMAIL_JOBS"),
fail_silently=True, fail_silently=True,
html_message=html,
) )
print(rst) print(rst)

26
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',),
},
),
]

42
sigi/apps/utils/models.py

@ -9,7 +9,6 @@ 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 sigi.apps.utils.management.jobs import JobReportMixin
class SigiAlert(models.Model): class SigiAlert(models.Model):
@ -182,3 +181,44 @@ class JobSchedule(models.Model):
self.status = JobSchedule.STATUS_CONCLUIDO self.status = JobSchedule.STATUS_CONCLUIDO
self.tempo_gasto = timezone.localtime() - self.iniciado self.tempo_gasto = timezone.localtime() - self.iniciado
self.save() 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

3
sigi/menu_conf.yaml

@ -23,7 +23,8 @@ admin_menu:
- title: Jobs agendados - title: Jobs agendados
view_name: admin:utils_jobschedule_changelist view_name: admin:utils_jobschedule_changelist
querystr: status__exact=A querystr: status__exact=A
- title: Configurações
view_name: admin:utils_config_changelist
main_menu: main_menu:
- title: Municípios - title: Municípios
icon: location_city icon: location_city

Loading…
Cancel
Save