diff --git a/sigi/apps/casas/admin.py b/sigi/apps/casas/admin.py
index d8aefe2..7c7f95d 100644
--- a/sigi/apps/casas/admin.py
+++ b/sigi/apps/casas/admin.py
@@ -7,8 +7,12 @@ from django_weasyprint.views import WeasyTemplateResponse
from import_export.fields import Field
from sigi.apps.casas.forms import OrgaoForm
from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao
-from sigi.apps.casas.filters import (GerentesInterlegisFilter, ConvenioFilter,
- ExcluirConvenioFilter, ServicoFilter)
+from sigi.apps.casas.filters import (
+ GerentesInterlegisFilter,
+ ConvenioFilter,
+ ExcluirConvenioFilter,
+ ServicoFilter,
+)
from sigi.apps.contatos.models import Telefone
from sigi.apps.convenios.models import Convenio
from sigi.apps.ocorrencias.models import Ocorrencia
@@ -19,16 +23,30 @@ from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse
class OrgaoExportResourse(LabeledResourse):
- presidente = Field(column_name='presidente')
- telefone = Field(column_name='telefone')
+ presidente = Field(column_name="presidente")
+ telefone = Field(column_name="telefone")
# servicos_seit = Field(column_name='servicos_seit')
- contato = Field(column_name='contato')
+ contato = Field(column_name="contato")
+
class Meta:
model = Orgao
- fields = ('municipio__codigo_ibge', 'cnpj', 'municipio__codigo_tse',
- 'nome', 'municipio__nome', 'municipio__uf__sigla',
- 'presidente', 'logradouro', 'bairro', 'cep', 'telefone',
- 'pagina_web', 'email', 'ult_alt_endereco', 'contato')
+ fields = (
+ "municipio__codigo_ibge",
+ "cnpj",
+ "municipio__codigo_tse",
+ "nome",
+ "municipio__nome",
+ "municipio__uf__sigla",
+ "presidente",
+ "logradouro",
+ "bairro",
+ "cep",
+ "telefone",
+ "pagina_web",
+ "email",
+ "ult_alt_endereco",
+ "contato",
+ )
export_order = fields
def dehydrate_presidente(self, orgao):
@@ -44,105 +62,189 @@ class OrgaoExportResourse(LabeledResourse):
def dehydrate_contato(self, orgao):
return ", ".join(
- [f"{c.cargo if c.cargo else 'Sem cargo'}: {c.nome} ({c.email})"
- for c in orgao.funcionario_set.filter(desativado=False)
+ [
+ f"{c.cargo if c.cargo else 'Sem cargo'}: {c.nome} ({c.email})"
+ for c in orgao.funcionario_set.filter(desativado=False)
]
)
+
class TelefonesInline(GenericTabularInline):
model = Telefone
- readonly_fields = ('ult_alteracao',)
+ readonly_fields = ("ult_alteracao",)
extra = 1
+
class PresidenteInline(admin.StackedInline):
model = Presidente
- fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email',
- 'tempo_de_servico', 'ult_alteracao', 'endereco', 'municipio',
- 'bairro', 'cep', 'redes_sociais',)
- raw_id_fields = ('municipio',)
- readonly_fields = ('ult_alteracao',)
+ fields = (
+ "nome",
+ "sexo",
+ "data_nascimento",
+ "nota",
+ "email",
+ "tempo_de_servico",
+ "ult_alteracao",
+ "endereco",
+ "municipio",
+ "bairro",
+ "cep",
+ "redes_sociais",
+ )
+ raw_id_fields = ("municipio",)
+ readonly_fields = ("ult_alteracao",)
extra = 1
max_num = 1
- verbose_name_plural = _('Presidente')
+ verbose_name_plural = _("Presidente")
+
def get_queryset(self, request):
- return (self.model.objects.exclude(desativado=True)
- .extra(select={'ult_null': 'ult_alteracao is null'})
- .order_by('ult_null', '-ult_alteracao')
+ return (
+ self.model.objects.exclude(desativado=True)
+ .extra(select={"ult_null": "ult_alteracao is null"})
+ .order_by("ult_null", "-ult_alteracao")
# A função extra foi usada para quando existir um registro com o
# campo igual a null não aparecer na frente dos mais novos
)
+
class ContatoInterlegisInline(admin.StackedInline):
model = Funcionario
- fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email', 'cargo',
- 'funcao', 'setor', 'tempo_de_servico', 'ult_alteracao',
- 'endereco', 'municipio', 'bairro', 'cep', 'redes_sociais',
- 'desativado', 'observacoes')
- raw_id_fields = ('municipio',)
- readonly_fields = ('ult_alteracao',)
+ fields = (
+ "nome",
+ "sexo",
+ "data_nascimento",
+ "nota",
+ "email",
+ "cargo",
+ "funcao",
+ "setor",
+ "tempo_de_servico",
+ "ult_alteracao",
+ "endereco",
+ "municipio",
+ "bairro",
+ "cep",
+ "redes_sociais",
+ "desativado",
+ "observacoes",
+ )
+ raw_id_fields = ("municipio",)
+ readonly_fields = ("ult_alteracao",)
extra = 1
inlines = (TelefonesInline,)
- verbose_name_plural = _('Contato(s) Interlegis Vigente(s)')
+ verbose_name_plural = _("Contato(s) Interlegis Vigente(s)")
+
def get_queryset(self, request):
- return (self.model.objects.filter(setor='contato_interlegis')
- .extra(select={'ult_null': 'ult_alteracao is null'}).order_by(
- '-ult_alteracao')
+ return (
+ self.model.objects.filter(setor="contato_interlegis")
+ .extra(select={"ult_null": "ult_alteracao is null"})
+ .order_by("-ult_alteracao")
)
- def get_extra(self, request, obj=None , **kwargs):
+
+ def get_extra(self, request, obj=None, **kwargs):
extra = 0
return extra
+
class FuncionariosInline(admin.StackedInline):
model = Funcionario
- fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email', 'cargo',
- 'funcao', 'setor', 'tempo_de_servico', 'ult_alteracao',
- 'endereco', 'municipio', 'bairro', 'cep', 'redes_sociais',
- 'desativado', 'observacoes')
- raw_id_fields = ('municipio',)
- readonly_fields = ('ult_alteracao',)
+ fields = (
+ "nome",
+ "sexo",
+ "data_nascimento",
+ "nota",
+ "email",
+ "cargo",
+ "funcao",
+ "setor",
+ "tempo_de_servico",
+ "ult_alteracao",
+ "endereco",
+ "municipio",
+ "bairro",
+ "cep",
+ "redes_sociais",
+ "desativado",
+ "observacoes",
+ )
+ raw_id_fields = ("municipio",)
+ readonly_fields = ("ult_alteracao",)
extra = 1
inlines = (TelefonesInline,)
- verbose_name_plural = _('Outros Contatos da Casa')
+ verbose_name_plural = _("Outros Contatos da Casa")
def get_queryset(self, request):
- return (self.model.objects.exclude(cargo='Presidente',)
- .exclude(desativado=True).extra(
- select={'ult_null': 'ult_alteracao is null'})
- .order_by('ult_null', '-ult_alteracao')
+ return (
+ self.model.objects.exclude(
+ cargo="Presidente",
+ )
+ .exclude(desativado=True)
+ .extra(select={"ult_null": "ult_alteracao is null"})
+ .order_by("ult_null", "-ult_alteracao")
# A função extra foi usada para quando existir um registro com
# o campo igual a null não aparecer na frente dos mais novos
)
+
class ConveniosInline(admin.TabularInline):
model = Convenio
fieldsets = (
- (None, {'fields': (
- ('link_sigad', 'status_convenio', 'num_convenio',
- 'projeto', 'observacao'),
- ('data_retorno_assinatura', 'data_pub_diario',),
- ('get_anexos',),
- ('link_convenio',),
- )}),
+ (
+ None,
+ {
+ "fields": (
+ (
+ "link_sigad",
+ "status_convenio",
+ "num_convenio",
+ "projeto",
+ "observacao",
+ ),
+ (
+ "data_retorno_assinatura",
+ "data_pub_diario",
+ ),
+ ("get_anexos",),
+ ("link_convenio",),
+ )
+ },
+ ),
)
- readonly_fields = ['link_convenio', 'link_sigad', 'status_convenio',
- 'num_convenio', 'projeto', 'observacao', 'data_adesao',
- 'data_retorno_assinatura', 'data_termo_aceite',
- 'data_pub_diario', 'data_devolucao_via',
- 'data_postagem_correio', 'data_devolucao_sem_assinatura',
- 'data_retorno_sem_assinatura', 'get_anexos']
+ readonly_fields = [
+ "link_convenio",
+ "link_sigad",
+ "status_convenio",
+ "num_convenio",
+ "projeto",
+ "observacao",
+ "data_adesao",
+ "data_retorno_assinatura",
+ "data_termo_aceite",
+ "data_pub_diario",
+ "data_devolucao_via",
+ "data_postagem_correio",
+ "data_devolucao_sem_assinatura",
+ "data_retorno_sem_assinatura",
+ "get_anexos",
+ ]
extra = 0
can_delete = False
- ordering = ('-data_retorno_assinatura',)
+ ordering = ("-data_retorno_assinatura",)
def has_add_permission(self, request, obj):
return False
def get_anexos(self, obj):
- return mark_safe(' '.join(
- [f'{a} '
- for a in obj.anexo_set.all()])
+ return mark_safe(
+ " ".join(
+ [
+ f'{a} '
+ for a in obj.anexo_set.all()
+ ]
+ )
)
- get_anexos.short_description = _('Anexos')
+
+ get_anexos.short_description = _("Anexos")
def status_convenio(self, obj):
if obj.pk is None:
@@ -159,37 +261,56 @@ class ConveniosInline(admin.TabularInline):
label = r"info"
return mark_safe(f'
{status}
')
+
status_convenio.short_description = _("Status do convênio")
def link_convenio(self, obj):
if obj.pk is None:
return ""
opts = self.opts
- url = reverse(f"admin:{opts.app_label}_{opts.model_name}_change",
- args=[obj.pk])
+ url = reverse(
+ f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
+ )
return mark_safe(
f'edit '
)
- link_convenio.short_description = _('Editar convenio')
+
+ link_convenio.short_description = _("Editar convenio")
def link_sigad(self, obj):
if obj.pk is None:
return ""
return mark_safe(obj.get_sigad_url())
+
link_sigad.short_description = _("Processo no Senado")
+
class ServicoInline(admin.TabularInline):
model = Servico
- fields = ('link_url', 'contato_tecnico', 'contato_administrativo',
- 'hospedagem_interlegis', 'data_ativacao', 'data_alteracao',
- 'data_desativacao', 'link_servico')
- readonly_fields = ['link_url', 'contato_tecnico', 'contato_administrativo',
- 'hospedagem_interlegis', 'data_ativacao',
- 'data_alteracao', 'data_desativacao', 'link_servico']
+ fields = (
+ "link_url",
+ "contato_tecnico",
+ "contato_administrativo",
+ "hospedagem_interlegis",
+ "data_ativacao",
+ "data_alteracao",
+ "data_desativacao",
+ "link_servico",
+ )
+ readonly_fields = [
+ "link_url",
+ "contato_tecnico",
+ "contato_administrativo",
+ "hospedagem_interlegis",
+ "data_ativacao",
+ "data_alteracao",
+ "data_desativacao",
+ "link_servico",
+ ]
extra = 0
max_num = 0
can_delete = False
- ordering = ('-data_alteracao',)
+ ordering = ("-data_alteracao",)
def link_url(self, servico):
if servico.data_desativacao is not None:
@@ -197,179 +318,286 @@ class ServicoInline(admin.TabularInline):
return mark_safe(
f'{servico.url} '
)
- link_url.short_description = _('URL do serviço')
+
+ link_url.short_description = _("URL do serviço")
def link_servico(self, obj):
if obj.pk is None:
return ""
opts = self.opts
- url = reverse(f'admin:{opts.app_label}_{opts.model_name}_change',
- args=[obj.pk])
+ url = reverse(
+ f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
+ )
return mark_safe(
f'edit '
)
- link_servico.short_description = _('Editar Serviço')
+
+ link_servico.short_description = _("Editar Serviço")
def has_add_permission(self, request, obj):
return False
+
class OcorrenciaInline(admin.TabularInline):
model = Ocorrencia
- fields = ('data_criacao', 'assunto', 'prioridade', 'status',
- 'data_modificacao', 'link_editar',)
- readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status',
- 'data_modificacao', 'link_editar',)
+ fields = (
+ "data_criacao",
+ "assunto",
+ "prioridade",
+ "status",
+ "data_modificacao",
+ "link_editar",
+ )
+ readonly_fields = (
+ "data_criacao",
+ "assunto",
+ "prioridade",
+ "status",
+ "data_modificacao",
+ "link_editar",
+ )
extra = 0
max_num = 0
can_delete = False
- ordering = ('-data_modificacao',)
+ ordering = ("-data_modificacao",)
def link_editar(self, obj):
if obj.pk is None:
return ""
opts = self.opts
url = reverse(
- f'admin:{opts.app_label}_{opts.model_name}_change',
- args=[obj.pk]
+ f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
)
return mark_safe(
f'edit '
)
- link_editar.short_description = _('Editar')
+
+ link_editar.short_description = _("Editar")
@admin.register(Orgao)
class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
form = OrgaoForm
resource_class = OrgaoExportResourse
- inlines = (TelefonesInline, PresidenteInline, ContatoInterlegisInline,
- FuncionariosInline, ConveniosInline, ServicoInline,
- OcorrenciaInline,)
- list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes',
- 'get_convenios', 'get_servicos')
- list_display_links = ('sigla', 'nome',)
- list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter),
- 'municipio__uf__nome', ConvenioFilter,
- ('servico__data_desativacao', ServicoAtivoFilter),
- ExcluirConvenioFilter, ServicoFilter,
- 'inclusao_digital',)
- ordering = ('municipio__uf__nome', 'nome')
+ inlines = (
+ TelefonesInline,
+ PresidenteInline,
+ ContatoInterlegisInline,
+ FuncionariosInline,
+ ConveniosInline,
+ ServicoInline,
+ OcorrenciaInline,
+ )
+ list_display = (
+ "id",
+ "sigla",
+ "nome",
+ "get_uf",
+ "get_gerentes",
+ "get_convenios",
+ "get_servicos",
+ )
+ list_display_links = (
+ "sigla",
+ "nome",
+ )
+ list_filter = (
+ "tipo",
+ ("gerentes_interlegis", GerentesInterlegisFilter),
+ "municipio__uf__nome",
+ ConvenioFilter,
+ ("servico__data_desativacao", ServicoAtivoFilter),
+ ExcluirConvenioFilter,
+ ServicoFilter,
+ "inclusao_digital",
+ )
+ ordering = ("municipio__uf__nome", "nome")
queryset = queryset_ascii
fieldsets = (
- (None, {
- 'fields': ('tipo', 'nome', 'sigla', 'cnpj', 'gerentes_interlegis')
- }),
- (_('Endereço'), {
- 'fields': ('data_instalacao', 'logradouro', 'bairro',
- 'municipio', 'cep', 'ult_alt_endereco'),
- }),
- (_('Presença na Internet'), {
- 'fields': ('inclusao_digital', 'data_levantamento', 'pesquisador',
- 'pagina_web', 'email', 'obs_pesquisa',)
- }),
- (_('Outras informações'), {
- 'fields': ('observacoes', 'horario_funcionamento', 'foto',),
- }),
+ (
+ None,
+ {
+ "fields": (
+ "tipo",
+ "nome",
+ "sigla",
+ "cnpj",
+ "gerentes_interlegis",
+ )
+ },
+ ),
+ (
+ _("Endereço"),
+ {
+ "fields": (
+ "data_instalacao",
+ "logradouro",
+ "bairro",
+ "municipio",
+ "cep",
+ "ult_alt_endereco",
+ ),
+ },
+ ),
+ (
+ _("Presença na Internet"),
+ {
+ "fields": (
+ "inclusao_digital",
+ "data_levantamento",
+ "pesquisador",
+ "pagina_web",
+ "email",
+ "obs_pesquisa",
+ )
+ },
+ ),
+ (
+ _("Outras informações"),
+ {
+ "fields": (
+ "observacoes",
+ "horario_funcionamento",
+ "foto",
+ ),
+ },
+ ),
+ )
+ raw_id_fields = ("municipio",)
+ readonly_fields = [
+ "gerentes_interlegis",
+ ]
+ search_fields = (
+ "search_text",
+ "sigla",
+ "cnpj",
+ "bairro",
+ "logradouro",
+ "cep",
+ "municipio__nome",
+ "municipio__uf__nome",
+ "municipio__codigo_ibge",
+ "pagina_web",
+ "observacoes",
)
- raw_id_fields = ('municipio',)
- readonly_fields = ['gerentes_interlegis',]
- search_fields = ('search_text', 'sigla', 'cnpj', 'bairro', 'logradouro',
- 'cep', 'municipio__nome', 'municipio__uf__nome',
- 'municipio__codigo_ibge', 'pagina_web', 'observacoes')
- reports = ['casas_sem_processo', 'relatorio_simples', 'relatorio_completo',
- 'etiqueta_presidente_25', 'etiqueta_presidente_39',
- 'etiqueta_25', 'etiqueta_39', 'etiqueta_parlamentar_25',
- 'etiqueta_parlamentar_39',]
+ reports = [
+ "casas_sem_processo",
+ "relatorio_simples",
+ "relatorio_completo",
+ "etiqueta_presidente_25",
+ "etiqueta_presidente_39",
+ "etiqueta_25",
+ "etiqueta_39",
+ "etiqueta_parlamentar_25",
+ "etiqueta_parlamentar_39",
+ ]
def get_queryset(self, request):
queryset = super(OrgaoAdmin, self).get_queryset(request)
- return queryset.prefetch_related('gerentes_interlegis', 'convenio_set')
+ return queryset.prefetch_related("gerentes_interlegis", "convenio_set")
def get_uf(self, obj):
return obj.municipio.uf.nome
- get_uf.short_description = _('Unidade da Federação')
- get_uf.admin_order_field = 'municipio__uf__nome'
+
+ get_uf.short_description = _("Unidade da Federação")
+ get_uf.admin_order_field = "municipio__uf__nome"
def get_gerentes(self, obj):
return mark_safe(obj.lista_gerentes())
- get_gerentes.short_description = _('Gerente Interlegis')
+
+ get_gerentes.short_description = _("Gerente Interlegis")
def get_convenios(self, obj):
return mark_safe(
- '' +
- ''.join([f'{c} ' for c in obj.convenio_set.all()]) +
- ' '
+ ""
+ + "".join([f"{c} " for c in obj.convenio_set.all()])
+ + " "
)
- get_convenios.short_description = _('Convênios')
+
+ get_convenios.short_description = _("Convênios")
def get_servicos(self, obj):
return mark_safe(
- '' +
- ''.join(
- [f'{s} '
- for s in obj.servico_set.filter(
- data_desativacao__isnull=True)
+ ""
+ + "".join(
+ [
+ f'{s} '
+ for s in obj.servico_set.filter(
+ data_desativacao__isnull=True
+ )
]
- ) +
- ' '
+ )
+ + " "
)
- get_servicos.short_description = _('Serviços')
+
+ get_servicos.short_description = _("Serviços")
def lookup_allowed(self, lookup, value):
- return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or
- lookup in ['tipo__legislativo__exact',
- 'tipo__sigla__exact',
- 'municipio__uf__codigo_ibge__exact',
- 'convenio__projeto__id__exact'])
+ return super(OrgaoAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in [
+ "tipo__legislativo__exact",
+ "tipo__sigla__exact",
+ "municipio__uf__codigo_ibge__exact",
+ "convenio__projeto__id__exact",
+ ]
def casas_sem_processo(self, request):
context = {
- 'casas': self.get_queryset(request).filter(convenio=None).order_by(
- 'municipio__uf','nome'),
- 'title': _('Casas sem nenhum processo de convênio')
+ "casas": self.get_queryset(request)
+ .filter(convenio=None)
+ .order_by("municipio__uf", "nome"),
+ "title": _("Casas sem nenhum processo de convênio"),
}
return WeasyTemplateResponse(
- filename='casas_sem_processo.pdf',
+ filename="casas_sem_processo.pdf",
request=request,
template="casas/casas_sem_convenio_pdf.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- casas_sem_processo.title = _('Casas sem nenhum processo de convênio')
+
+ casas_sem_processo.title = _("Casas sem nenhum processo de convênio")
def relatorio_simples(self, request):
context = {
- 'casas': self.get_queryset(request).order_by(
- 'municipio__uf','nome'),
- 'title': _('Relatório Simples')
+ "casas": self.get_queryset(request).order_by(
+ "municipio__uf", "nome"
+ ),
+ "title": _("Relatório Simples"),
}
return WeasyTemplateResponse(
- filename='relatorio_simples.pdf',
+ filename="relatorio_simples.pdf",
request=request,
template="casas/casas_sem_convenio_pdf.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- relatorio_simples.title = _('Relatório Simples')
+
+ relatorio_simples.title = _("Relatório Simples")
def relatorio_completo(self, request):
context = {
- 'casas': self.get_queryset(request).order_by('municipio__uf','nome'),
- 'title': _('Relatório completo')
+ "casas": self.get_queryset(request).order_by(
+ "municipio__uf", "nome"
+ ),
+ "title": _("Relatório completo"),
}
return WeasyTemplateResponse(
- filename='relatorio_completo.pdf',
+ filename="relatorio_completo.pdf",
request=request,
template="casas/relatorio_completo_pdf.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- relatorio_completo.title = _('Relatório completo')
+
+ relatorio_completo.title = _("Relatório completo")
def get_actions(self, request):
actions = super(OrgaoAdmin, self).get_actions(request)
- if 'delete_selected' in actions:
- del actions['delete_selected']
+ if "delete_selected" in actions:
+ del actions["delete_selected"]
return actions
-admin.site.register(TipoOrgao)
\ No newline at end of file
+
+admin.site.register(TipoOrgao)
diff --git a/sigi/apps/casas/apps.py b/sigi/apps/casas/apps.py
index 78c131f..1e2b44b 100644
--- a/sigi/apps/casas/apps.py
+++ b/sigi/apps/casas/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class CasasConfig(AppConfig):
- name = 'sigi.apps.casas'
- verbose_name = _('casas legislativas')
+ name = "sigi.apps.casas"
+ verbose_name = _("casas legislativas")
diff --git a/sigi/apps/casas/filters.py b/sigi/apps/casas/filters.py
index 89f5264..0e96be8 100644
--- a/sigi/apps/casas/filters.py
+++ b/sigi/apps/casas/filters.py
@@ -8,78 +8,83 @@ from sigi.apps.servicos.models import TipoServico
class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- gerentes = Servidor.objects.exclude(
- casas_que_gerencia=None).order_by(
- 'nome_completo')
+ gerentes = Servidor.objects.exclude(casas_que_gerencia=None).order_by(
+ "nome_completo"
+ )
self.lookup_choices = [(x.id, x) for x in gerentes]
+
class ConvenioFilter(admin.SimpleListFilter):
title = _("Tipo de convênio")
- parameter_name = 'convenio'
+ parameter_name = "convenio"
def lookups(self, request, model_admin):
return (
- ('SC', _("Sem nenhum convênio")),
- ('CC', _("Com algum convênio")),
+ ("SC", _("Sem nenhum convênio")),
+ ("CC", _("Com algum convênio")),
) + tuple([(p.pk, p.sigla) for p in Projeto.objects.all()])
def queryset(self, request, queryset):
if self.value() is not None:
- if self.value() == 'SC':
+ if self.value() == "SC":
queryset = queryset.filter(convenio=None)
- elif self.value() == 'CC':
+ elif self.value() == "CC":
queryset = queryset.exclude(convenio=None)
else:
queryset = queryset.filter(convenio__projeto_id=self.value())
- return queryset.distinct('municipio__uf__nome', 'nome')
+ return queryset.distinct("municipio__uf__nome", "nome")
+
class ExcluirConvenioFilter(admin.SimpleListFilter):
- title=_("Excluir convênio da pesquisa")
- parameter_name = 'excluir_convenio'
+ title = _("Excluir convênio da pesquisa")
+ parameter_name = "excluir_convenio"
def lookups(self, request, model_admin):
return tuple([(p.pk, p.sigla) for p in Projeto.objects.all()])
def queryset(self, request, queryset):
- if (self.value() is None):
+ if self.value() is None:
return queryset
else:
queryset = queryset.exclude(
- convenio__projeto_id=self.value()).distinct(
- 'municipio__uf__nome', 'nome')
+ convenio__projeto_id=self.value()
+ ).distinct("municipio__uf__nome", "nome")
return queryset
+
class ServicoFilter(admin.SimpleListFilter):
title = _("Serviço")
- parameter_name = 'servico'
+ parameter_name = "servico"
def lookups(self, request, model_admin):
return (
- ('SS', _("Sem nenhum serviço")),
- ('CS', _("Com algum serviço")),
- ('CH', _("Com algum serviço de hospedagem")),
- ('CR', _("Apenas serviço de registro")),
+ ("SS", _("Sem nenhum serviço")),
+ ("CS", _("Com algum serviço")),
+ ("CH", _("Com algum serviço de hospedagem")),
+ ("CR", _("Apenas serviço de registro")),
) + tuple([(p.pk, p.nome) for p in TipoServico.objects.all()])
def queryset(self, request, queryset):
if self.value() is not None:
- if self.value() == 'SS':
+ if self.value() == "SS":
queryset = queryset.filter(servico=None)
- elif self.value() == 'CS':
+ elif self.value() == "CS":
queryset = queryset.exclude(servico=None).filter(
- servico__data_desativacao__isnull=True)
- elif self.value() == 'CR':
- queryset = queryset.exclude(servico__tipo_servico__modo='H') \
- .exclude(servico=None)
- elif self.value() == 'CH':
- queryset = queryset.filter(
- servico__tipo_servico__modo='H',
servico__data_desativacao__isnull=True
)
+ elif self.value() == "CR":
+ queryset = queryset.exclude(
+ servico__tipo_servico__modo="H"
+ ).exclude(servico=None)
+ elif self.value() == "CH":
+ queryset = queryset.filter(
+ servico__tipo_servico__modo="H",
+ servico__data_desativacao__isnull=True,
+ )
else:
queryset = queryset.filter(
servico__tipo_servico_id=self.value()
)
- return queryset.distinct('municipio__uf__nome', 'nome')
+ return queryset.distinct("municipio__uf__nome", "nome")
diff --git a/sigi/apps/casas/forms.py b/sigi/apps/casas/forms.py
index d2c1ce0..f5e24fc 100644
--- a/sigi/apps/casas/forms.py
+++ b/sigi/apps/casas/forms.py
@@ -5,6 +5,7 @@ from localflavor.br.forms import BRZipCodeField
from sigi.apps.casas.models import Orgao
from sigi.apps.servidores.models import Servidor
+
class AtualizaCasaForm(forms.Form):
arquivo = forms.FileField(
required=True,
@@ -12,17 +13,20 @@ class AtualizaCasaForm(forms.Form):
help_text=_("Envie um arquivo no formato CSV"),
)
+
class OrgaoForm(forms.ModelForm):
# cnpj = BRCNPJField(
# label=_('CNPJ'),
# required=False,
# help_text=_('Utilize o formato XX.XXX.XXX/XXXX-XX ou insira apenas os dígitos.')
- #)
- cep = BRZipCodeField(label=_('CEP'), help_text=_('Formato') + ': XXXXX-XXX .')
+ # )
+ cep = BRZipCodeField(
+ label=_("CEP"), help_text=_("Formato") + ": XXXXX-XXX ."
+ )
class Meta:
model = Orgao
- fields = '__all__'
+ fields = "__all__"
# def clean(self):
# cleaned_data = super(OrgaoForm, self).clean()
@@ -31,23 +35,20 @@ class OrgaoForm(forms.ModelForm):
# if tipo.legislativo:
# if Orgao.objects.filter(tipo=tipo)
+
class PortfolioForm(forms.Form):
- ACAO_CHOICES = (
- ('ADD', _("Adicionar")),
- ('DEL', _("Remover"))
- )
+ ACAO_CHOICES = (("ADD", _("Adicionar")), ("DEL", _("Remover")))
acao = forms.ChoiceField(
label=_("Ação"),
choices=ACAO_CHOICES,
- initial='ADD',
- widget=forms.RadioSelect
+ initial="ADD",
+ widget=forms.RadioSelect,
)
gerente = forms.ModelChoiceField(
- queryset=Servidor.objects.all(),
- label=_("Atribuir para")
+ queryset=Servidor.objects.all(), label=_("Atribuir para")
)
# O label precisa ser trocado dependendo da região que se está visualizando
def __init__(self, label=_("Atribuir para"), *args, **kwargs):
super(PortfolioForm, self).__init__(*args, **kwargs)
- self.fields['gerente'].label = label
+ self.fields["gerente"].label = label
diff --git a/sigi/apps/casas/management/commands/importa_gerentes.py b/sigi/apps/casas/management/commands/importa_gerentes.py
index 3f55647..335ab6e 100644
--- a/sigi/apps/casas/management/commands/importa_gerentes.py
+++ b/sigi/apps/casas/management/commands/importa_gerentes.py
@@ -29,6 +29,7 @@ from sigi.apps.casas.models import Orgao
from sigi.apps.servidores.models import Servidor
from sigi.apps.contatos.models import Municipio
+
class Command(BaseCommand):
args = "data_file.csv"
help = """Importa dados de atribuição de gerencia de relacionamentos de um arquivo CSV.
@@ -39,7 +40,7 @@ class Command(BaseCommand):
* Os nomes dos campos devem ser grafados exatamente como descrito."""
- campos = {'cod_municipio', 'user_id'}
+ campos = {"cod_municipio", "user_id"}
def handle(self, *args, **options):
if len(args) != 1:
@@ -48,13 +49,20 @@ class Command(BaseCommand):
file_name = args[0]
if not os.path.isfile(file_name):
- raise CommandError("Arquivo %s não encontrado" % [file_name,])
-
- with open(file_name, 'rb') as csvfile:
+ raise CommandError(
+ "Arquivo %s não encontrado"
+ % [
+ file_name,
+ ]
+ )
+
+ with open(file_name, "rb") as csvfile:
reader = csv.DictReader(csvfile)
if not self.campos.issubset(reader.fieldnames):
- raise CommandError("O arquivo não possui todos os campos obrigatórios")
+ raise CommandError(
+ "O arquivo não possui todos os campos obrigatórios"
+ )
Orgao.gerentes_interlegis.through.objects.all().delete()
@@ -63,36 +71,39 @@ class Command(BaseCommand):
for reg in reader:
try:
municipio = Municipio.objects.get(
- codigo_ibge=reg['cod_municipio']
+ codigo_ibge=reg["cod_municipio"]
)
except Municipio.DoesNotExist:
- self.stdout.write("{linha}: não existe Município com "
- "código IBGE {ibge}'".format(
- linha=reader.line_num,
- ibge=reg['cod_municipio'])
+ self.stdout.write(
+ "{linha}: não existe Município com "
+ "código IBGE {ibge}'".format(
+ linha=reader.line_num, ibge=reg["cod_municipio"]
+ )
)
erros = erros + 1
continue
try:
gerente = Servidor.objects.get(
- user__username=reg['user_id']
+ user__username=reg["user_id"]
)
except Servidor.DoesNotExist:
- self.stdout.write("({linha}): não existe Servidor com "
- "userid {userid}".format(
- linha=reader.line_num,
- userid=reg['user_id'])
+ self.stdout.write(
+ "({linha}): não existe Servidor com "
+ "userid {userid}".format(
+ linha=reader.line_num, userid=reg["user_id"]
+ )
)
erros = erros + 1
continue
for casa in municipio.orgao_set.filter(
- tipo__sigla__in=['AL', 'CM']):
+ tipo__sigla__in=["AL", "CM"]
+ ):
casa.gerentes_interlegis.add(gerente)
casa.save()
- self.stdout.write("Importação concluída. {erros} erros em {linhas}"
- " linhas".format(erros=erros,
- linhas=reader.line_num)
- )
\ No newline at end of file
+ self.stdout.write(
+ "Importação concluída. {erros} erros em {linhas}"
+ " linhas".format(erros=erros, linhas=reader.line_num)
+ )
diff --git a/sigi/apps/casas/migrations/0001_initial.py b/sigi/apps/casas/migrations/0001_initial.py
index 5adb0d9..11ee4e6 100644
--- a/sigi/apps/casas/migrations/0001_initial.py
+++ b/sigi/apps/casas/migrations/0001_initial.py
@@ -7,91 +7,291 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('contatos', '0001_initial'),
+ ("servidores", "0001_initial"),
+ ("contatos", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='CasaLegislativa',
+ name="CasaLegislativa",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(help_text='Exemplo: C\xc3\xa2mara Municipal de Pains .', max_length=60)),
- ('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)),
- ('cnpj', models.CharField(max_length=32, verbose_name='CNPJ', blank=True)),
- ('observacoes', models.TextField(verbose_name='observa\xe7\xf5es', blank=True)),
- ('codigo_interlegis', models.CharField(max_length=3, verbose_name='C\xc3\xb3digo Interlegis', blank=True)),
- ('logradouro', models.CharField(help_text='Avenida, rua, pra\xc3\xa7a, jardim, parque...', max_length=100)),
- ('bairro', models.CharField(max_length=100, blank=True)),
- ('cep', models.CharField(max_length=32)),
- ('email', models.EmailField(max_length=128, verbose_name='e-mail', blank=True)),
- ('pagina_web', models.URLField(help_text=b'Exemplo: http://www.camarapains.mg.gov.br .', verbose_name='p\xe1gina web', blank=True)),
- ('ult_alt_endereco', models.DateTimeField(null=True, verbose_name='\xdaltima altera\xe7\xe3o do endere\xe7o', blank=True)),
- ('foto', models.ImageField(height_field='foto_altura', width_field='foto_largura', upload_to='imagens/casas', blank=True)),
- ('recorte', models.CharField('foto', max_length=255)),
- ('foto_largura', models.SmallIntegerField(null=True, editable=False)),
- ('foto_altura', models.SmallIntegerField(null=True, editable=False)),
- ('data_instalacao', models.DateField(null=True, verbose_name='Data de instala\xe7\xe3o da Casa Legislativa', blank=True)),
- ('gerente_contas', models.ForeignKey(verbose_name='Gerente de contas', blank=True, to='servidores.Servidor', null=True, on_delete=models.CASCADE)),
- ('municipio', models.ForeignKey(verbose_name='munic\xc3\xadpio', to='contatos.Municipio', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ help_text="Exemplo: C\xc3\xa2mara Municipal de Pains .",
+ max_length=60,
+ ),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["nome"], editable=False
+ ),
+ ),
+ (
+ "cnpj",
+ models.CharField(
+ max_length=32, verbose_name="CNPJ", blank=True
+ ),
+ ),
+ (
+ "observacoes",
+ models.TextField(
+ verbose_name="observa\xe7\xf5es", blank=True
+ ),
+ ),
+ (
+ "codigo_interlegis",
+ models.CharField(
+ max_length=3,
+ verbose_name="C\xc3\xb3digo Interlegis",
+ blank=True,
+ ),
+ ),
+ (
+ "logradouro",
+ models.CharField(
+ help_text="Avenida, rua, pra\xc3\xa7a, jardim, parque...",
+ max_length=100,
+ ),
+ ),
+ ("bairro", models.CharField(max_length=100, blank=True)),
+ ("cep", models.CharField(max_length=32)),
+ (
+ "email",
+ models.EmailField(
+ max_length=128, verbose_name="e-mail", blank=True
+ ),
+ ),
+ (
+ "pagina_web",
+ models.URLField(
+ help_text=b"Exemplo: http://www.camarapains.mg.gov.br .",
+ verbose_name="p\xe1gina web",
+ blank=True,
+ ),
+ ),
+ (
+ "ult_alt_endereco",
+ models.DateTimeField(
+ null=True,
+ verbose_name="\xdaltima altera\xe7\xe3o do endere\xe7o",
+ blank=True,
+ ),
+ ),
+ (
+ "foto",
+ models.ImageField(
+ height_field="foto_altura",
+ width_field="foto_largura",
+ upload_to="imagens/casas",
+ blank=True,
+ ),
+ ),
+ ("recorte", models.CharField("foto", max_length=255)),
+ (
+ "foto_largura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "foto_altura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "data_instalacao",
+ models.DateField(
+ null=True,
+ verbose_name="Data de instala\xe7\xe3o da Casa Legislativa",
+ blank=True,
+ ),
+ ),
+ (
+ "gerente_contas",
+ models.ForeignKey(
+ verbose_name="Gerente de contas",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "municipio",
+ models.ForeignKey(
+ verbose_name="munic\xc3\xadpio",
+ to="contatos.Municipio",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'Casa Legislativa',
- 'verbose_name_plural': 'Casas Legislativas',
+ "ordering": ("nome",),
+ "verbose_name": "Casa Legislativa",
+ "verbose_name_plural": "Casas Legislativas",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Funcionario',
+ name="Funcionario",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=60, verbose_name='nome completo')),
- ('sexo', models.CharField(default='M', max_length=1, choices=[('M', 'Masculino'), ('F', 'Feminino')])),
- ('nota', models.CharField(max_length=70, null=True, blank=True)),
- ('email', models.CharField(max_length=75, verbose_name='e-mail', blank=True)),
- ('cargo', models.CharField(max_length=100, null=True, blank=True)),
- ('funcao', models.CharField(max_length=100, null=True, verbose_name='fun\xe7\xe3o', blank=True)),
- ('setor', models.CharField(default='outros', max_length=100, choices=[('presidente', 'Presidente'), ('contato_interlegis', 'Contato Interlegis'), ('infraestrutura_fisica', 'Infraestrutura F\xc3\xadsica'), ('estrutura_de_ti', 'Estrutura de TI'), ('organizacao_do_processo_legislativo', 'Organiza\xc3\xa7\xc3\xa3o do Processo Legislativo'), ('producao_legislativa', 'Produ\xc3\xa7\xc3\xa3o Legislativa'), ('estrutura_de_comunicacao_social', 'Estrutura de Comunica\xc3\xa7\xc3\xa3o Social'), ('estrutura_de_recursos_humanos', 'Estrutura de Recursos Humanos'), ('gestao', 'Gest\xc3\xa3o'), ('outros', 'Outros')])),
- ('tempo_de_servico', models.CharField(max_length=50, null=True, verbose_name='tempo de servi\xe7o', blank=True)),
- ('ult_alteracao', models.DateTimeField(null=True, verbose_name='\xdaltima altera\xe7\xe3o', blank=True)),
- ('casa_legislativa', models.ForeignKey(to='casas.CasaLegislativa', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=60, verbose_name="nome completo"
+ ),
+ ),
+ (
+ "sexo",
+ models.CharField(
+ default="M",
+ max_length=1,
+ choices=[("M", "Masculino"), ("F", "Feminino")],
+ ),
+ ),
+ (
+ "nota",
+ models.CharField(max_length=70, null=True, blank=True),
+ ),
+ (
+ "email",
+ models.CharField(
+ max_length=75, verbose_name="e-mail", blank=True
+ ),
+ ),
+ (
+ "cargo",
+ models.CharField(max_length=100, null=True, blank=True),
+ ),
+ (
+ "funcao",
+ models.CharField(
+ max_length=100,
+ null=True,
+ verbose_name="fun\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "setor",
+ models.CharField(
+ default="outros",
+ max_length=100,
+ choices=[
+ ("presidente", "Presidente"),
+ ("contato_interlegis", "Contato Interlegis"),
+ (
+ "infraestrutura_fisica",
+ "Infraestrutura F\xc3\xadsica",
+ ),
+ ("estrutura_de_ti", "Estrutura de TI"),
+ (
+ "organizacao_do_processo_legislativo",
+ "Organiza\xc3\xa7\xc3\xa3o do Processo Legislativo",
+ ),
+ (
+ "producao_legislativa",
+ "Produ\xc3\xa7\xc3\xa3o Legislativa",
+ ),
+ (
+ "estrutura_de_comunicacao_social",
+ "Estrutura de Comunica\xc3\xa7\xc3\xa3o Social",
+ ),
+ (
+ "estrutura_de_recursos_humanos",
+ "Estrutura de Recursos Humanos",
+ ),
+ ("gestao", "Gest\xc3\xa3o"),
+ ("outros", "Outros"),
+ ],
+ ),
+ ),
+ (
+ "tempo_de_servico",
+ models.CharField(
+ max_length=50,
+ null=True,
+ verbose_name="tempo de servi\xe7o",
+ blank=True,
+ ),
+ ),
+ (
+ "ult_alteracao",
+ models.DateTimeField(
+ null=True,
+ verbose_name="\xdaltima altera\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ to="casas.CasaLegislativa", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'contato da Casa Legislativa',
- 'verbose_name_plural': 'contatos da Casa Legislativa',
+ "ordering": ("nome",),
+ "verbose_name": "contato da Casa Legislativa",
+ "verbose_name_plural": "contatos da Casa Legislativa",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='TipoCasaLegislativa',
+ name="TipoCasaLegislativa",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('sigla', models.CharField(max_length=5)),
- ('nome', models.CharField(max_length=100)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("sigla", models.CharField(max_length=5)),
+ ("nome", models.CharField(max_length=100)),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.AddField(
- model_name='casalegislativa',
- name='tipo',
- field=models.ForeignKey(verbose_name='Tipo', to='casas.TipoCasaLegislativa', on_delete=models.CASCADE),
+ model_name="casalegislativa",
+ name="tipo",
+ field=models.ForeignKey(
+ verbose_name="Tipo",
+ to="casas.TipoCasaLegislativa",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='casalegislativa',
- unique_together=set([('municipio', 'tipo')]),
+ name="casalegislativa",
+ unique_together=set([("municipio", "tipo")]),
),
migrations.CreateModel(
- name='Presidente',
- fields=[
- ],
+ name="Presidente",
+ fields=[],
options={
- 'proxy': True,
+ "proxy": True,
},
- bases=('casas.funcionario',),
+ bases=("casas.funcionario",),
),
]
diff --git a/sigi/apps/casas/migrations/0002_auto_20150710_1247.py b/sigi/apps/casas/migrations/0002_auto_20150710_1247.py
index faa6adc..06c78a8 100644
--- a/sigi/apps/casas/migrations/0002_auto_20150710_1247.py
+++ b/sigi/apps/casas/migrations/0002_auto_20150710_1247.py
@@ -6,45 +6,75 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('casas', '0001_initial'),
+ ("servidores", "0001_initial"),
+ ("casas", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='casalegislativa',
- name='data_levantamento',
- field=models.DateTimeField(null=True, verbose_name='Data/hora da pesquisa', blank=True),
+ model_name="casalegislativa",
+ name="data_levantamento",
+ field=models.DateTimeField(
+ null=True, verbose_name="Data/hora da pesquisa", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='casalegislativa',
- name='inclusao_digital',
- field=models.CharField(default='NAO PESQUISADO', max_length=30, choices=[('NAO PESQUISADO', 'N\xe3o pesquisado'), ('NAO POSSUI PORTAL', 'N\xe3o possui portal'), ('PORTAL MODELO', 'Possui Portal Modelo'), ('OUTRO PORTAL', 'Possui outro portal')]),
+ model_name="casalegislativa",
+ name="inclusao_digital",
+ field=models.CharField(
+ default="NAO PESQUISADO",
+ max_length=30,
+ choices=[
+ ("NAO PESQUISADO", "N\xe3o pesquisado"),
+ ("NAO POSSUI PORTAL", "N\xe3o possui portal"),
+ ("PORTAL MODELO", "Possui Portal Modelo"),
+ ("OUTRO PORTAL", "Possui outro portal"),
+ ],
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='casalegislativa',
- name='obs_pesquisa',
- field=models.TextField(verbose_name='Observa\xe7\xf5es do pesquisador', blank=True),
+ model_name="casalegislativa",
+ name="obs_pesquisa",
+ field=models.TextField(
+ verbose_name="Observa\xe7\xf5es do pesquisador", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='casalegislativa',
- name='pesquisador',
- field=models.ForeignKey(verbose_name='Pesquisador', blank=True, to='servidores.Servidor', null=True, on_delete=models.CASCADE),
+ model_name="casalegislativa",
+ name="pesquisador",
+ field=models.ForeignKey(
+ verbose_name="Pesquisador",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='gerente_contas',
- field=models.ForeignKey(related_name='casas_que_gerencia', verbose_name='Gerente de contas', blank=True, to='servidores.Servidor', null=True, on_delete=models.CASCADE),
+ model_name="casalegislativa",
+ name="gerente_contas",
+ field=models.ForeignKey(
+ related_name="casas_que_gerencia",
+ verbose_name="Gerente de contas",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='ult_alteracao',
- field=models.DateTimeField(auto_now=True, verbose_name='\xdaltima altera\xe7\xe3o', null=True),
+ model_name="funcionario",
+ name="ult_alteracao",
+ field=models.DateTimeField(
+ auto_now=True,
+ verbose_name="\xdaltima altera\xe7\xe3o",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0003_auto_20200207_0919.py b/sigi/apps/casas/migrations/0003_auto_20200207_0919.py
index 8b57026..a6a2908 100644
--- a/sigi/apps/casas/migrations/0003_auto_20200207_0919.py
+++ b/sigi/apps/casas/migrations/0003_auto_20200207_0919.py
@@ -6,20 +6,26 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0002_auto_20150710_1247'),
+ ("casas", "0002_auto_20150710_1247"),
]
operations = [
migrations.AddField(
- model_name='casalegislativa',
- name='horario_funcionamento',
- field=models.CharField(max_length=100, verbose_name='Hor\xe1rio de funcionamento da Casa Legislativa', blank=True),
+ model_name="casalegislativa",
+ name="horario_funcionamento",
+ field=models.CharField(
+ max_length=100,
+ verbose_name="Hor\xe1rio de funcionamento da Casa Legislativa",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='data_nascimento',
- field=models.DateField(null=True, verbose_name='Data de nascimento', blank=True),
+ model_name="funcionario",
+ name="data_nascimento",
+ field=models.DateField(
+ null=True, verbose_name="Data de nascimento", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0004_auto_20201015_0810.py b/sigi/apps/casas/migrations/0004_auto_20201015_0810.py
index 36dafd6..a4b46f2 100644
--- a/sigi/apps/casas/migrations/0004_auto_20201015_0810.py
+++ b/sigi/apps/casas/migrations/0004_auto_20201015_0810.py
@@ -6,14 +6,21 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0003_auto_20200207_0919'),
+ ("casas", "0003_auto_20200207_0919"),
]
operations = [
migrations.AlterField(
- model_name='casalegislativa',
- name='gerente_contas',
- field=models.ForeignKey(related_name='casas_que_gerencia_old', verbose_name='Gerente de contas', blank=True, to='servidores.Servidor', null=True, on_delete=models.CASCADE),
+ model_name="casalegislativa",
+ name="gerente_contas",
+ field=models.ForeignKey(
+ related_name="casas_que_gerencia_old",
+ verbose_name="Gerente de contas",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py b/sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py
index 3a06049..5abafe8 100644
--- a/sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py
+++ b/sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py
@@ -6,15 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('casas', '0004_auto_20201015_0810'),
+ ("servidores", "0001_initial"),
+ ("casas", "0004_auto_20201015_0810"),
]
operations = [
migrations.AddField(
- model_name='casalegislativa',
- name='gerentes_interlegis',
- field=models.ManyToManyField(related_name='casas_que_gerencia', verbose_name='Gerentes Interlegis', to='servidores.Servidor'),
+ model_name="casalegislativa",
+ name="gerentes_interlegis",
+ field=models.ManyToManyField(
+ related_name="casas_que_gerencia",
+ verbose_name="Gerentes Interlegis",
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py b/sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py
index a9e3e7a..f8da79e 100644
--- a/sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py
+++ b/sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0005_casalegislativa_gerentes_interlegis'),
+ ("casas", "0005_casalegislativa_gerentes_interlegis"),
]
operations = [
migrations.RemoveField(
- model_name='casalegislativa',
- name='gerente_contas',
+ model_name="casalegislativa",
+ name="gerente_contas",
),
]
diff --git a/sigi/apps/casas/migrations/0007_auto_20201016_1632.py b/sigi/apps/casas/migrations/0007_auto_20201016_1632.py
index 5558455..7b3384f 100644
--- a/sigi/apps/casas/migrations/0007_auto_20201016_1632.py
+++ b/sigi/apps/casas/migrations/0007_auto_20201016_1632.py
@@ -6,122 +6,201 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0006_remove_casalegislativa_gerente_contas'),
+ ("casas", "0006_remove_casalegislativa_gerente_contas"),
]
operations = [
migrations.AddField(
- model_name='funcionario',
- name='desativado',
- field=models.BooleanField(default=False, verbose_name='Desativado'),
+ model_name="funcionario",
+ name="desativado",
+ field=models.BooleanField(default=False, verbose_name="Desativado"),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='observacoes',
- field=models.TextField(verbose_name='Observa\xe7\xf5es', blank=True),
+ model_name="funcionario",
+ name="observacoes",
+ field=models.TextField(
+ verbose_name="Observa\xe7\xf5es", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='bairro',
- field=models.CharField(max_length=100, verbose_name='Bairro', blank=True),
+ model_name="casalegislativa",
+ name="bairro",
+ field=models.CharField(
+ max_length=100, verbose_name="Bairro", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='cep',
- field=models.CharField(max_length=32, verbose_name='CEP'),
+ model_name="casalegislativa",
+ name="cep",
+ field=models.CharField(max_length=32, verbose_name="CEP"),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='codigo_interlegis',
- field=models.CharField(max_length=3, verbose_name='C\xf3digo Interlegis', blank=True),
+ model_name="casalegislativa",
+ name="codigo_interlegis",
+ field=models.CharField(
+ max_length=3, verbose_name="C\xf3digo Interlegis", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='email',
- field=models.EmailField(max_length=128, verbose_name='E-mail', blank=True),
+ model_name="casalegislativa",
+ name="email",
+ field=models.EmailField(
+ max_length=128, verbose_name="E-mail", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='foto',
- field=models.ImageField(upload_to='imagens/casas', width_field='foto_largura', height_field='foto_altura', blank=True, verbose_name='Foto'),
+ model_name="casalegislativa",
+ name="foto",
+ field=models.ImageField(
+ upload_to="imagens/casas",
+ width_field="foto_largura",
+ height_field="foto_altura",
+ blank=True,
+ verbose_name="Foto",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='inclusao_digital',
- field=models.CharField(default='NAO PESQUISADO', max_length=30, verbose_name='Inclus\xe3o digital', choices=[('NAO PESQUISADO', 'N\xe3o pesquisado'), ('NAO POSSUI PORTAL', 'N\xe3o possui portal'), ('PORTAL MODELO', 'Possui Portal Modelo'), ('OUTRO PORTAL', 'Possui outro portal')]),
+ model_name="casalegislativa",
+ name="inclusao_digital",
+ field=models.CharField(
+ default="NAO PESQUISADO",
+ max_length=30,
+ verbose_name="Inclus\xe3o digital",
+ choices=[
+ ("NAO PESQUISADO", "N\xe3o pesquisado"),
+ ("NAO POSSUI PORTAL", "N\xe3o possui portal"),
+ ("PORTAL MODELO", "Possui Portal Modelo"),
+ ("OUTRO PORTAL", "Possui outro portal"),
+ ],
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='logradouro',
- field=models.CharField(help_text='Avenida, rua, pra\xe7a, jardim, parque...', max_length=100, verbose_name='Logradouro'),
+ model_name="casalegislativa",
+ name="logradouro",
+ field=models.CharField(
+ help_text="Avenida, rua, pra\xe7a, jardim, parque...",
+ max_length=100,
+ verbose_name="Logradouro",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='municipio',
- field=models.ForeignKey(verbose_name='Munic\xedpio', to='contatos.Municipio', on_delete=models.CASCADE),
+ model_name="casalegislativa",
+ name="municipio",
+ field=models.ForeignKey(
+ verbose_name="Munic\xedpio",
+ to="contatos.Municipio",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='nome',
- field=models.CharField(help_text='Exemplo: C\xe2mara Municipal de Pains .', max_length=60, verbose_name='Nome'),
+ model_name="casalegislativa",
+ name="nome",
+ field=models.CharField(
+ help_text="Exemplo: C\xe2mara Municipal de Pains .",
+ max_length=60,
+ verbose_name="Nome",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='casalegislativa',
- name='pagina_web',
- field=models.URLField(help_text='Exemplo: http://www.camarapains.mg.gov.br .', verbose_name='P\xe1gina web', blank=True),
+ model_name="casalegislativa",
+ name="pagina_web",
+ field=models.URLField(
+ help_text="Exemplo: http://www.camarapains.mg.gov.br .",
+ verbose_name="P\xe1gina web",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='cargo',
- field=models.CharField(max_length=100, null=True, verbose_name='Cargo', blank=True),
+ model_name="funcionario",
+ name="cargo",
+ field=models.CharField(
+ max_length=100, null=True, verbose_name="Cargo", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='nota',
- field=models.CharField(max_length=70, null=True, verbose_name='Telefones', blank=True),
+ model_name="funcionario",
+ name="nota",
+ field=models.CharField(
+ max_length=70, null=True, verbose_name="Telefones", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='setor',
- field=models.CharField(default='outros', max_length=100, verbose_name='Setor', choices=[('presidente', 'Presidente'), ('contato_interlegis', 'Contato Interlegis'), ('infraestrutura_fisica', 'Infraestrutura F\xedsica'), ('estrutura_de_ti', 'Estrutura de TI'), ('organizacao_do_processo_legislativo', 'Organiza\xe7\xe3o do Processo Legislativo'), ('producao_legislativa', 'Produ\xe7\xe3o Legislativa'), ('estrutura_de_comunicacao_social', 'Estrutura de Comunica\xe7\xe3o Social'), ('estrutura_de_recursos_humanos', 'Estrutura de Recursos Humanos'), ('gestao', 'Gest\xe3o'), ('outros', 'Outros')]),
+ model_name="funcionario",
+ name="setor",
+ field=models.CharField(
+ default="outros",
+ max_length=100,
+ verbose_name="Setor",
+ choices=[
+ ("presidente", "Presidente"),
+ ("contato_interlegis", "Contato Interlegis"),
+ ("infraestrutura_fisica", "Infraestrutura F\xedsica"),
+ ("estrutura_de_ti", "Estrutura de TI"),
+ (
+ "organizacao_do_processo_legislativo",
+ "Organiza\xe7\xe3o do Processo Legislativo",
+ ),
+ ("producao_legislativa", "Produ\xe7\xe3o Legislativa"),
+ (
+ "estrutura_de_comunicacao_social",
+ "Estrutura de Comunica\xe7\xe3o Social",
+ ),
+ (
+ "estrutura_de_recursos_humanos",
+ "Estrutura de Recursos Humanos",
+ ),
+ ("gestao", "Gest\xe3o"),
+ ("outros", "Outros"),
+ ],
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='sexo',
- field=models.CharField(default='M', max_length=1, verbose_name='Sexo', choices=[('M', 'Masculino'), ('F', 'Feminino')]),
+ model_name="funcionario",
+ name="sexo",
+ field=models.CharField(
+ default="M",
+ max_length=1,
+ verbose_name="Sexo",
+ choices=[("M", "Masculino"), ("F", "Feminino")],
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='tempo_de_servico',
- field=models.CharField(max_length=50, null=True, verbose_name='Tempo de servi\xe7o', blank=True),
+ model_name="funcionario",
+ name="tempo_de_servico",
+ field=models.CharField(
+ max_length=50,
+ null=True,
+ verbose_name="Tempo de servi\xe7o",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='tipocasalegislativa',
- name='nome',
- field=models.CharField(max_length=100, verbose_name='Nome'),
+ model_name="tipocasalegislativa",
+ name="nome",
+ field=models.CharField(max_length=100, verbose_name="Nome"),
preserve_default=True,
),
migrations.AlterField(
- model_name='tipocasalegislativa',
- name='sigla',
- field=models.CharField(max_length=5, verbose_name='Sigla'),
+ model_name="tipocasalegislativa",
+ name="sigla",
+ field=models.CharField(max_length=5, verbose_name="Sigla"),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0008_auto_20210218_1007.py b/sigi/apps/casas/migrations/0008_auto_20210218_1007.py
index b76582b..26b3445 100644
--- a/sigi/apps/casas/migrations/0008_auto_20210218_1007.py
+++ b/sigi/apps/casas/migrations/0008_auto_20210218_1007.py
@@ -6,39 +6,54 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0002_auto_20151104_0810'),
- ('casas', '0007_auto_20201016_1632'),
+ ("contatos", "0002_auto_20151104_0810"),
+ ("casas", "0007_auto_20201016_1632"),
]
operations = [
migrations.AddField(
- model_name='funcionario',
- name='bairro',
- field=models.CharField(max_length=100, verbose_name='Bairro', blank=True),
+ model_name="funcionario",
+ name="bairro",
+ field=models.CharField(
+ max_length=100, verbose_name="Bairro", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='cep',
- field=models.CharField(max_length=10, verbose_name='CEP', blank=True),
+ model_name="funcionario",
+ name="cep",
+ field=models.CharField(
+ max_length=10, verbose_name="CEP", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='endereco',
- field=models.CharField(max_length=100, verbose_name='Endere\xe7o', blank=True),
+ model_name="funcionario",
+ name="endereco",
+ field=models.CharField(
+ max_length=100, verbose_name="Endere\xe7o", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='municipio',
- field=models.ForeignKey(verbose_name='Municipio', to='contatos.Municipio', null=True, on_delete=models.CASCADE),
+ model_name="funcionario",
+ name="municipio",
+ field=models.ForeignKey(
+ verbose_name="Municipio",
+ to="contatos.Municipio",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcionario',
- name='redes_sociais',
- field=models.TextField(help_text='Colocar um por linha', verbose_name='Redes sociais', blank=True),
+ model_name="funcionario",
+ name="redes_sociais",
+ field=models.TextField(
+ help_text="Colocar um por linha",
+ verbose_name="Redes sociais",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0009_auto_20210406_1055.py b/sigi/apps/casas/migrations/0009_auto_20210406_1055.py
index 19a280a..c6306c1 100644
--- a/sigi/apps/casas/migrations/0009_auto_20210406_1055.py
+++ b/sigi/apps/casas/migrations/0009_auto_20210406_1055.py
@@ -6,14 +6,20 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0008_auto_20210218_1007'),
+ ("casas", "0008_auto_20210218_1007"),
]
operations = [
migrations.AlterField(
- model_name='funcionario',
- name='municipio',
- field=models.ForeignKey(verbose_name='Municipio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE),
+ model_name="funcionario",
+ name="municipio",
+ field=models.ForeignKey(
+ verbose_name="Municipio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0010_auto_20210406_1101.py b/sigi/apps/casas/migrations/0010_auto_20210406_1101.py
index b6b9876..638c9ba 100644
--- a/sigi/apps/casas/migrations/0010_auto_20210406_1101.py
+++ b/sigi/apps/casas/migrations/0010_auto_20210406_1101.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0009_auto_20210406_1055'),
+ ("casas", "0009_auto_20210406_1055"),
]
operations = [
migrations.RenameModel(
- old_name='TipoCasaLegislativa',
- new_name='TipoOrgao',
+ old_name="TipoCasaLegislativa",
+ new_name="TipoOrgao",
),
]
diff --git a/sigi/apps/casas/migrations/0011_auto_20210406_1135.py b/sigi/apps/casas/migrations/0011_auto_20210406_1135.py
index 763bd13..4d806d8 100644
--- a/sigi/apps/casas/migrations/0011_auto_20210406_1135.py
+++ b/sigi/apps/casas/migrations/0011_auto_20210406_1135.py
@@ -6,12 +6,15 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0010_auto_20210406_1101'),
+ ("casas", "0010_auto_20210406_1101"),
]
operations = [
migrations.AlterModelOptions(
- name='tipoorgao',
- options={'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'},
+ name="tipoorgao",
+ options={
+ "verbose_name": "Tipo de \xf3rg\xe3o",
+ "verbose_name_plural": "Tipos de \xf3rg\xe3o",
+ },
),
]
diff --git a/sigi/apps/casas/migrations/0012_auto_20210406_1420.py b/sigi/apps/casas/migrations/0012_auto_20210406_1420.py
index 012326a..806a95b 100644
--- a/sigi/apps/casas/migrations/0012_auto_20210406_1420.py
+++ b/sigi/apps/casas/migrations/0012_auto_20210406_1420.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0011_auto_20210406_1135'),
+ ("casas", "0011_auto_20210406_1135"),
]
operations = [
migrations.AlterModelOptions(
- name='tipoorgao',
+ name="tipoorgao",
options={},
),
]
diff --git a/sigi/apps/casas/migrations/0013_auto_20210406_1428.py b/sigi/apps/casas/migrations/0013_auto_20210406_1428.py
index 0cac340..4767dcf 100644
--- a/sigi/apps/casas/migrations/0013_auto_20210406_1428.py
+++ b/sigi/apps/casas/migrations/0013_auto_20210406_1428.py
@@ -6,12 +6,15 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0012_auto_20210406_1420'),
+ ("casas", "0012_auto_20210406_1420"),
]
operations = [
migrations.AlterModelOptions(
- name='tipoorgao',
- options={'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'},
+ name="tipoorgao",
+ options={
+ "verbose_name": "Tipo de \xf3rg\xe3o",
+ "verbose_name_plural": "Tipos de \xf3rg\xe3o",
+ },
),
]
diff --git a/sigi/apps/casas/migrations/0014_auto_20210406_1945.py b/sigi/apps/casas/migrations/0014_auto_20210406_1945.py
index 6a3f091..2444406 100644
--- a/sigi/apps/casas/migrations/0014_auto_20210406_1945.py
+++ b/sigi/apps/casas/migrations/0014_auto_20210406_1945.py
@@ -7,19 +7,19 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0002_auto_20151104_0810'),
- ('servidores', '0001_initial'),
- ('servicos', '0004_delete_casaatendida'),
- ('inventario', '0001_initial'),
- ('convenios', '0002_convenio_duracao'),
- ('ocorrencias', '0002_auto_20160308_0828'),
- ('eventos', '0004_remove_evento_curso_moodle_id'),
- ('casas', '0013_auto_20210406_1428'),
+ ("contatos", "0002_auto_20151104_0810"),
+ ("servidores", "0001_initial"),
+ ("servicos", "0004_delete_casaatendida"),
+ ("inventario", "0001_initial"),
+ ("convenios", "0002_convenio_duracao"),
+ ("ocorrencias", "0002_auto_20160308_0828"),
+ ("eventos", "0004_remove_evento_curso_moodle_id"),
+ ("casas", "0013_auto_20210406_1428"),
]
operations = [
migrations.RenameModel(
- old_name='CasaLegislativa',
- new_name='Orgao',
+ old_name="CasaLegislativa",
+ new_name="Orgao",
),
]
diff --git a/sigi/apps/casas/migrations/0015_auto_20210407_0801.py b/sigi/apps/casas/migrations/0015_auto_20210407_0801.py
index 744c050..af7f1fc 100644
--- a/sigi/apps/casas/migrations/0015_auto_20210407_0801.py
+++ b/sigi/apps/casas/migrations/0015_auto_20210407_0801.py
@@ -6,22 +6,28 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0014_auto_20210406_1945'),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterModelOptions(
- name='orgao',
- options={'ordering': ('nome',), 'verbose_name': '\xd3rg\xe3o', 'verbose_name_plural': '\xd3rg\xe3os'},
+ name="orgao",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "\xd3rg\xe3o",
+ "verbose_name_plural": "\xd3rg\xe3os",
+ },
),
migrations.AddField(
- model_name='tipoorgao',
- name='legislativo',
- field=models.BooleanField(default=False, verbose_name='Poder legislativo'),
+ model_name="tipoorgao",
+ name="legislativo",
+ field=models.BooleanField(
+ default=False, verbose_name="Poder legislativo"
+ ),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='orgao',
+ name="orgao",
unique_together=set([]),
),
]
diff --git a/sigi/apps/casas/migrations/0016_auto_20210407_1559.py b/sigi/apps/casas/migrations/0016_auto_20210407_1559.py
index a87b846..8480fb8 100644
--- a/sigi/apps/casas/migrations/0016_auto_20210407_1559.py
+++ b/sigi/apps/casas/migrations/0016_auto_20210407_1559.py
@@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0015_auto_20210407_0801'),
+ ("casas", "0015_auto_20210407_0801"),
]
operations = [
migrations.AlterField(
- model_name='orgao',
- name='gerentes_interlegis',
- field=models.ManyToManyField(related_name='casas_que_gerencia', verbose_name='Gerentes Interlegis', to='servidores.Servidor', blank=True),
+ model_name="orgao",
+ name="gerentes_interlegis",
+ field=models.ManyToManyField(
+ related_name="casas_que_gerencia",
+ verbose_name="Gerentes Interlegis",
+ to="servidores.Servidor",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0017_auto_20210416_0841.py b/sigi/apps/casas/migrations/0017_auto_20210416_0841.py
index a831992..0e7bba7 100644
--- a/sigi/apps/casas/migrations/0017_auto_20210416_0841.py
+++ b/sigi/apps/casas/migrations/0017_auto_20210416_0841.py
@@ -7,38 +7,62 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0016_auto_20210407_1559'),
+ ("casas", "0016_auto_20210407_1559"),
]
operations = [
migrations.AlterField(
- model_name='funcionario',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='\xf3rg\xe3o', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="funcionario",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="\xf3rg\xe3o",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='municipio',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Municipio', blank=True, to='contatos.Municipio', null=True),
+ model_name="funcionario",
+ name="municipio",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="Municipio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='orgao',
- name='municipio',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Munic\xedpio', to='contatos.Municipio'),
+ model_name="orgao",
+ name="municipio",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Munic\xedpio",
+ to="contatos.Municipio",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='orgao',
- name='pesquisador',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Pesquisador', blank=True, to='servidores.Servidor', null=True),
+ model_name="orgao",
+ name="pesquisador",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="Pesquisador",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='orgao',
- name='tipo',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo', to='casas.TipoOrgao'),
+ model_name="orgao",
+ name="tipo",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Tipo",
+ to="casas.TipoOrgao",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0018_orgao_sigla.py b/sigi/apps/casas/migrations/0018_orgao_sigla.py
index 70aaed7..b4e3faa 100644
--- a/sigi/apps/casas/migrations/0018_orgao_sigla.py
+++ b/sigi/apps/casas/migrations/0018_orgao_sigla.py
@@ -6,14 +6,16 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0017_auto_20210416_0841'),
+ ("casas", "0017_auto_20210416_0841"),
]
operations = [
migrations.AddField(
- model_name='orgao',
- name='sigla',
- field=models.CharField(max_length=30, verbose_name='sigla do \xf3rg\xe3o', blank=True),
+ model_name="orgao",
+ name="sigla",
+ field=models.CharField(
+ max_length=30, verbose_name="sigla do \xf3rg\xe3o", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0019_auto_20210501_1058.py b/sigi/apps/casas/migrations/0019_auto_20210501_1058.py
index 9a406fa..d5f662a 100644
--- a/sigi/apps/casas/migrations/0019_auto_20210501_1058.py
+++ b/sigi/apps/casas/migrations/0019_auto_20210501_1058.py
@@ -6,20 +6,24 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0018_orgao_sigla'),
+ ("casas", "0018_orgao_sigla"),
]
operations = [
migrations.AlterField(
- model_name='funcionario',
- name='email',
- field=models.CharField(max_length=250, verbose_name='e-mail', blank=True),
+ model_name="funcionario",
+ name="email",
+ field=models.CharField(
+ max_length=250, verbose_name="e-mail", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='funcionario',
- name='nota',
- field=models.CharField(max_length=250, null=True, verbose_name='Telefones', blank=True),
+ model_name="funcionario",
+ name="nota",
+ field=models.CharField(
+ max_length=250, null=True, verbose_name="Telefones", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/casas/migrations/0020_auto_20210611_0946.py b/sigi/apps/casas/migrations/0020_auto_20210611_0946.py
index 2b4f310..fc7a9dc 100644
--- a/sigi/apps/casas/migrations/0020_auto_20210611_0946.py
+++ b/sigi/apps/casas/migrations/0020_auto_20210611_0946.py
@@ -6,12 +6,16 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0019_auto_20210501_1058'),
+ ("casas", "0019_auto_20210501_1058"),
]
operations = [
migrations.AlterModelOptions(
- name='tipoorgao',
- options={'ordering': ('nome',), 'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'},
+ name="tipoorgao",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "Tipo de \xf3rg\xe3o",
+ "verbose_name_plural": "Tipos de \xf3rg\xe3o",
+ },
),
]
diff --git a/sigi/apps/casas/migrations/0021_alter_orgao_options_remove_orgao_recorte_and_more.py b/sigi/apps/casas/migrations/0021_alter_orgao_options_remove_orgao_recorte_and_more.py
index 63421a9..bcef4bb 100644
--- a/sigi/apps/casas/migrations/0021_alter_orgao_options_remove_orgao_recorte_and_more.py
+++ b/sigi/apps/casas/migrations/0021_alter_orgao_options_remove_orgao_recorte_and_more.py
@@ -8,193 +8,340 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0008_alter_servico_id_alter_servidor_foto_and_more'),
- ('contatos', '0005_alter_mesorregiao_options_alter_microrregiao_options_and_more'),
- ('casas', '0020_auto_20210611_0946'),
+ ("servidores", "0008_alter_servico_id_alter_servidor_foto_and_more"),
+ (
+ "contatos",
+ "0005_alter_mesorregiao_options_alter_microrregiao_options_and_more",
+ ),
+ ("casas", "0020_auto_20210611_0946"),
]
operations = [
migrations.AlterModelOptions(
- name='orgao',
- options={'ordering': ('nome',), 'verbose_name': 'órgão', 'verbose_name_plural': 'órgãos'},
+ name="orgao",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "órgão",
+ "verbose_name_plural": "órgãos",
+ },
),
migrations.RemoveField(
- model_name='orgao',
- name='recorte',
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='bairro',
- field=models.CharField(blank=True, max_length=100, verbose_name='bairro'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='cargo',
- field=models.CharField(blank=True, max_length=100, null=True, verbose_name='cargo'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='data_nascimento',
- field=models.DateField(blank=True, null=True, verbose_name='data de nascimento'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='desativado',
- field=models.BooleanField(default=False, verbose_name='desativado'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='endereco',
- field=models.CharField(blank=True, max_length=100, verbose_name='endereço'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='municipio',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contatos.municipio', verbose_name='municipio'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='nome',
- field=models.CharField(max_length=60, verbose_name='nome completo'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='nota',
- field=models.CharField(blank=True, max_length=250, null=True, verbose_name='telefones'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='observacoes',
- field=models.TextField(blank=True, verbose_name='observações'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='redes_sociais',
- field=models.TextField(blank=True, help_text='Colocar um por linha', verbose_name='redes sociais'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='setor',
- field=models.CharField(choices=[('presidente', 'Presidente'), ('contato_interlegis', 'Contato Interlegis'), ('infraestrutura_fisica', 'Infraestrutura Física'), ('estrutura_de_ti', 'Estrutura de TI'), ('organizacao_do_processo_legislativo', 'Organização do Processo Legislativo'), ('producao_legislativa', 'Produção Legislativa'), ('estrutura_de_comunicacao_social', 'Estrutura de Comunicação Social'), ('estrutura_de_recursos_humanos', 'Estrutura de Recursos Humanos'), ('gestao', 'Gestão'), ('outros', 'Outros')], default='outros', max_length=100, verbose_name='setor'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='sexo',
- field=models.CharField(choices=[('M', 'Masculino'), ('F', 'Feminino')], default='M', max_length=1, verbose_name='sexo'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='tempo_de_servico',
- field=models.CharField(blank=True, max_length=50, null=True, verbose_name='tempo de serviço'),
- ),
- migrations.AlterField(
- model_name='funcionario',
- name='ult_alteracao',
- field=models.DateTimeField(auto_now=True, null=True, verbose_name='última alteração'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='bairro',
- field=models.CharField(blank=True, max_length=100, verbose_name='bairro'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='cnpj',
- field=models.CharField(blank=True, max_length=32, verbose_name='CNPJ'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='codigo_interlegis',
- field=models.CharField(blank=True, max_length=3, verbose_name='código Interlegis'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='data_instalacao',
- field=models.DateField(blank=True, null=True, verbose_name='data de instalação da Casa Legislativa'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='data_levantamento',
- field=models.DateTimeField(blank=True, null=True, verbose_name='data/hora da pesquisa'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='email',
- field=models.EmailField(blank=True, max_length=128, verbose_name='e-mail'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='foto',
- field=models.ImageField(blank=True, height_field='foto_altura', upload_to='imagens/casas', verbose_name='foto', width_field='foto_largura'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='horario_funcionamento',
- field=models.CharField(blank=True, max_length=100, verbose_name='horário de funcionamento da Casa Legislativa'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='inclusao_digital',
- field=models.CharField(choices=[('NAO PESQUISADO', 'Não pesquisado'), ('NAO POSSUI PORTAL', 'Não possui portal'), ('PORTAL MODELO', 'Possui Portal Modelo'), ('OUTRO PORTAL', 'Possui outro portal')], default='NAO PESQUISADO', max_length=30, verbose_name='inclusão digital'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='logradouro',
- field=models.CharField(help_text='Avenida, rua, praça, jardim, parque...', max_length=100, verbose_name='logradouro'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='municipio',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contatos.municipio', verbose_name='município'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='nome',
- field=models.CharField(help_text='Exemplo: Câmara Municipal de Pains .', max_length=60, verbose_name='nome'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='obs_pesquisa',
- field=models.TextField(blank=True, verbose_name='observações do pesquisador'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='pagina_web',
- field=models.URLField(blank=True, help_text='Exemplo: http://www.camarapains.mg.gov.br .', verbose_name='página web'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='pesquisador',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='servidores.servidor', verbose_name='pesquisador'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='search_text',
- field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='tipo',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='casas.tipoorgao', verbose_name='tipo'),
- ),
- migrations.AlterField(
- model_name='orgao',
- name='ult_alt_endereco',
- field=models.DateTimeField(blank=True, null=True, verbose_name='última alteração do endereço'),
- ),
- migrations.AlterField(
- model_name='tipoorgao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="orgao",
+ name="recorte",
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="bairro",
+ field=models.CharField(
+ blank=True, max_length=100, verbose_name="bairro"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="cargo",
+ field=models.CharField(
+ blank=True, max_length=100, null=True, verbose_name="cargo"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="data_nascimento",
+ field=models.DateField(
+ blank=True, null=True, verbose_name="data de nascimento"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="desativado",
+ field=models.BooleanField(default=False, verbose_name="desativado"),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="endereco",
+ field=models.CharField(
+ blank=True, max_length=100, verbose_name="endereço"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="municipio",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="contatos.municipio",
+ verbose_name="municipio",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="nome",
+ field=models.CharField(max_length=60, verbose_name="nome completo"),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="nota",
+ field=models.CharField(
+ blank=True, max_length=250, null=True, verbose_name="telefones"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="observacoes",
+ field=models.TextField(blank=True, verbose_name="observações"),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="redes_sociais",
+ field=models.TextField(
+ blank=True,
+ help_text="Colocar um por linha",
+ verbose_name="redes sociais",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="setor",
+ field=models.CharField(
+ choices=[
+ ("presidente", "Presidente"),
+ ("contato_interlegis", "Contato Interlegis"),
+ ("infraestrutura_fisica", "Infraestrutura Física"),
+ ("estrutura_de_ti", "Estrutura de TI"),
+ (
+ "organizacao_do_processo_legislativo",
+ "Organização do Processo Legislativo",
+ ),
+ ("producao_legislativa", "Produção Legislativa"),
+ (
+ "estrutura_de_comunicacao_social",
+ "Estrutura de Comunicação Social",
+ ),
+ (
+ "estrutura_de_recursos_humanos",
+ "Estrutura de Recursos Humanos",
+ ),
+ ("gestao", "Gestão"),
+ ("outros", "Outros"),
+ ],
+ default="outros",
+ max_length=100,
+ verbose_name="setor",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="sexo",
+ field=models.CharField(
+ choices=[("M", "Masculino"), ("F", "Feminino")],
+ default="M",
+ max_length=1,
+ verbose_name="sexo",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="tempo_de_servico",
+ field=models.CharField(
+ blank=True,
+ max_length=50,
+ null=True,
+ verbose_name="tempo de serviço",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="funcionario",
+ name="ult_alteracao",
+ field=models.DateTimeField(
+ auto_now=True, null=True, verbose_name="última alteração"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="bairro",
+ field=models.CharField(
+ blank=True, max_length=100, verbose_name="bairro"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="cnpj",
+ field=models.CharField(
+ blank=True, max_length=32, verbose_name="CNPJ"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="codigo_interlegis",
+ field=models.CharField(
+ blank=True, max_length=3, verbose_name="código Interlegis"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="data_instalacao",
+ field=models.DateField(
+ blank=True,
+ null=True,
+ verbose_name="data de instalação da Casa Legislativa",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="data_levantamento",
+ field=models.DateTimeField(
+ blank=True, null=True, verbose_name="data/hora da pesquisa"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="email",
+ field=models.EmailField(
+ blank=True, max_length=128, verbose_name="e-mail"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="foto",
+ field=models.ImageField(
+ blank=True,
+ height_field="foto_altura",
+ upload_to="imagens/casas",
+ verbose_name="foto",
+ width_field="foto_largura",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="horario_funcionamento",
+ field=models.CharField(
+ blank=True,
+ max_length=100,
+ verbose_name="horário de funcionamento da Casa Legislativa",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="inclusao_digital",
+ field=models.CharField(
+ choices=[
+ ("NAO PESQUISADO", "Não pesquisado"),
+ ("NAO POSSUI PORTAL", "Não possui portal"),
+ ("PORTAL MODELO", "Possui Portal Modelo"),
+ ("OUTRO PORTAL", "Possui outro portal"),
+ ],
+ default="NAO PESQUISADO",
+ max_length=30,
+ verbose_name="inclusão digital",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="logradouro",
+ field=models.CharField(
+ help_text="Avenida, rua, praça, jardim, parque...",
+ max_length=100,
+ verbose_name="logradouro",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="municipio",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ to="contatos.municipio",
+ verbose_name="município",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="nome",
+ field=models.CharField(
+ help_text="Exemplo: Câmara Municipal de Pains .",
+ max_length=60,
+ verbose_name="nome",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="obs_pesquisa",
+ field=models.TextField(
+ blank=True, verbose_name="observações do pesquisador"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="pagina_web",
+ field=models.URLField(
+ blank=True,
+ help_text="Exemplo: http://www.camarapains.mg.gov.br .",
+ verbose_name="página web",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="pesquisador",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="servidores.servidor",
+ verbose_name="pesquisador",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="search_text",
+ field=sigi.apps.utils.SearchField(
+ editable=False, field_names=["nome"]
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="tipo",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ to="casas.tipoorgao",
+ verbose_name="tipo",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orgao",
+ name="ult_alt_endereco",
+ field=models.DateTimeField(
+ blank=True,
+ null=True,
+ verbose_name="última alteração do endereço",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="tipoorgao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
]
diff --git a/sigi/apps/casas/models.py b/sigi/apps/casas/models.py
index cfa81cd..b800921 100644
--- a/sigi/apps/casas/models.py
+++ b/sigi/apps/casas/models.py
@@ -11,140 +11,129 @@ from sigi.apps.contatos.models import Municipio
from sigi.apps.servidores.models import Servidor
from sigi.apps.utils import SearchField
+
class TipoOrgao(models.Model):
sigla = models.CharField(_("Sigla"), max_length=5)
nome = models.CharField(_("Nome"), max_length=100)
legislativo = models.BooleanField(_("Poder legislativo"), default=False)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
verbose_name = _("Tipo de órgão")
verbose_name_plural = _("Tipos de órgão")
def __str__(self):
return self.nome
+
class Orgao(models.Model):
INCLUSAO_DIGITAL_CHOICES = (
- ('NAO PESQUISADO', _('Não pesquisado')),
- ('NAO POSSUI PORTAL', _('Não possui portal')),
- ('PORTAL MODELO', _('Possui Portal Modelo')),
- ('OUTRO PORTAL', _('Possui outro portal')),
+ ("NAO PESQUISADO", _("Não pesquisado")),
+ ("NAO POSSUI PORTAL", _("Não possui portal")),
+ ("PORTAL MODELO", _("Possui Portal Modelo")),
+ ("OUTRO PORTAL", _("Possui outro portal")),
)
nome = models.CharField(
_("nome"),
max_length=60,
- help_text=_('Exemplo: Câmara Municipal de Pains .')
- )
- sigla = models.CharField(
- _("sigla do órgão"),
- max_length=30,
- blank=True
+ help_text=_("Exemplo: Câmara Municipal de Pains ."),
)
+ sigla = models.CharField(_("sigla do órgão"), max_length=30, blank=True)
# Guarda um campo para ser usado em buscas em caixa baixa e sem acento
- search_text = SearchField(field_names=['nome'])
+ search_text = SearchField(field_names=["nome"])
tipo = models.ForeignKey(
- TipoOrgao,
- on_delete=models.PROTECT,
- verbose_name=_("tipo")
+ TipoOrgao, on_delete=models.PROTECT, verbose_name=_("tipo")
)
cnpj = models.CharField(_("CNPJ"), max_length=32, blank=True)
- observacoes = models.TextField(_('observações'), blank=True)
+ observacoes = models.TextField(_("observações"), blank=True)
horario_funcionamento = models.CharField(
_("horário de funcionamento da Casa Legislativa"),
max_length=100,
blank=True,
)
codigo_interlegis = models.CharField(
- _('código Interlegis'),
- max_length=3,
- blank=True
+ _("código Interlegis"), max_length=3, blank=True
)
gerentes_interlegis = models.ManyToManyField(
Servidor,
verbose_name=_("Gerentes Interlegis"),
- related_name='casas_que_gerencia',
+ related_name="casas_que_gerencia",
blank=True,
)
# Informações de contato
logradouro = models.CharField(
_("logradouro"),
max_length=100,
- help_text=_('Avenida, rua, praça, jardim, parque...')
+ help_text=_("Avenida, rua, praça, jardim, parque..."),
)
bairro = models.CharField(_("bairro"), max_length=100, blank=True)
municipio = models.ForeignKey(
- 'contatos.Municipio',
+ "contatos.Municipio",
on_delete=models.PROTECT,
- verbose_name=_('município')
+ verbose_name=_("município"),
)
cep = models.CharField(_("CEP"), max_length=32)
- email = models.EmailField(_('e-mail'), max_length=128, blank=True)
+ email = models.EmailField(_("e-mail"), max_length=128, blank=True)
pagina_web = models.URLField(
- _('página web'),
- help_text=_('Exemplo: http://www.camarapains.mg.gov.br .'),
+ _("página web"),
+ help_text=_("Exemplo: http://www.camarapains.mg.gov.br ."),
blank=True,
)
inclusao_digital = models.CharField(
_("inclusão digital"),
max_length=30,
choices=INCLUSAO_DIGITAL_CHOICES,
- default=INCLUSAO_DIGITAL_CHOICES[0][0]
+ default=INCLUSAO_DIGITAL_CHOICES[0][0],
)
data_levantamento = models.DateTimeField(
- _("data/hora da pesquisa"),
- null=True,
- blank=True
+ _("data/hora da pesquisa"), null=True, blank=True
)
pesquisador = models.ForeignKey(
Servidor,
on_delete=models.SET_NULL,
verbose_name=_("pesquisador"),
null=True,
- blank=True
- )
- obs_pesquisa = models.TextField(
- _("observações do pesquisador"),
- blank=True
+ blank=True,
)
+ obs_pesquisa = models.TextField(_("observações do pesquisador"), blank=True)
ult_alt_endereco = models.DateTimeField(
- _('última alteração do endereço'),
- null=True,
- blank=True,
- editable=True
+ _("última alteração do endereço"), null=True, blank=True, editable=True
)
- telefones = GenericRelation('contatos.Telefone')
+ telefones = GenericRelation("contatos.Telefone")
foto = models.ImageField(
_("foto"),
- upload_to='imagens/casas',
- width_field='foto_largura',
- height_field='foto_altura',
- blank=True
+ upload_to="imagens/casas",
+ width_field="foto_largura",
+ height_field="foto_altura",
+ blank=True,
)
foto_largura = models.SmallIntegerField(editable=False, null=True)
foto_altura = models.SmallIntegerField(editable=False, null=True)
data_instalacao = models.DateField(
- _('data de instalação da Casa Legislativa'),
- null=True,
- blank=True
+ _("data de instalação da Casa Legislativa"), null=True, blank=True
)
class Meta:
- ordering = ('nome',)
- verbose_name = _('órgão')
- verbose_name_plural = _('órgãos')
+ ordering = ("nome",)
+ verbose_name = _("órgão")
+ verbose_name_plural = _("órgãos")
- def lista_gerentes(self, fmt='html'):
+ def lista_gerentes(self, fmt="html"):
if not self.gerentes_interlegis.exists():
return ""
- if fmt == 'html':
- return ""+" ".join(
- [g.nome_completo for g in self.gerentes_interlegis.all()])+\
- " "
+ if fmt == "html":
+ return (
+ ""
+ + " ".join(
+ [g.nome_completo for g in self.gerentes_interlegis.all()]
+ )
+ + " "
+ )
else:
- return ", ".join([g.nome_completo for g in
- self.gerentes_interlegis.all()])
+ return ", ".join(
+ [g.nome_completo for g in self.gerentes_interlegis.all()]
+ )
@property
def num_parlamentares(self):
@@ -160,29 +149,34 @@ class Orgao(models.Model):
@property
def presidente(self):
try:
- if self.funcionario_set.filter(setor='presidente').count() > 1:
- return self.funcionario_set.filter(setor='presidente')[0]
+ if self.funcionario_set.filter(setor="presidente").count() > 1:
+ return self.funcionario_set.filter(setor="presidente")[0]
else:
- return self.funcionario_set.get(setor='presidente')
+ return self.funcionario_set.get(setor="presidente")
except Funcionario.DoesNotExist:
return None
@property
def contato_interlegis(self):
try:
- if self.funcionario_set.filter(setor='contato_interlegis').count() > 1:
- return self.funcionario_set.filter(setor='contato_interlegis')[0]
+ if (
+ self.funcionario_set.filter(setor="contato_interlegis").count()
+ > 1
+ ):
+ return self.funcionario_set.filter(setor="contato_interlegis")[
+ 0
+ ]
else:
- return self.funcionario_set.get(setor='contato_interlegis')
+ return self.funcionario_set.get(setor="contato_interlegis")
except Funcionario.DoesNotExist:
return None
def gerarCodigoInterlegis(self):
codigo = self.codigo_interlegis
- if codigo == '':
- if self.tipo.sigla == 'AL': # Assembléias são tratadas a parte
- codigo = 'A' + self.municipio.uf.sigla
+ if codigo == "":
+ if self.tipo.sigla == "AL": # Assembléias são tratadas a parte
+ codigo = "A" + self.municipio.uf.sigla
if Orgao.objects.filter(codigo_interlegis=codigo).count() <= 0:
# Só grava o código se ele for inédito
self.codigo_interlegis = codigo
@@ -190,20 +184,21 @@ class Orgao(models.Model):
return codigo
# Se já existe, então trata a Assembleia como uma Casa qualquer.
- cityName = normalize('NFKD', self.municipio.nome).encode(
- 'ascii', 'ignore')
+ cityName = normalize("NFKD", self.municipio.nome).encode(
+ "ascii", "ignore"
+ )
cityName = cityName.upper().strip()
- cityName = cityName.replace(' DA ', ' ')
- cityName = cityName.replace(' DE ', ' ')
- cityName = cityName.replace(' DO ', ' ')
- cityName = filter(lambda x: x in ascii_uppercase + ' ', cityName)
+ cityName = cityName.replace(" DA ", " ")
+ cityName = cityName.replace(" DE ", " ")
+ cityName = cityName.replace(" DO ", " ")
+ cityName = filter(lambda x: x in ascii_uppercase + " ", cityName)
# estratégia 1 - Pegar as 1ª letra de cada nome da cidade
- codigo = ''.join([x[0] for x in cityName.split(' ')[:3]])
+ codigo = "".join([x[0] for x in cityName.split(" ")[:3]])
# Se o código ficou com menos que três letras, pegar as 2 primeiras
if len(codigo) < 3:
- codigo = ''.join([x[0:2] for x in cityName.split(' ')[:3]])[:3]
+ codigo = "".join([x[0:2] for x in cityName.split(" ")[:3]])[:3]
# Se ainda ficou com menos de três letras, então o nome da cidade só
# tem uma palavra. Pegue as três primeiras letras da palavra
@@ -214,12 +209,14 @@ class Orgao(models.Model):
# última letra do nome da cidade, e ir recuando, letra a letra,
# até achar um novo código.
- cityName = cityName.replace(' ', '')
+ cityName = cityName.replace(" ", "")
ultima = len(cityName)
- while Orgao.objects.filter(codigo_interlegis=codigo). \
- count() > 0 and ultima > 0:
- codigo = codigo[:2] + cityName[ultima - 1: ultima]
+ while (
+ Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
+ and ultima > 0
+ ):
+ codigo = codigo[:2] + cityName[ultima - 1 : ultima]
ultima -= 1
# Se usou todas as letras do nome na última posição e ainda assim
@@ -227,19 +224,29 @@ class Orgao(models.Model):
# três primeiras consoantes.
if Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
- codigo_cons = cityName.replace('A', '').replace('E', '').\
- replace('I', '').replace('O', '').replace('', '')[:3]
- if len(codigo_cons) == 3 and \
- Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
+ codigo_cons = (
+ cityName.replace("A", "")
+ .replace("E", "")
+ .replace("I", "")
+ .replace("O", "")
+ .replace("", "")[:3]
+ )
+ if (
+ len(codigo_cons) == 3
+ and Orgao.objects.filter(codigo_interlegis=codigo).count()
+ > 0
+ ):
codigo = codigo_cons
# Se ainda não gerou um nome único, vamos colocar dígitos no
# último caractere, de A a Z
- i = 'A'
+ i = "A"
- while Orgao.objects.filter(codigo_interlegis=codigo). \
- count() > 0 and i <= 'Z':
+ while (
+ Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
+ and i <= "Z"
+ ):
codigo = codigo[:2] + str(i)
i = chr(ord(i) + 1)
@@ -249,16 +256,21 @@ class Orgao(models.Model):
i = 0
- while Orgao.objects.filter(codigo_interlegis=codigo). \
- count() > 0 and i < 100:
- codigo = random.choice(cityName) + random.choice(cityName) + \
+ while (
+ Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
+ and i < 100
+ ):
+ codigo = (
random.choice(cityName)
+ + random.choice(cityName)
+ + random.choice(cityName)
+ )
i += 1
# Caramba! Só resta então gerar o código com 3 letras aleatórias
# quaisquer do alfabeto!
- i = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ i = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
codigo = random.choice(i) + random.choice(i) + random.choice(i)
@@ -272,25 +284,33 @@ class Orgao(models.Model):
return self.nome
def clean(self):
- if (hasattr(self, 'tipo') and hasattr(self, 'municipio')
- and self.tipo.legislativo):
- if Orgao.objects.filter(
- tipo=self.tipo,
- municipio=self.municipio).exclude(pk=self.pk).exists():
+ if (
+ hasattr(self, "tipo")
+ and hasattr(self, "municipio")
+ and self.tipo.legislativo
+ ):
+ if (
+ Orgao.objects.filter(tipo=self.tipo, municipio=self.municipio)
+ .exclude(pk=self.pk)
+ .exists()
+ ):
raise ValidationError(
_("Já existe um(a) %(tipo)s em %(municipio)s"),
- code='integrity',
- params={'tipo': self.tipo, 'municipio': self.municipio})
+ code="integrity",
+ params={"tipo": self.tipo, "municipio": self.municipio},
+ )
def save(self, *args, **kwargs):
address_changed = False
if self.pk is not None:
original = Orgao.objects.get(pk=self.pk)
- if (self.logradouro != original.logradouro or
- self.bairro != original.bairro or
- self.municipio != original.municipio or
- self.cep != original.cep):
+ if (
+ self.logradouro != original.logradouro
+ or self.bairro != original.bairro
+ or self.municipio != original.municipio
+ or self.cep != original.cep
+ ):
address_changed = True
else:
address_changed = True
@@ -300,108 +320,93 @@ class Orgao(models.Model):
return super(Orgao, self).save(*args, **kwargs)
+
class Funcionario(models.Model):
SETOR_CHOICES = [
("presidente", _("Presidente")),
("contato_interlegis", _("Contato Interlegis")),
("infraestrutura_fisica", _("Infraestrutura Física")),
("estrutura_de_ti", _("Estrutura de TI")),
- ("organizacao_do_processo_legislativo",
- _("Organização do Processo Legislativo")),
+ (
+ "organizacao_do_processo_legislativo",
+ _("Organização do Processo Legislativo"),
+ ),
("producao_legislativa", _("Produção Legislativa")),
- ("estrutura_de_comunicacao_social",
- _("Estrutura de Comunicação Social")),
+ (
+ "estrutura_de_comunicacao_social",
+ _("Estrutura de Comunicação Social"),
+ ),
("estrutura_de_recursos_humanos", _("Estrutura de Recursos Humanos")),
("gestao", _("Gestão")),
("outros", _("Outros")),
]
- SEXO_CHOICES = [
- ("M", _("Masculino")),
- ("F", _("Feminino"))
- ]
+ SEXO_CHOICES = [("M", _("Masculino")), ("F", _("Feminino"))]
casa_legislativa = models.ForeignKey(
Orgao,
on_delete=models.CASCADE,
verbose_name=_("órgão"),
)
- nome = models.CharField(_('nome completo'), max_length=60, blank=False)
+ nome = models.CharField(_("nome completo"), max_length=60, blank=False)
sexo = models.CharField(
- _("sexo"),
- max_length=1,
- choices=SEXO_CHOICES,
- default="M"
+ _("sexo"), max_length=1, choices=SEXO_CHOICES, default="M"
)
data_nascimento = models.DateField(
- _("data de nascimento"),
- blank=True,
- null=True
+ _("data de nascimento"), blank=True, null=True
)
nota = models.CharField(
- _("telefones"),
- max_length=250,
- null=True,
- blank=True
+ _("telefones"), max_length=250, null=True, blank=True
)
- email = models.CharField(_('e-mail'), max_length=250, blank=True)
- endereco = models.CharField(_('endereço'), max_length=100, blank=True)
+ email = models.CharField(_("e-mail"), max_length=250, blank=True)
+ endereco = models.CharField(_("endereço"), max_length=100, blank=True)
municipio = models.ForeignKey(
Municipio,
on_delete=models.SET_NULL,
- verbose_name=_('municipio'),
+ verbose_name=_("municipio"),
null=True,
blank=True,
)
- bairro = models.CharField(_('bairro'), max_length=100, blank=True)
- cep = models.CharField(_('CEP'), max_length=10, blank=True)
+ bairro = models.CharField(_("bairro"), max_length=100, blank=True)
+ cep = models.CharField(_("CEP"), max_length=10, blank=True)
redes_sociais = models.TextField(
- _('redes sociais'),
- help_text=_('Colocar um por linha'),
- blank=True
+ _("redes sociais"), help_text=_("Colocar um por linha"), blank=True
)
cargo = models.CharField(_("cargo"), max_length=100, null=True, blank=True)
funcao = models.CharField(
- _('função'),
- max_length=100,
- null=True,
- blank=True
+ _("função"), max_length=100, null=True, blank=True
)
setor = models.CharField(
- _("setor"),
- max_length=100,
- choices=SETOR_CHOICES,
- default="outros"
+ _("setor"), max_length=100, choices=SETOR_CHOICES, default="outros"
)
tempo_de_servico = models.CharField(
- _('tempo de serviço'),
- max_length=50,
- null=True,
- blank=True
+ _("tempo de serviço"), max_length=50, null=True, blank=True
)
ult_alteracao = models.DateTimeField(
- _('última alteração'),
+ _("última alteração"),
null=True,
blank=True,
editable=True,
- auto_now=True
+ auto_now=True,
)
desativado = models.BooleanField(_("desativado"), default=False)
observacoes = models.TextField(_("observações"), blank=True)
class Meta:
- ordering = ('nome',)
- verbose_name = _('contato da Casa Legislativa')
- verbose_name_plural = _('contatos da Casa Legislativa')
+ ordering = ("nome",)
+ verbose_name = _("contato da Casa Legislativa")
+ verbose_name_plural = _("contatos da Casa Legislativa")
def __str__(self):
return self.nome
+
class PresidenteManager(models.Manager):
def get_queryset(self):
qs = super(PresidenteManager, self).get_queryset()
- qs = qs.filter(setor='presidente')
+ qs = qs.filter(setor="presidente")
return qs
+
class Presidente(Funcionario):
class Meta:
proxy = True
@@ -409,7 +414,7 @@ class Presidente(Funcionario):
objects = PresidenteManager()
def save(self, *args, **kwargs):
- self.setor = 'presidente'
- self.cargo = 'Presidente'
- self.funcao = 'Presidente'
- return super(Presidente, self).save(*args, **kwargs)
\ No newline at end of file
+ self.setor = "presidente"
+ self.cargo = "Presidente"
+ self.funcao = "Presidente"
+ return super(Presidente, self).save(*args, **kwargs)
diff --git a/sigi/apps/casas/test_casas.py b/sigi/apps/casas/test_casas.py
index a2026ec..dd29ff0 100644
--- a/sigi/apps/casas/test_casas.py
+++ b/sigi/apps/casas/test_casas.py
@@ -6,12 +6,21 @@ from sigi.apps.casas.models import Orgao
@pytest.fixture
def some_parliaments():
- return parliaments_from_names([
- "Assembleia Legislativa do Amapa",
- "Camara Municipal de Fortaleza",
- "Camara Legislativa do Distrito Federal",
- ])
+ return parliaments_from_names(
+ [
+ "Assembleia Legislativa do Amapa",
+ "Camara Municipal de Fortaleza",
+ "Camara Legislativa do Distrito Federal",
+ ]
+ )
def parliaments_from_names(names):
- return [G(Orgao, nome=name, foto=None,) for name in names]
+ return [
+ G(
+ Orgao,
+ nome=name,
+ foto=None,
+ )
+ for name in names
+ ]
diff --git a/sigi/apps/casas/urls.py b/sigi/apps/casas/urls.py
index c3556d4..6d0288d 100644
--- a/sigi/apps/casas/urls.py
+++ b/sigi/apps/casas/urls.py
@@ -2,9 +2,12 @@ from django.urls import path, include
from sigi.apps.casas import views
urlpatterns = [
- path('orgao/casas_sem_convenio_report/', views.CasasSemConvenioReport.as_view(),
- name='casas-sem-convenio-report'),
- path('carteira/', views.painel_relacionamento, name='casas-carteira'),
+ path(
+ "orgao/casas_sem_convenio_report/",
+ views.CasasSemConvenioReport.as_view(),
+ name="casas-sem-convenio-report",
+ ),
+ path("carteira/", views.painel_relacionamento, name="casas-carteira"),
]
@@ -65,4 +68,4 @@ urlpatterns = patterns(
url(r'^gerentes/$', 'gerentes_interlegis',
name='gerentes_interlegis'),
)
-"""
\ No newline at end of file
+"""
diff --git a/sigi/apps/casas/views.py b/sigi/apps/casas/views.py
index ea71c3f..c8a4564 100644
--- a/sigi/apps/casas/views.py
+++ b/sigi/apps/casas/views.py
@@ -9,8 +9,11 @@ from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Count, Q
-from django.http import (HttpResponse, HttpResponseRedirect,
- HttpResponseForbidden)
+from django.http import (
+ HttpResponse,
+ HttpResponseRedirect,
+ HttpResponseForbidden,
+)
from django.shortcuts import render, get_object_or_404
from django.utils.translation import gettext as _, ngettext
from django.views.generic import View
@@ -19,42 +22,46 @@ from django_weasyprint.views import WeasyTemplateView
from sigi.apps.casas.forms import PortfolioForm, AtualizaCasaForm
from sigi.apps.casas.models import Orgao, TipoOrgao, Funcionario
from sigi.apps.servidores.models import Servidor
+
# from sigi.shortcuts import render_to_pdf
# from sigi.apps.casas.reports import (CasasLegislativasLabels,
# CasasLegislativasLabelsSemPresidente)
-from sigi.apps.contatos.models import (UnidadeFederativa, Mesorregiao,
- Microrregiao)
+from sigi.apps.contatos.models import (
+ UnidadeFederativa,
+ Mesorregiao,
+ Microrregiao,
+)
+
# , Municipio
from sigi.apps.ocorrencias.models import Ocorrencia
+
# from sigi.apps.parlamentares.reports import ParlamentaresLabels
from sigi.apps.servicos.models import TipoServico
+
class CasasSemConvenioReport(WeasyTemplateView):
template_name = "casas/casas_sem_convenio_pdf.html"
- pdf_filename = 'casas_sem_convenio.pdf'
+ pdf_filename = "casas_sem_convenio.pdf"
def get_context_data(self, **kwargs):
qs = Orgao.objects.filter(convenio=None).order_by(
- 'municipio__uf',
- 'nome'
- )
- qs = Orgao.objects.order_by(
- 'municipio__uf',
- 'nome'
+ "municipio__uf", "nome"
)
+ qs = Orgao.objects.order_by("municipio__uf", "nome")
if self.request.GET:
qs = get_for_qs(self.request.GET, qs)
if not qs:
- return HttpResponseRedirect('../')
+ return HttpResponseRedirect("../")
+
+ qs = qs.order_by("municipio__uf", "nome")
+ return {"casas": qs, "title": _("Casas sem convênio")}
- qs = qs.order_by('municipio__uf', 'nome')
- return {'casas': qs, 'title': _("Casas sem convênio")}
def get_for_qs(get, qs):
kwargs = {}
for k, v in get.items():
- if str(k) not in ('page', 'pop', 'q', '_popup', 'o', 'ot'):
+ if str(k) not in ("page", "pop", "q", "_popup", "o", "ot"):
kwargs[str(k)] = v
# if 'convenio' in kwargs:
@@ -85,37 +92,37 @@ def get_for_qs(get, qs):
# else:
# qs = qs.filter(servico__tipo_servico_id=kwargs['servico'])
- # qs = qs.distinct('municipio__uf__nome', 'nome')
+ # qs = qs.distinct('municipio__uf__nome', 'nome')
- # del(kwargs['servico'])
+ # del(kwargs['servico'])
qs = qs.filter(**kwargs)
- if 'o' in get:
- qs = query_ordena(qs, get['o'])
+ if "o" in get:
+ qs = query_ordena(qs, get["o"])
return qs
+
# @param qs: queryset
# @param o: (int) number of order field
def query_ordena(qs, o):
from sigi.apps.casas.admin import OrgaoAdmin
+
list_display = OrgaoAdmin.list_display
order_fields = []
- for order_number in o.split('.'):
+ for order_number in o.split("."):
order_number = int(order_number)
- order = ''
+ order = ""
if order_number != abs(order_number):
order_number = abs(order_number)
- order = '-'
+ order = "-"
order_fields.append(order + list_display[order_number - 1])
qs = qs.order_by(*order_fields)
return qs
-
-
# class importa_casas(View):
# errors = []
# total_registros = 0
@@ -405,7 +412,6 @@ def query_ordena(qs, o):
# return len(self.errors) == 0
-
# def get_for_qs(get, qs):
# """
# Verifica atributos do GET e retorna queryset correspondente
@@ -913,110 +919,131 @@ def query_ordena(qs, o):
def resumo_carteira(casas):
regioes = {r[0]: 0 for r in UnidadeFederativa.REGIAO_CHOICES}
- regioes['total'] = 0
+ regioes["total"] = 0
total = regioes.copy()
sem_produto = regioes.copy()
tipos_servico = TipoServico.objects.all()
dados = {ts.id: regioes.copy() for ts in tipos_servico}
- for r in casas.values('municipio__uf__regiao').annotate(
- quantidade=Count('id')).order_by():
- regiao = r['municipio__uf__regiao']
- quantidade = r['quantidade']
+ for r in (
+ casas.values("municipio__uf__regiao")
+ .annotate(quantidade=Count("id"))
+ .order_by()
+ ):
+ regiao = r["municipio__uf__regiao"]
+ quantidade = r["quantidade"]
total[regiao] = quantidade
- total['total'] += quantidade
-
- for r in casas.values('municipio__uf__regiao',
- 'servico__tipo_servico__id').annotate(
- quantidade=Count('id')).order_by():
- regiao = r['municipio__uf__regiao']
- servico = r['servico__tipo_servico__id']
- quantidade = r['quantidade']
+ total["total"] += quantidade
+
+ for r in (
+ casas.values("municipio__uf__regiao", "servico__tipo_servico__id")
+ .annotate(quantidade=Count("id"))
+ .order_by()
+ ):
+ regiao = r["municipio__uf__regiao"]
+ servico = r["servico__tipo_servico__id"]
+ quantidade = r["quantidade"]
if servico is None:
sem_produto[regiao] = quantidade
- sem_produto['total'] += quantidade
+ sem_produto["total"] += quantidade
else:
dados[servico][regiao] = quantidade
- dados[servico]['total'] += quantidade
+ dados[servico]["total"] += quantidade
dados_ocorrencia = {
- 'registradas': regioes.copy(),
- 'pendentes': regioes.copy(),
- 'sem': regioes.copy(),
- 'media': regioes.copy(),
+ "registradas": regioes.copy(),
+ "pendentes": regioes.copy(),
+ "sem": regioes.copy(),
+ "media": regioes.copy(),
}
- for r in casas.values('ocorrencia__status',
- 'municipio__uf__regiao').annotate(
- quantidade=Count('id')).order_by():
- status = r['ocorrencia__status']
- regiao = r['municipio__uf__regiao']
- quantidade = r['quantidade']
+ for r in (
+ casas.values("ocorrencia__status", "municipio__uf__regiao")
+ .annotate(quantidade=Count("id"))
+ .order_by()
+ ):
+ status = r["ocorrencia__status"]
+ regiao = r["municipio__uf__regiao"]
+ quantidade = r["quantidade"]
if status is None:
- dados_ocorrencia['sem'][regiao] += quantidade
- dados_ocorrencia['sem']['total'] += quantidade
+ dados_ocorrencia["sem"][regiao] += quantidade
+ dados_ocorrencia["sem"]["total"] += quantidade
else:
- dados_ocorrencia['registradas'][regiao] += quantidade
- dados_ocorrencia['registradas']['total'] += quantidade
+ dados_ocorrencia["registradas"][regiao] += quantidade
+ dados_ocorrencia["registradas"]["total"] += quantidade
if status in [Ocorrencia.STATUS_ABERTO, Ocorrencia.STATUS_REABERTO]:
- dados_ocorrencia['pendentes'][regiao] += quantidade
- dados_ocorrencia['pendentes']['total'] += quantidade
+ dados_ocorrencia["pendentes"][regiao] += quantidade
+ dados_ocorrencia["pendentes"]["total"] += quantidade
for r in regioes:
- if (total[r] - dados_ocorrencia['sem'][r]) == 0:
- dados_ocorrencia['media'][r] = 0
+ if (total[r] - dados_ocorrencia["sem"][r]) == 0:
+ dados_ocorrencia["media"][r] = 0
else:
- dados_ocorrencia['media'][r] = (
- 1.0 * dados_ocorrencia['registradas'][r] /
- (total[r] - dados_ocorrencia['sem'][r])
+ dados_ocorrencia["media"][r] = (
+ 1.0
+ * dados_ocorrencia["registradas"][r]
+ / (total[r] - dados_ocorrencia["sem"][r])
)
resumo = [
- [_("Item"), _("Total nacional")] +
- [r[1] for r in UnidadeFederativa.REGIAO_CHOICES]
+ [_("Item"), _("Total nacional")]
+ + [r[1] for r in UnidadeFederativa.REGIAO_CHOICES]
]
resumo.append(
- [_("Casas em sua carteira"), total['total']] +
- [total[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
+ [_("Casas em sua carteira"), total["total"]]
+ + [total[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
)
- resumo.append({'subtitle': _("Uso dos produtos Interlegis")})
+ resumo.append({"subtitle": _("Uso dos produtos Interlegis")})
resumo.append(
- [_("Casas sem nenhum produto"), sem_produto['total']] +
- [sem_produto[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
+ [_("Casas sem nenhum produto"), sem_produto["total"]]
+ + [sem_produto[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
)
resumo.extend(
- [[ts.nome, dados[ts.id]['total']] +
- [dados[ts.id][r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
- for ts in tipos_servico
+ [
+ [ts.nome, dados[ts.id]["total"]]
+ + [dados[ts.id][r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
+ for ts in tipos_servico
]
)
- resumo.append({'subtitle': _("Registros no sistema de ocorrências")})
+ resumo.append({"subtitle": _("Registros no sistema de ocorrências")})
resumo.append(
- [_("Casas que nunca registraram ocorrências"),
- dados_ocorrencia['sem']['total']] +
- [dados_ocorrencia['sem'][r[0]]
- for r in UnidadeFederativa.REGIAO_CHOICES
+ [
+ _("Casas que nunca registraram ocorrências"),
+ dados_ocorrencia["sem"]["total"],
+ ]
+ + [
+ dados_ocorrencia["sem"][r[0]]
+ for r in UnidadeFederativa.REGIAO_CHOICES
]
)
resumo.append(
- [_("Total de ocorrências registradas"),
- dados_ocorrencia['registradas']['total']] +
- [dados_ocorrencia['registradas'][r[0]]
- for r in UnidadeFederativa.REGIAO_CHOICES
+ [
+ _("Total de ocorrências registradas"),
+ dados_ocorrencia["registradas"]["total"],
+ ]
+ + [
+ dados_ocorrencia["registradas"][r[0]]
+ for r in UnidadeFederativa.REGIAO_CHOICES
]
)
resumo.append(
- [_("Total de ocorrências pendentes"),
- dados_ocorrencia['pendentes']['total']] +
- [dados_ocorrencia['pendentes'][r[0]]
- for r in UnidadeFederativa.REGIAO_CHOICES
+ [
+ _("Total de ocorrências pendentes"),
+ dados_ocorrencia["pendentes"]["total"],
+ ]
+ + [
+ dados_ocorrencia["pendentes"][r[0]]
+ for r in UnidadeFederativa.REGIAO_CHOICES
]
)
resumo.append(
- [_("Média de ocorrências por casa"),
- round(dados_ocorrencia['media']['total'], 2)] +
- [round(dados_ocorrencia['media'][r[0]], 2)
- for r in UnidadeFederativa.REGIAO_CHOICES
+ [
+ _("Média de ocorrências por casa"),
+ round(dados_ocorrencia["media"]["total"], 2),
+ ]
+ + [
+ round(dados_ocorrencia["media"][r[0]], 2)
+ for r in UnidadeFederativa.REGIAO_CHOICES
]
)
@@ -1024,84 +1051,84 @@ def resumo_carteira(casas):
def casas_carteira(request, casas, context):
- servicos = request.GET.getlist('servico')
- sigla_regiao = request.GET.get('r', None)
- sigla_uf = request.GET.get('uf', None)
- meso_id = request.GET.get('meso', None)
- micro_id = request.GET.get('micro', None)
- servicos = request.GET.getlist('servico')
- tipos_servico = context['servicos']
+ servicos = request.GET.getlist("servico")
+ sigla_regiao = request.GET.get("r", None)
+ sigla_uf = request.GET.get("uf", None)
+ meso_id = request.GET.get("meso", None)
+ micro_id = request.GET.get("micro", None)
+ servicos = request.GET.getlist("servico")
+ tipos_servico = context["servicos"]
- context['qs_regiao'] = ''
+ context["qs_regiao"] = ""
if micro_id is not None:
- context['micro'] = get_object_or_404(Microrregiao, pk=micro_id)
- context['qs_regiao'] = 'micro=%s' % micro_id
- context['meso'] = context['micro'].mesorregiao
- context['uf'] = context['meso'].uf
- context['regiao'] = context['uf'].regiao
- casas = casas.filter(municipio__microrregiao=context['micro'])
+ context["micro"] = get_object_or_404(Microrregiao, pk=micro_id)
+ context["qs_regiao"] = "micro=%s" % micro_id
+ context["meso"] = context["micro"].mesorregiao
+ context["uf"] = context["meso"].uf
+ context["regiao"] = context["uf"].regiao
+ casas = casas.filter(municipio__microrregiao=context["micro"])
elif meso_id is not None:
- context['meso'] = get_object_or_404(Mesorregiao, pk=meso_id)
- context['qs_regiao'] = 'meso=%s' % meso_id
- context['uf'] = context['meso'].uf
- context['regiao'] = context['uf'].regiao
+ context["meso"] = get_object_or_404(Mesorregiao, pk=meso_id)
+ context["qs_regiao"] = "meso=%s" % meso_id
+ context["uf"] = context["meso"].uf
+ context["regiao"] = context["uf"].regiao
casas = casas.filter(
- municipio__microrregiao__mesorregiao=context['meso']
+ municipio__microrregiao__mesorregiao=context["meso"]
)
elif sigla_uf is not None:
- context['uf'] = get_object_or_404(UnidadeFederativa, sigla=sigla_uf)
- context['qs_regiao'] = 'uf=%s' % sigla_uf
- context['regiao'] = context['uf'].regiao
- casas = casas.filter(municipio__uf=context['uf'])
+ context["uf"] = get_object_or_404(UnidadeFederativa, sigla=sigla_uf)
+ context["qs_regiao"] = "uf=%s" % sigla_uf
+ context["regiao"] = context["uf"].regiao
+ casas = casas.filter(municipio__uf=context["uf"])
elif sigla_regiao is not None:
- context['regiao'] = sigla_regiao
- context['qs_regiao'] = 'r=%s' % sigla_regiao
+ context["regiao"] = sigla_regiao
+ context["qs_regiao"] = "r=%s" % sigla_regiao
casas = casas.filter(municipio__uf__regiao=sigla_regiao)
- if 'regiao' in context:
- context['ufs'] = UnidadeFederativa.objects.filter(
- regiao=context['regiao']
+ if "regiao" in context:
+ context["ufs"] = UnidadeFederativa.objects.filter(
+ regiao=context["regiao"]
)
- todos_servicos = ['_none_'] + [s.sigla for s in tipos_servico]
+ todos_servicos = ["_none_"] + [s.sigla for s in tipos_servico]
if not servicos or set(servicos) == set(todos_servicos):
servicos = todos_servicos
- context['qs_servico'] = ''
+ context["qs_servico"] = ""
else:
- if '_none_' in servicos:
+ if "_none_" in servicos:
casas = casas.filter(
Q(servico=None) | Q(servico__tipo_servico__sigla__in=servicos)
)
else:
casas = casas.filter(servico__tipo_servico__sigla__in=servicos)
- casas = casas.distinct('nome', 'municipio__uf')
- context['qs_servico'] = "&".join(['servico=%s' % s for s in servicos])
+ casas = casas.distinct("nome", "municipio__uf")
+ context["qs_servico"] = "&".join(["servico=%s" % s for s in servicos])
- context['servicos_check'] = servicos
+ context["servicos_check"] = servicos
casas = casas.select_related(
- 'municipio',
- 'municipio__uf',
- 'municipio__microrregiao',
- 'municipio__microrregiao__mesorregiao'
- ).prefetch_related('servico_set')
+ "municipio",
+ "municipio__uf",
+ "municipio__microrregiao",
+ "municipio__microrregiao__mesorregiao",
+ ).prefetch_related("servico_set")
return casas, context
@login_required
def painel_relacionamento(request):
- page = request.GET.get('page', 1)
- snippet = request.GET.get('snippet', '')
- seletor = request.GET.get('s', None)
- servidor = request.GET.get('servidor', None)
- fmt = request.GET.get('f', 'html')
+ page = request.GET.get("page", 1)
+ snippet = request.GET.get("snippet", "")
+ seletor = request.GET.get("s", None)
+ servidor = request.GET.get("servidor", None)
+ fmt = request.GET.get("f", "html")
if servidor is None:
gerente = request.user.servidor
- elif servidor == '_all':
+ elif servidor == "_all":
gerente = None
else:
gerente = get_object_or_404(Servidor, pk=servidor)
@@ -1117,59 +1144,73 @@ def painel_relacionamento(request):
regioes = UnidadeFederativa.REGIAO_CHOICES
context = {
- 'seletor': seletor,
- 'snippet': snippet,
- 'regioes': regioes,
- 'servicos': tipos_servico,
- 'gerentes': Servidor.objects.exclude(casas_que_gerencia=None),
- 'gerente': gerente,
- 'qs_servidor': ('servidor=%s' % gerente.pk) if gerente else '',
+ "seletor": seletor,
+ "snippet": snippet,
+ "regioes": regioes,
+ "servicos": tipos_servico,
+ "gerentes": Servidor.objects.exclude(casas_que_gerencia=None),
+ "gerente": gerente,
+ "qs_servidor": ("servidor=%s" % gerente.pk) if gerente else "",
}
- if snippet != 'lista':
- context['resumo'] = resumo_carteira(casas)
+ if snippet != "lista":
+ context["resumo"] = resumo_carteira(casas)
- if snippet != 'resumo':
+ if snippet != "resumo":
casas, context = casas_carteira(request, casas, context)
paginator = Paginator(casas, 30)
try:
pagina = paginator.page(page)
except (EmptyPage, InvalidPage):
pagina = paginator.page(paginator.num_pages)
- context['page_obj'] = pagina
+ context["page_obj"] = pagina
- if snippet == 'lista':
- if fmt == 'csv':
- response = HttpResponse(content_type='text/csv')
- response['Content-Disposition'] = 'attachment; filename=casas.csv'
+ if snippet == "lista":
+ if fmt == "csv":
+ response = HttpResponse(content_type="text/csv")
+ response["Content-Disposition"] = "attachment; filename=casas.csv"
writer = csv.writer(response)
- writer.writerow([_("Casa legislativa"), _("Região"), _("Estado"),
- _("Mesorregião"), _("Microrregião"),
- _("Gerentes Interlegis"), _("Serviços"),])
+ writer.writerow(
+ [
+ _("Casa legislativa"),
+ _("Região"),
+ _("Estado"),
+ _("Mesorregião"),
+ _("Microrregião"),
+ _("Gerentes Interlegis"),
+ _("Serviços"),
+ ]
+ )
for c in casas:
- writer.writerow([
- c.nome,
- c.municipio.uf.get_regiao_display(),
- c.municipio.uf.sigla,
- c.municipio.microrregiao.mesorregiao.nome,
- c.municipio.microrregiao.nome,
- c.lista_gerentes(fmt='lista'),
- (", ".join(
- [s.tipo_servico.nome for s in c.servico_set.filter(
- data_desativacao__isnull=True)
- ])
- ),
- ])
+ writer.writerow(
+ [
+ c.nome,
+ c.municipio.uf.get_regiao_display(),
+ c.municipio.uf.sigla,
+ c.municipio.microrregiao.mesorregiao.nome,
+ c.municipio.microrregiao.nome,
+ c.lista_gerentes(fmt="lista"),
+ (
+ ", ".join(
+ [
+ s.tipo_servico.nome
+ for s in c.servico_set.filter(
+ data_desativacao__isnull=True
+ )
+ ]
+ )
+ ),
+ ]
+ )
return response
return render(
- request,
- 'casas/lista_casas_carteira_snippet.html',
- context
+ request, "casas/lista_casas_carteira_snippet.html", context
)
- if snippet == 'resumo':
- return render(request, 'casas/resumo_carteira_snippet.html', context)
+ if snippet == "resumo":
+ return render(request, "casas/resumo_carteira_snippet.html", context)
+
+ return render(request, "casas/painel.html", context)
- return render(request, 'casas/painel.html', context)
# @login_required
# def gerentes_interlegis(request):
diff --git a/sigi/apps/contatos/admin.py b/sigi/apps/contatos/admin.py
index c20dc24..f9d0649 100644
--- a/sigi/apps/contatos/admin.py
+++ b/sigi/apps/contatos/admin.py
@@ -2,74 +2,130 @@ from django.contrib import admin
from django.utils.translation import gettext as _
from sigi.apps.utils.filters import RangeFilter
-from sigi.apps.contatos.models import (UnidadeFederativa, Mesorregiao,
- Microrregiao, Municipio, Telefone,
- Contato)
+from sigi.apps.contatos.models import (
+ UnidadeFederativa,
+ Mesorregiao,
+ Microrregiao,
+ Municipio,
+ Telefone,
+ Contato,
+)
from sigi.apps.utils import queryset_ascii
class MesorregiaoInline(admin.TabularInline):
model = Mesorregiao
+
class MicrorregiaoInline(admin.TabularInline):
model = Microrregiao
+
@admin.register(UnidadeFederativa)
class UnidadeFederativaAdmin(admin.ModelAdmin):
actions = None
- list_display = ('codigo_ibge', 'nome', 'sigla', 'regiao', 'populacao')
- list_display_links = ('codigo_ibge', 'nome')
- list_filter = ('regiao', ('populacao', RangeFilter),)
- search_fields = ('search_text', 'codigo_ibge', 'sigla', 'regiao')
+ list_display = ("codigo_ibge", "nome", "sigla", "regiao", "populacao")
+ list_display_links = ("codigo_ibge", "nome")
+ list_filter = (
+ "regiao",
+ ("populacao", RangeFilter),
+ )
+ search_fields = ("search_text", "codigo_ibge", "sigla", "regiao")
get_queryset = queryset_ascii
- inlines = (MesorregiaoInline, )
+ inlines = (MesorregiaoInline,)
+
@admin.register(Mesorregiao)
class MesorregiaoAdmin(admin.ModelAdmin):
actions = None
- list_display = ('codigo_ibge', 'uf', 'nome')
- list_display_links = ('codigo_ibge', 'nome')
- list_filter = ('uf',)
- search_fields = ('uf__search_text', 'search_text', 'codigo_ibge',
- 'uf__sigla')
+ list_display = ("codigo_ibge", "uf", "nome")
+ list_display_links = ("codigo_ibge", "nome")
+ list_filter = ("uf",)
+ search_fields = (
+ "uf__search_text",
+ "search_text",
+ "codigo_ibge",
+ "uf__sigla",
+ )
get_queryset = queryset_ascii
inlines = (MicrorregiaoInline,)
+
@admin.register(Municipio)
class MunicipioAdmin(admin.ModelAdmin):
actions = None
- list_display = ('codigo_ibge', 'codigo_tse', 'nome', 'uf', 'is_capital',
- 'populacao', 'is_polo', 'idh', 'pib_ano', 'pib_total',
- 'pib_percapita')
- list_display_links = ('codigo_ibge', 'codigo_tse', 'nome')
- list_filter = ('is_capital', 'is_polo', ('idh', RangeFilter),
- ('populacao', RangeFilter), 'uf__regiao', 'uf', )
+ list_display = (
+ "codigo_ibge",
+ "codigo_tse",
+ "nome",
+ "uf",
+ "is_capital",
+ "populacao",
+ "is_polo",
+ "idh",
+ "pib_ano",
+ "pib_total",
+ "pib_percapita",
+ )
+ list_display_links = ("codigo_ibge", "codigo_tse", "nome")
+ list_filter = (
+ "is_capital",
+ "is_polo",
+ ("idh", RangeFilter),
+ ("populacao", RangeFilter),
+ "uf__regiao",
+ "uf",
+ )
get_queryset = queryset_ascii
fieldsets = (
- (None, {
- 'fields': ('codigo_ibge', 'codigo_tse', 'nome', 'data_criacao',
- 'uf', 'microrregiao', 'is_capital', 'populacao',
- 'is_polo', 'idh', 'pib_ano', 'pib_total',
- 'pib_percapita')
- }),
- (_('Posição geográfica'), {
- 'fields': ('latitude', 'longitude'),
- }),
+ (
+ None,
+ {
+ "fields": (
+ "codigo_ibge",
+ "codigo_tse",
+ "nome",
+ "data_criacao",
+ "uf",
+ "microrregiao",
+ "is_capital",
+ "populacao",
+ "is_polo",
+ "idh",
+ "pib_ano",
+ "pib_total",
+ "pib_percapita",
+ )
+ },
+ ),
+ (
+ _("Posição geográfica"),
+ {
+ "fields": ("latitude", "longitude"),
+ },
+ ),
)
- search_fields = ('search_text', 'codigo_ibge', 'codigo_tse', 'uf__sigla')
+ search_fields = ("search_text", "codigo_ibge", "codigo_tse", "uf__sigla")
+
@admin.register(Telefone)
class TelefoneAdmin(admin.ModelAdmin):
- list_display = ('numero', 'tipo', 'nota')
- list_display_links = ('numero',)
- list_filter = ('tipo',)
- radio_fields = {'tipo': admin.VERTICAL}
- search_fields = ('numero', 'tipo', 'nota')
+ list_display = ("numero", "tipo", "nota")
+ list_display_links = ("numero",)
+ list_filter = ("tipo",)
+ radio_fields = {"tipo": admin.VERTICAL}
+ search_fields = ("numero", "tipo", "nota")
+
@admin.register(Contato)
class ContatoAdmin(admin.ModelAdmin):
- list_display = ('nome', 'nota', 'email', 'municipio')
- list_display_links = ('nome',)
- list_filter = ('nome',)
- search_fields = ('nome', 'nota', 'email', 'municipio__nome',
- 'municipio__uf__nome')
+ list_display = ("nome", "nota", "email", "municipio")
+ list_display_links = ("nome",)
+ list_filter = ("nome",)
+ search_fields = (
+ "nome",
+ "nota",
+ "email",
+ "municipio__nome",
+ "municipio__uf__nome",
+ )
diff --git a/sigi/apps/contatos/apps.py b/sigi/apps/contatos/apps.py
index 2dd9391..60eed26 100644
--- a/sigi/apps/contatos/apps.py
+++ b/sigi/apps/contatos/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class ContatosConfig(AppConfig):
- name = 'sigi.apps.contatos'
- verbose_name = _('contatos')
+ name = "sigi.apps.contatos"
+ verbose_name = _("contatos")
diff --git a/sigi/apps/contatos/management/commands/importa_mesomicro.py b/sigi/apps/contatos/management/commands/importa_mesomicro.py
index 1aa0ae0..5d64036 100644
--- a/sigi/apps/contatos/management/commands/importa_mesomicro.py
+++ b/sigi/apps/contatos/management/commands/importa_mesomicro.py
@@ -24,7 +24,13 @@
import csv
import os
from django.core.management.base import BaseCommand, CommandError
-from sigi.apps.contatos.models import Municipio, UnidadeFederativa, Mesorregiao, Microrregiao
+from sigi.apps.contatos.models import (
+ Municipio,
+ UnidadeFederativa,
+ Mesorregiao,
+ Microrregiao,
+)
+
class Command(BaseCommand):
args = "data_file.csv"
@@ -40,8 +46,14 @@ class Command(BaseCommand):
* Os nomes dos campos devem ser grafados exatamente como descrito."""
- campos = {'cod_uf', 'cod_mesorregiao', 'nome_mesorregiao', 'cod_microrregiao',
- 'nome_microrregiao', 'cod_municipio'}
+ campos = {
+ "cod_uf",
+ "cod_mesorregiao",
+ "nome_mesorregiao",
+ "cod_microrregiao",
+ "nome_microrregiao",
+ "cod_municipio",
+ }
def handle(self, *args, **options):
if len(args) != 1:
@@ -50,51 +62,86 @@ class Command(BaseCommand):
file_name = args[0]
if not os.path.isfile(file_name):
- raise CommandError("Arquivo %s não encontrado" % [file_name,])
-
- with open(file_name, 'rb') as csvfile:
+ raise CommandError(
+ "Arquivo %s não encontrado"
+ % [
+ file_name,
+ ]
+ )
+
+ with open(file_name, "rb") as csvfile:
reader = csv.DictReader(csvfile)
if not self.campos.issubset(reader.fieldnames):
- raise CommandError("O arquivo não possui todos os campos obrigatórios")
+ raise CommandError(
+ "O arquivo não possui todos os campos obrigatórios"
+ )
erros = 0
for reg in reader:
try:
- uf = UnidadeFederativa.objects.get(codigo_ibge=reg['cod_uf'])
+ uf = UnidadeFederativa.objects.get(
+ codigo_ibge=reg["cod_uf"]
+ )
except UnidadeFederativa.DoesNotExist:
- self.stdout.write("(Linha %s): não existe UF com código IBGE '%s'" %
- (reader.line_num, reg['cod_uf'],))
+ self.stdout.write(
+ "(Linha %s): não existe UF com código IBGE '%s'"
+ % (
+ reader.line_num,
+ reg["cod_uf"],
+ )
+ )
erros = erros + 1
continue
try:
- municipio = Municipio.objects.get(codigo_ibge=reg['cod_municipio'])
+ municipio = Municipio.objects.get(
+ codigo_ibge=reg["cod_municipio"]
+ )
except Municipio.DoesNotExist:
- self.stdout.write("(Linha %s): não existe Município com código IBGE '%s'" %
- (reader.line_num, reg['cod_municipio'],))
+ self.stdout.write(
+ "(Linha %s): não existe Município com código IBGE '%s'"
+ % (
+ reader.line_num,
+ reg["cod_municipio"],
+ )
+ )
erros = erros + 1
continue
- cod_meso = reg['cod_uf'] + reg['cod_mesorregiao']
- cod_micro = cod_meso + reg['cod_microrregiao']
+ cod_meso = reg["cod_uf"] + reg["cod_mesorregiao"]
+ cod_micro = cod_meso + reg["cod_microrregiao"]
if Mesorregiao.objects.filter(codigo_ibge=cod_meso).exists():
meso = Mesorregiao.objects.get(codigo_ibge=cod_meso)
else:
- meso = Mesorregiao(codigo_ibge=cod_meso, uf=uf, nome=reg['nome_mesorregiao'])
- meso.nome = reg['nome_mesorregiao']
+ meso = Mesorregiao(
+ codigo_ibge=cod_meso,
+ uf=uf,
+ nome=reg["nome_mesorregiao"],
+ )
+ meso.nome = reg["nome_mesorregiao"]
meso.save()
if Microrregiao.objects.filter(codigo_ibge=cod_micro).exists():
micro = Microrregiao.objects.get(codigo_ibge=cod_micro)
else:
- micro = Microrregiao(codigo_ibge=cod_micro, mesorregiao=meso, nome=reg['nome_microrregiao'])
- micro.nome = reg['nome_microrregiao']
+ micro = Microrregiao(
+ codigo_ibge=cod_micro,
+ mesorregiao=meso,
+ nome=reg["nome_microrregiao"],
+ )
+ micro.nome = reg["nome_microrregiao"]
micro.save()
municipio.microrregiao = micro
municipio.save()
- self.stdout.write("Importação concluída. %s erros em %s linhas" % (erros, reader.line_num,))
\ No newline at end of file
+ self.stdout.write(
+ "Importação concluída. %s erros em %s linhas"
+ % (
+ erros,
+ reader.line_num,
+ )
+ )
diff --git a/sigi/apps/contatos/migrations/0001_initial.py b/sigi/apps/contatos/migrations/0001_initial.py
index 6c7c274..3048369 100644
--- a/sigi/apps/contatos/migrations/0001_initial.py
+++ b/sigi/apps/contatos/migrations/0001_initial.py
@@ -8,128 +8,430 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('contenttypes', '0001_initial'),
+ ("contenttypes", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Contato',
+ name="Contato",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=120, verbose_name='nome completo')),
- ('nota', models.CharField(max_length=70, blank=True)),
- ('email', models.EmailField(max_length=75, verbose_name='e-mail', blank=True)),
- ('object_id', models.PositiveIntegerField()),
- ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=120, verbose_name="nome completo"
+ ),
+ ),
+ ("nota", models.CharField(max_length=70, blank=True)),
+ (
+ "email",
+ models.EmailField(
+ max_length=75, verbose_name="e-mail", blank=True
+ ),
+ ),
+ ("object_id", models.PositiveIntegerField()),
+ (
+ "content_type",
+ models.ForeignKey(
+ to="contenttypes.ContentType", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'contato Interlegis',
- 'verbose_name_plural': 'contatos Interlegis',
+ "ordering": ("nome",),
+ "verbose_name": "contato Interlegis",
+ "verbose_name_plural": "contatos Interlegis",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Endereco',
+ name="Endereco",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('tipo', models.CharField(max_length=15, choices=[('aeroporto', 'Aeroporto'), ('alameda', 'Alameda'), ('area', '\xc1rea'), ('avenida', 'Avenida'), ('campo', 'Campo'), ('chacara', 'Ch\xe1cara'), ('colonia', 'Col\xf4nia'), ('condominio', 'Condom\xednio'), ('conjunto', 'Conjunto'), ('distrito', 'Distrito'), ('esplanada', 'Esplanada'), ('estacao', 'Esta\xe7\xe3o'), ('estrada', 'Estrada'), ('favela', 'Favela'), ('fazenda', 'Fazenda'), ('feira', 'Feira'), ('jardim', 'Jardim'), ('ladeira', 'Ladeira'), ('lago', 'Lago'), ('lagoa', 'Lagoa'), ('largo', 'Largo'), ('loteamento', 'Loteamento'), ('morro', 'Morro'), ('nucleo', 'N\xfacleo'), ('parque', 'Parque'), ('passarela', 'Passarela'), ('patio', 'P\xe1tio'), ('praca', 'Pra\xe7a'), ('quadra', 'Quadra'), ('recanto', 'Recanto'), ('residencial', 'Residencial'), ('rodovia', 'Rodovia'), ('rua', 'Rua'), ('setor', 'Setor'), ('sitio', 'S\xedtio'), ('travessa', 'Travessa'), ('trecho', 'Trecho'), ('trevo', 'Trevo'), ('vale', 'Vale'), ('vereda', 'Vereda'), ('via', 'Via'), ('viaduto', 'Viaduto'), ('viela', 'Viela'), ('vila', 'Vila'), ('outro', 'Outro')])),
- ('logradouro', models.CharField(max_length=100)),
- ('numero', models.CharField(max_length=15, blank=True)),
- ('complemento', models.CharField(max_length=15, blank=True)),
- ('referencia', models.CharField(max_length=100, blank=True)),
- ('bairro', models.CharField(max_length=100, blank=True)),
- ('cep', models.CharField(help_text='Formato: XXXXX-XXX .', max_length=9, null=True, verbose_name='CEP', blank=True)),
- ('object_id', models.PositiveIntegerField()),
- ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "tipo",
+ models.CharField(
+ max_length=15,
+ choices=[
+ ("aeroporto", "Aeroporto"),
+ ("alameda", "Alameda"),
+ ("area", "\xc1rea"),
+ ("avenida", "Avenida"),
+ ("campo", "Campo"),
+ ("chacara", "Ch\xe1cara"),
+ ("colonia", "Col\xf4nia"),
+ ("condominio", "Condom\xednio"),
+ ("conjunto", "Conjunto"),
+ ("distrito", "Distrito"),
+ ("esplanada", "Esplanada"),
+ ("estacao", "Esta\xe7\xe3o"),
+ ("estrada", "Estrada"),
+ ("favela", "Favela"),
+ ("fazenda", "Fazenda"),
+ ("feira", "Feira"),
+ ("jardim", "Jardim"),
+ ("ladeira", "Ladeira"),
+ ("lago", "Lago"),
+ ("lagoa", "Lagoa"),
+ ("largo", "Largo"),
+ ("loteamento", "Loteamento"),
+ ("morro", "Morro"),
+ ("nucleo", "N\xfacleo"),
+ ("parque", "Parque"),
+ ("passarela", "Passarela"),
+ ("patio", "P\xe1tio"),
+ ("praca", "Pra\xe7a"),
+ ("quadra", "Quadra"),
+ ("recanto", "Recanto"),
+ ("residencial", "Residencial"),
+ ("rodovia", "Rodovia"),
+ ("rua", "Rua"),
+ ("setor", "Setor"),
+ ("sitio", "S\xedtio"),
+ ("travessa", "Travessa"),
+ ("trecho", "Trecho"),
+ ("trevo", "Trevo"),
+ ("vale", "Vale"),
+ ("vereda", "Vereda"),
+ ("via", "Via"),
+ ("viaduto", "Viaduto"),
+ ("viela", "Viela"),
+ ("vila", "Vila"),
+ ("outro", "Outro"),
+ ],
+ ),
+ ),
+ ("logradouro", models.CharField(max_length=100)),
+ ("numero", models.CharField(max_length=15, blank=True)),
+ ("complemento", models.CharField(max_length=15, blank=True)),
+ ("referencia", models.CharField(max_length=100, blank=True)),
+ ("bairro", models.CharField(max_length=100, blank=True)),
+ (
+ "cep",
+ models.CharField(
+ help_text="Formato: XXXXX-XXX .",
+ max_length=9,
+ null=True,
+ verbose_name="CEP",
+ blank=True,
+ ),
+ ),
+ ("object_id", models.PositiveIntegerField()),
+ (
+ "content_type",
+ models.ForeignKey(
+ to="contenttypes.ContentType", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('logradouro', 'numero'),
- 'verbose_name': 'endere\xe7o',
- 'verbose_name_plural': 'endere\xe7os',
+ "ordering": ("logradouro", "numero"),
+ "verbose_name": "endere\xe7o",
+ "verbose_name_plural": "endere\xe7os",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Municipio',
+ name="Municipio",
fields=[
- ('codigo_ibge', models.PositiveIntegerField(help_text='C\xf3digo do munic\xedpio segundo IBGE.', unique=True, serialize=False, verbose_name='c\xf3digo IBGE', primary_key=True)),
- ('codigo_mesorregiao', models.PositiveIntegerField(null=True, verbose_name='c\xf3digo mesorregi\xe3o', blank=True)),
- ('codigo_microrregiao', models.PositiveIntegerField(null=True, verbose_name='c\xf3digo microrregi\xe3o', blank=True)),
- ('codigo_tse', models.PositiveIntegerField(help_text='C\xf3digo do munic\xedpio segundo TSE.', unique=True, null=True, verbose_name='c\xf3digo TSE')),
- ('nome', models.CharField(max_length=50)),
- ('search_text', sigi.apps.utils.SearchField(field_names=['nome', 'uf'], editable=False)),
- ('is_capital', models.BooleanField(default=False, verbose_name='capital')),
- ('populacao', models.PositiveIntegerField(verbose_name='popula\xe7\xe3o')),
- ('is_polo', models.BooleanField(default=False, verbose_name='p\xf3lo')),
- ('data_criacao', models.DateField(null=True, verbose_name='data de cria\xe7\xe3o do munic\xedpio', blank=True)),
- ('latitude', models.DecimalField(help_text='Exemplo: -20,464 .', null=True, max_digits=10, decimal_places=8, blank=True)),
- ('longitude', models.DecimalField(help_text='Exemplo: -45,426 .', null=True, max_digits=11, decimal_places=8, blank=True)),
- ('idh', models.DecimalField(help_text='\xcdndice de desenvolvimento Humano', verbose_name='IDH', max_digits=4, decimal_places=3, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(1)])),
- ('pib_total', models.DecimalField(null=True, verbose_name='PIB total', max_digits=18, decimal_places=3, blank=True)),
- ('pib_percapita', models.DecimalField(null=True, verbose_name='PIB per capita', max_digits=18, decimal_places=3, blank=True)),
- ('pib_ano', models.IntegerField(null=True, verbose_name='Ano de apura\xe7\xe3o do PIB', blank=True)),
+ (
+ "codigo_ibge",
+ models.PositiveIntegerField(
+ help_text="C\xf3digo do munic\xedpio segundo IBGE.",
+ unique=True,
+ serialize=False,
+ verbose_name="c\xf3digo IBGE",
+ primary_key=True,
+ ),
+ ),
+ (
+ "codigo_mesorregiao",
+ models.PositiveIntegerField(
+ null=True,
+ verbose_name="c\xf3digo mesorregi\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "codigo_microrregiao",
+ models.PositiveIntegerField(
+ null=True,
+ verbose_name="c\xf3digo microrregi\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "codigo_tse",
+ models.PositiveIntegerField(
+ help_text="C\xf3digo do munic\xedpio segundo TSE.",
+ unique=True,
+ null=True,
+ verbose_name="c\xf3digo TSE",
+ ),
+ ),
+ ("nome", models.CharField(max_length=50)),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["nome", "uf"], editable=False
+ ),
+ ),
+ (
+ "is_capital",
+ models.BooleanField(default=False, verbose_name="capital"),
+ ),
+ (
+ "populacao",
+ models.PositiveIntegerField(verbose_name="popula\xe7\xe3o"),
+ ),
+ (
+ "is_polo",
+ models.BooleanField(default=False, verbose_name="p\xf3lo"),
+ ),
+ (
+ "data_criacao",
+ models.DateField(
+ null=True,
+ verbose_name="data de cria\xe7\xe3o do munic\xedpio",
+ blank=True,
+ ),
+ ),
+ (
+ "latitude",
+ models.DecimalField(
+ help_text="Exemplo: -20,464 .",
+ null=True,
+ max_digits=10,
+ decimal_places=8,
+ blank=True,
+ ),
+ ),
+ (
+ "longitude",
+ models.DecimalField(
+ help_text="Exemplo: -45,426 .",
+ null=True,
+ max_digits=11,
+ decimal_places=8,
+ blank=True,
+ ),
+ ),
+ (
+ "idh",
+ models.DecimalField(
+ help_text="\xcdndice de desenvolvimento Humano",
+ verbose_name="IDH",
+ max_digits=4,
+ decimal_places=3,
+ validators=[
+ django.core.validators.MinValueValidator(0),
+ django.core.validators.MaxValueValidator(1),
+ ],
+ ),
+ ),
+ (
+ "pib_total",
+ models.DecimalField(
+ null=True,
+ verbose_name="PIB total",
+ max_digits=18,
+ decimal_places=3,
+ blank=True,
+ ),
+ ),
+ (
+ "pib_percapita",
+ models.DecimalField(
+ null=True,
+ verbose_name="PIB per capita",
+ max_digits=18,
+ decimal_places=3,
+ blank=True,
+ ),
+ ),
+ (
+ "pib_ano",
+ models.IntegerField(
+ null=True,
+ verbose_name="Ano de apura\xe7\xe3o do PIB",
+ blank=True,
+ ),
+ ),
],
options={
- 'ordering': ('nome', 'codigo_ibge'),
- 'verbose_name': 'munic\xedpio',
- 'verbose_name_plural': 'munic\xedpios',
+ "ordering": ("nome", "codigo_ibge"),
+ "verbose_name": "munic\xedpio",
+ "verbose_name_plural": "munic\xedpios",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Telefone',
+ name="Telefone",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('numero', models.CharField(help_text='Exemplo: (31)8851-9898 .', max_length=64, verbose_name='n\xfamero')),
- ('tipo', models.CharField(default='I', max_length=1, choices=[('F', 'Fixo'), ('M', 'M\xf3vel'), ('X', 'Fax'), ('I', 'Indefinido')])),
- ('nota', models.CharField(max_length=70, null=True, blank=True)),
- ('ult_alteracao', models.DateTimeField(auto_now=True, verbose_name='\xdaltima altera\xe7\xe3o', null=True)),
- ('object_id', models.PositiveIntegerField()),
- ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "numero",
+ models.CharField(
+ help_text="Exemplo: (31)8851-9898 .",
+ max_length=64,
+ verbose_name="n\xfamero",
+ ),
+ ),
+ (
+ "tipo",
+ models.CharField(
+ default="I",
+ max_length=1,
+ choices=[
+ ("F", "Fixo"),
+ ("M", "M\xf3vel"),
+ ("X", "Fax"),
+ ("I", "Indefinido"),
+ ],
+ ),
+ ),
+ (
+ "nota",
+ models.CharField(max_length=70, null=True, blank=True),
+ ),
+ (
+ "ult_alteracao",
+ models.DateTimeField(
+ auto_now=True,
+ verbose_name="\xdaltima altera\xe7\xe3o",
+ null=True,
+ ),
+ ),
+ ("object_id", models.PositiveIntegerField()),
+ (
+ "content_type",
+ models.ForeignKey(
+ to="contenttypes.ContentType", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('numero',),
+ "ordering": ("numero",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='UnidadeFederativa',
+ name="UnidadeFederativa",
fields=[
- ('codigo_ibge', models.PositiveIntegerField(help_text='C\xf3digo do estado segundo IBGE.', unique=True, serialize=False, verbose_name='c\xf3digo IBGE', primary_key=True)),
- ('nome', models.CharField(max_length=25, verbose_name='Nome UF')),
- ('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)),
- ('sigla', models.CharField(help_text='Exemplo: MG .', unique=True, max_length=2)),
- ('regiao', models.CharField(max_length=2, verbose_name='regi\xe3o', choices=[('SL', 'Sul'), ('SD', 'Sudeste'), ('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte')])),
- ('populacao', models.PositiveIntegerField(verbose_name='popula\xe7\xe3o')),
+ (
+ "codigo_ibge",
+ models.PositiveIntegerField(
+ help_text="C\xf3digo do estado segundo IBGE.",
+ unique=True,
+ serialize=False,
+ verbose_name="c\xf3digo IBGE",
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(max_length=25, verbose_name="Nome UF"),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["nome"], editable=False
+ ),
+ ),
+ (
+ "sigla",
+ models.CharField(
+ help_text="Exemplo: MG .",
+ unique=True,
+ max_length=2,
+ ),
+ ),
+ (
+ "regiao",
+ models.CharField(
+ max_length=2,
+ verbose_name="regi\xe3o",
+ choices=[
+ ("SL", "Sul"),
+ ("SD", "Sudeste"),
+ ("CO", "Centro-Oeste"),
+ ("NE", "Nordeste"),
+ ("NO", "Norte"),
+ ],
+ ),
+ ),
+ (
+ "populacao",
+ models.PositiveIntegerField(verbose_name="popula\xe7\xe3o"),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'Unidade Federativa',
- 'verbose_name_plural': 'Unidades Federativas',
+ "ordering": ("nome",),
+ "verbose_name": "Unidade Federativa",
+ "verbose_name_plural": "Unidades Federativas",
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
- name='telefone',
- unique_together=set([('numero', 'tipo')]),
+ name="telefone",
+ unique_together=set([("numero", "tipo")]),
),
migrations.AddField(
- model_name='municipio',
- name='uf',
- field=models.ForeignKey(verbose_name='UF', to='contatos.UnidadeFederativa', on_delete=models.CASCADE),
+ model_name="municipio",
+ name="uf",
+ field=models.ForeignKey(
+ verbose_name="UF",
+ to="contatos.UnidadeFederativa",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='endereco',
- name='municipio',
- field=models.ForeignKey(verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE),
+ model_name="endereco",
+ name="municipio",
+ field=models.ForeignKey(
+ verbose_name="munic\xedpio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='contato',
- name='municipio',
- field=models.ForeignKey(verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE),
+ model_name="contato",
+ name="municipio",
+ field=models.ForeignKey(
+ verbose_name="munic\xedpio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/contatos/migrations/0002_auto_20151104_0810.py b/sigi/apps/contatos/migrations/0002_auto_20151104_0810.py
index ea8b6fa..e1aaadb 100644
--- a/sigi/apps/contatos/migrations/0002_auto_20151104_0810.py
+++ b/sigi/apps/contatos/migrations/0002_auto_20151104_0810.py
@@ -8,52 +8,108 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0001_initial'),
+ ("contatos", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Mesorregiao',
+ name="Mesorregiao",
fields=[
- ('codigo_ibge', models.PositiveIntegerField(help_text='C\xf3digo da mesorregi\xe3o segundo o IBGE', unique=True, serialize=False, verbose_name='C\xf3digo IBGE', primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome mesorregi\xe3o')),
- ('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)),
- ('uf', models.ForeignKey(verbose_name='UF', to='contatos.UnidadeFederativa', on_delete=models.CASCADE)),
+ (
+ "codigo_ibge",
+ models.PositiveIntegerField(
+ help_text="C\xf3digo da mesorregi\xe3o segundo o IBGE",
+ unique=True,
+ serialize=False,
+ verbose_name="C\xf3digo IBGE",
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=100, verbose_name="Nome mesorregi\xe3o"
+ ),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["nome"], editable=False
+ ),
+ ),
+ (
+ "uf",
+ models.ForeignKey(
+ verbose_name="UF",
+ to="contatos.UnidadeFederativa",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('uf', 'nome'),
- 'verbose_name': 'Mesorregi\xe3o',
- 'verbose_name_plural': 'Mesorregi\xf5es',
+ "ordering": ("uf", "nome"),
+ "verbose_name": "Mesorregi\xe3o",
+ "verbose_name_plural": "Mesorregi\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Microrregiao',
+ name="Microrregiao",
fields=[
- ('codigo_ibge', models.PositiveIntegerField(help_text='C\xf3digo da microrregi\xe3o segundo o IBGE', unique=True, serialize=False, verbose_name='C\xf3digo IBGE', primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome microrregi\xe3o')),
- ('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)),
- ('mesorregiao', models.ForeignKey(to='contatos.Mesorregiao', on_delete=models.CASCADE)),
+ (
+ "codigo_ibge",
+ models.PositiveIntegerField(
+ help_text="C\xf3digo da microrregi\xe3o segundo o IBGE",
+ unique=True,
+ serialize=False,
+ verbose_name="C\xf3digo IBGE",
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=100, verbose_name="Nome microrregi\xe3o"
+ ),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["nome"], editable=False
+ ),
+ ),
+ (
+ "mesorregiao",
+ models.ForeignKey(
+ to="contatos.Mesorregiao", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('mesorregiao', 'nome'),
- 'verbose_name': 'Microrregi\xe3o',
- 'verbose_name_plural': 'Microrregi\xf5es',
+ "ordering": ("mesorregiao", "nome"),
+ "verbose_name": "Microrregi\xe3o",
+ "verbose_name_plural": "Microrregi\xf5es",
},
bases=(models.Model,),
),
migrations.RemoveField(
- model_name='municipio',
- name='codigo_mesorregiao',
+ model_name="municipio",
+ name="codigo_mesorregiao",
),
migrations.RemoveField(
- model_name='municipio',
- name='codigo_microrregiao',
+ model_name="municipio",
+ name="codigo_microrregiao",
),
migrations.AddField(
- model_name='municipio',
- name='microrregiao',
- field=models.ForeignKey(verbose_name='Microrregi\xe3o', blank=True, to='contatos.Microrregiao', null=True, on_delete=models.CASCADE),
+ model_name="municipio",
+ name="microrregiao",
+ field=models.ForeignKey(
+ verbose_name="Microrregi\xe3o",
+ blank=True,
+ to="contatos.Microrregiao",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/contatos/migrations/0003_auto_20210416_0841.py b/sigi/apps/contatos/migrations/0003_auto_20210416_0841.py
index ac856f1..3402c25 100644
--- a/sigi/apps/contatos/migrations/0003_auto_20210416_0841.py
+++ b/sigi/apps/contatos/migrations/0003_auto_20210416_0841.py
@@ -8,32 +8,54 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0002_auto_20151104_0810'),
+ ("contatos", "0002_auto_20151104_0810"),
]
operations = [
migrations.AlterField(
- model_name='contato',
- name='municipio',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True),
+ model_name="contato",
+ name="municipio",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="munic\xedpio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='endereco',
- name='municipio',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True),
+ model_name="endereco",
+ name="municipio",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="munic\xedpio",
+ blank=True,
+ to="contatos.Municipio",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='municipio',
- name='microrregiao',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Microrregi\xe3o', blank=True, to='contatos.Microrregiao', null=True),
+ model_name="municipio",
+ name="microrregiao",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Microrregi\xe3o",
+ blank=True,
+ to="contatos.Microrregiao",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='municipio',
- name='uf',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='UF', to='contatos.UnidadeFederativa'),
+ model_name="municipio",
+ name="uf",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="UF",
+ to="contatos.UnidadeFederativa",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/contatos/migrations/0004_auto_20210611_0946.py b/sigi/apps/contatos/migrations/0004_auto_20210611_0946.py
index 81c63d2..4af2062 100644
--- a/sigi/apps/contatos/migrations/0004_auto_20210611_0946.py
+++ b/sigi/apps/contatos/migrations/0004_auto_20210611_0946.py
@@ -7,18 +7,32 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0003_auto_20210416_0841'),
+ ("contatos", "0003_auto_20210416_0841"),
]
operations = [
migrations.AlterModelOptions(
- name='microrregiao',
- options={'ordering': ('nome',), 'verbose_name': 'Microrregi\xe3o', 'verbose_name_plural': 'Microrregi\xf5es'},
+ name="microrregiao",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "Microrregi\xe3o",
+ "verbose_name_plural": "Microrregi\xf5es",
+ },
),
migrations.AlterField(
- model_name='unidadefederativa',
- name='regiao',
- field=models.CharField(max_length=2, verbose_name='regi\xe3o', choices=[('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte'), ('SD', 'Sudeste'), ('SL', 'Sul')]),
+ model_name="unidadefederativa",
+ name="regiao",
+ field=models.CharField(
+ max_length=2,
+ verbose_name="regi\xe3o",
+ choices=[
+ ("CO", "Centro-Oeste"),
+ ("NE", "Nordeste"),
+ ("NO", "Norte"),
+ ("SD", "Sudeste"),
+ ("SL", "Sul"),
+ ],
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/contatos/migrations/0005_alter_mesorregiao_options_alter_microrregiao_options_and_more.py b/sigi/apps/contatos/migrations/0005_alter_mesorregiao_options_alter_microrregiao_options_and_more.py
index 941d434..113e2b9 100644
--- a/sigi/apps/contatos/migrations/0005_alter_mesorregiao_options_alter_microrregiao_options_and_more.py
+++ b/sigi/apps/contatos/migrations/0005_alter_mesorregiao_options_alter_microrregiao_options_and_more.py
@@ -8,126 +8,274 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('contatos', '0004_auto_20210611_0946'),
+ ("contatos", "0004_auto_20210611_0946"),
]
operations = [
migrations.AlterModelOptions(
- name='mesorregiao',
- options={'ordering': ('uf', 'nome'), 'verbose_name': ('mesorregião',), 'verbose_name_plural': 'mesorregiões'},
+ name="mesorregiao",
+ options={
+ "ordering": ("uf", "nome"),
+ "verbose_name": ("mesorregião",),
+ "verbose_name_plural": "mesorregiões",
+ },
),
migrations.AlterModelOptions(
- name='microrregiao',
- options={'ordering': ('nome',), 'verbose_name': 'microrregião', 'verbose_name_plural': 'microrregiões'},
+ name="microrregiao",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "microrregião",
+ "verbose_name_plural": "microrregiões",
+ },
),
migrations.AlterField(
- model_name='contato',
- name='email',
- field=models.EmailField(blank=True, max_length=254, verbose_name='e-mail'),
+ model_name="contato",
+ name="email",
+ field=models.EmailField(
+ blank=True, max_length=254, verbose_name="e-mail"
+ ),
),
migrations.AlterField(
- model_name='contato',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="contato",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='endereco',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="endereco",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='endereco',
- name='logradouro',
- field=models.CharField(max_length=100, verbose_name='logradouro'),
+ model_name="endereco",
+ name="logradouro",
+ field=models.CharField(max_length=100, verbose_name="logradouro"),
),
migrations.AlterField(
- model_name='endereco',
- name='tipo',
- field=models.CharField(choices=[('aeroporto', 'Aeroporto'), ('alameda', 'Alameda'), ('area', 'Área'), ('avenida', 'Avenida'), ('campo', 'Campo'), ('chacara', 'Chácara'), ('colonia', 'Colônia'), ('condominio', 'Condomínio'), ('conjunto', 'Conjunto'), ('distrito', 'Distrito'), ('esplanada', 'Esplanada'), ('estacao', 'Estação'), ('estrada', 'Estrada'), ('favela', 'Favela'), ('fazenda', 'Fazenda'), ('feira', 'Feira'), ('jardim', 'Jardim'), ('ladeira', 'Ladeira'), ('lago', 'Lago'), ('lagoa', 'Lagoa'), ('largo', 'Largo'), ('loteamento', 'Loteamento'), ('morro', 'Morro'), ('nucleo', 'Núcleo'), ('parque', 'Parque'), ('passarela', 'Passarela'), ('patio', 'Pátio'), ('praca', 'Praça'), ('quadra', 'Quadra'), ('recanto', 'Recanto'), ('residencial', 'Residencial'), ('rodovia', 'Rodovia'), ('rua', 'Rua'), ('setor', 'Setor'), ('sitio', 'Sítio'), ('travessa', 'Travessa'), ('trecho', 'Trecho'), ('trevo', 'Trevo'), ('vale', 'Vale'), ('vereda', 'Vereda'), ('via', 'Via'), ('viaduto', 'Viaduto'), ('viela', 'Viela'), ('vila', 'Vila'), ('outro', 'Outro')], max_length=15, verbose_name='tipo'),
+ model_name="endereco",
+ name="tipo",
+ field=models.CharField(
+ choices=[
+ ("aeroporto", "Aeroporto"),
+ ("alameda", "Alameda"),
+ ("area", "Área"),
+ ("avenida", "Avenida"),
+ ("campo", "Campo"),
+ ("chacara", "Chácara"),
+ ("colonia", "Colônia"),
+ ("condominio", "Condomínio"),
+ ("conjunto", "Conjunto"),
+ ("distrito", "Distrito"),
+ ("esplanada", "Esplanada"),
+ ("estacao", "Estação"),
+ ("estrada", "Estrada"),
+ ("favela", "Favela"),
+ ("fazenda", "Fazenda"),
+ ("feira", "Feira"),
+ ("jardim", "Jardim"),
+ ("ladeira", "Ladeira"),
+ ("lago", "Lago"),
+ ("lagoa", "Lagoa"),
+ ("largo", "Largo"),
+ ("loteamento", "Loteamento"),
+ ("morro", "Morro"),
+ ("nucleo", "Núcleo"),
+ ("parque", "Parque"),
+ ("passarela", "Passarela"),
+ ("patio", "Pátio"),
+ ("praca", "Praça"),
+ ("quadra", "Quadra"),
+ ("recanto", "Recanto"),
+ ("residencial", "Residencial"),
+ ("rodovia", "Rodovia"),
+ ("rua", "Rua"),
+ ("setor", "Setor"),
+ ("sitio", "Sítio"),
+ ("travessa", "Travessa"),
+ ("trecho", "Trecho"),
+ ("trevo", "Trevo"),
+ ("vale", "Vale"),
+ ("vereda", "Vereda"),
+ ("via", "Via"),
+ ("viaduto", "Viaduto"),
+ ("viela", "Viela"),
+ ("vila", "Vila"),
+ ("outro", "Outro"),
+ ],
+ max_length=15,
+ verbose_name="tipo",
+ ),
),
migrations.AlterField(
- model_name='mesorregiao',
- name='codigo_ibge',
- field=models.PositiveIntegerField(help_text='Código da mesorregião segundo o IBGE', primary_key=True, serialize=False, unique=True, verbose_name='código IBGE'),
+ model_name="mesorregiao",
+ name="codigo_ibge",
+ field=models.PositiveIntegerField(
+ help_text="Código da mesorregião segundo o IBGE",
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ verbose_name="código IBGE",
+ ),
),
migrations.AlterField(
- model_name='mesorregiao',
- name='nome',
- field=models.CharField(max_length=100, verbose_name='nome mesorregião'),
+ model_name="mesorregiao",
+ name="nome",
+ field=models.CharField(
+ max_length=100, verbose_name="nome mesorregião"
+ ),
),
migrations.AlterField(
- model_name='mesorregiao',
- name='search_text',
- field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']),
+ model_name="mesorregiao",
+ name="search_text",
+ field=sigi.apps.utils.SearchField(
+ editable=False, field_names=["nome"]
+ ),
),
migrations.AlterField(
- model_name='microrregiao',
- name='codigo_ibge',
- field=models.PositiveIntegerField(help_text='Código da microrregião segundo o IBGE', primary_key=True, serialize=False, unique=True, verbose_name='código IBGE'),
+ model_name="microrregiao",
+ name="codigo_ibge",
+ field=models.PositiveIntegerField(
+ help_text="Código da microrregião segundo o IBGE",
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ verbose_name="código IBGE",
+ ),
),
migrations.AlterField(
- model_name='microrregiao',
- name='mesorregiao',
- field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contatos.mesorregiao', verbose_name='mesorregião'),
+ model_name="microrregiao",
+ name="mesorregiao",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="contatos.mesorregiao",
+ verbose_name="mesorregião",
+ ),
),
migrations.AlterField(
- model_name='microrregiao',
- name='nome',
- field=models.CharField(max_length=100, verbose_name='nome microrregião'),
+ model_name="microrregiao",
+ name="nome",
+ field=models.CharField(
+ max_length=100, verbose_name="nome microrregião"
+ ),
),
migrations.AlterField(
- model_name='microrregiao',
- name='search_text',
- field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']),
+ model_name="microrregiao",
+ name="search_text",
+ field=sigi.apps.utils.SearchField(
+ editable=False, field_names=["nome"]
+ ),
),
migrations.AlterField(
- model_name='municipio',
- name='latitude',
- field=models.DecimalField(blank=True, decimal_places=8, help_text='Exemplo: -20,464 .', max_digits=10, null=True, verbose_name='latitude'),
+ model_name="municipio",
+ name="latitude",
+ field=models.DecimalField(
+ blank=True,
+ decimal_places=8,
+ help_text="Exemplo: -20,464 .",
+ max_digits=10,
+ null=True,
+ verbose_name="latitude",
+ ),
),
migrations.AlterField(
- model_name='municipio',
- name='longitude',
- field=models.DecimalField(blank=True, decimal_places=8, help_text='Exemplo: -45,426 .', max_digits=11, null=True, verbose_name='longitude'),
+ model_name="municipio",
+ name="longitude",
+ field=models.DecimalField(
+ blank=True,
+ decimal_places=8,
+ help_text="Exemplo: -45,426 .",
+ max_digits=11,
+ null=True,
+ verbose_name="longitude",
+ ),
),
migrations.AlterField(
- model_name='municipio',
- name='microrregiao',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='contatos.microrregiao', verbose_name='microrregião'),
+ model_name="municipio",
+ name="microrregiao",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ to="contatos.microrregiao",
+ verbose_name="microrregião",
+ ),
),
migrations.AlterField(
- model_name='telefone',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="telefone",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='telefone',
- name='tipo',
- field=models.CharField(choices=[('F', 'Fixo'), ('M', 'Móvel'), ('X', 'Fax'), ('I', 'Indefinido')], default='I', max_length=1, verbose_name='tipo'),
+ model_name="telefone",
+ name="tipo",
+ field=models.CharField(
+ choices=[
+ ("F", "Fixo"),
+ ("M", "Móvel"),
+ ("X", "Fax"),
+ ("I", "Indefinido"),
+ ],
+ default="I",
+ max_length=1,
+ verbose_name="tipo",
+ ),
),
migrations.AlterField(
- model_name='telefone',
- name='ult_alteracao',
- field=models.DateTimeField(auto_now=True, null=True, verbose_name='última alteração'),
+ model_name="telefone",
+ name="ult_alteracao",
+ field=models.DateTimeField(
+ auto_now=True, null=True, verbose_name="última alteração"
+ ),
),
migrations.AlterField(
- model_name='unidadefederativa',
- name='nome',
- field=models.CharField(max_length=25, verbose_name='nome UF'),
+ model_name="unidadefederativa",
+ name="nome",
+ field=models.CharField(max_length=25, verbose_name="nome UF"),
),
migrations.AlterField(
- model_name='unidadefederativa',
- name='regiao',
- field=models.CharField(choices=[('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte'), ('SD', 'Sudeste'), ('SL', 'Sul')], max_length=2, verbose_name='região'),
+ model_name="unidadefederativa",
+ name="regiao",
+ field=models.CharField(
+ choices=[
+ ("CO", "Centro-Oeste"),
+ ("NE", "Nordeste"),
+ ("NO", "Norte"),
+ ("SD", "Sudeste"),
+ ("SL", "Sul"),
+ ],
+ max_length=2,
+ verbose_name="região",
+ ),
),
migrations.AlterField(
- model_name='unidadefederativa',
- name='search_text',
- field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']),
+ model_name="unidadefederativa",
+ name="search_text",
+ field=sigi.apps.utils.SearchField(
+ editable=False, field_names=["nome"]
+ ),
),
migrations.AlterField(
- model_name='unidadefederativa',
- name='sigla',
- field=models.CharField(help_text='Exemplo: MG .', max_length=2, unique=True, verbose_name='sigla'),
+ model_name="unidadefederativa",
+ name="sigla",
+ field=models.CharField(
+ help_text="Exemplo: MG .",
+ max_length=2,
+ unique=True,
+ verbose_name="sigla",
+ ),
),
]
diff --git a/sigi/apps/contatos/models.py b/sigi/apps/contatos/models.py
index 6a00d5e..2f0c41d 100644
--- a/sigi/apps/contatos/models.py
+++ b/sigi/apps/contatos/models.py
@@ -1,5 +1,7 @@
-from django.contrib.contenttypes.fields import (GenericForeignKey,
- GenericRelation)
+from django.contrib.contenttypes.fields import (
+ GenericForeignKey,
+ GenericRelation,
+)
from django.contrib.contenttypes.models import ContentType
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
@@ -9,200 +11,192 @@ from sigi.apps.utils import SearchField
class UnidadeFederativa(models.Model):
REGIAO_CHOICES = (
- ('CO', _('Centro-Oeste')),
- ('NE', _('Nordeste')),
- ('NO', _('Norte')),
- ('SD', _('Sudeste')),
- ('SL', _('Sul')),
+ ("CO", _("Centro-Oeste")),
+ ("NE", _("Nordeste")),
+ ("NO", _("Norte")),
+ ("SD", _("Sudeste")),
+ ("SL", _("Sul")),
)
codigo_ibge = models.PositiveIntegerField(
- _('código IBGE'),
+ _("código IBGE"),
primary_key=True,
unique=True,
- help_text=_('Código do estado segundo IBGE.')
+ help_text=_("Código do estado segundo IBGE."),
)
- nome = models.CharField(_('nome UF'), max_length=25)
+ nome = models.CharField(_("nome UF"), max_length=25)
# Campo de busca em caixa baixa sem acento
- search_text = SearchField(field_names=['nome'])
+ search_text = SearchField(field_names=["nome"])
sigla = models.CharField(
- _('sigla'),
+ _("sigla"),
max_length=2,
unique=True,
help_text=_("Exemplo: MG ."),
)
- regiao = models.CharField(_('região'), max_length=2, choices=REGIAO_CHOICES)
- populacao = models.PositiveIntegerField(_('população'))
+ regiao = models.CharField(_("região"), max_length=2, choices=REGIAO_CHOICES)
+ populacao = models.PositiveIntegerField(_("população"))
class Meta:
- ordering = ('nome',)
- verbose_name = _('Unidade Federativa')
- verbose_name_plural = _('Unidades Federativas')
+ ordering = ("nome",)
+ verbose_name = _("Unidade Federativa")
+ verbose_name_plural = _("Unidades Federativas")
def __str__(self):
return self.nome
+
class Mesorregiao(models.Model):
codigo_ibge = models.PositiveIntegerField(
- _('código IBGE'),
+ _("código IBGE"),
primary_key=True,
unique=True,
- help_text=_('Código da mesorregião segundo o IBGE')
+ help_text=_("Código da mesorregião segundo o IBGE"),
)
uf = models.ForeignKey(
- UnidadeFederativa,
- on_delete=models.CASCADE,
- verbose_name=_('UF')
+ UnidadeFederativa, on_delete=models.CASCADE, verbose_name=_("UF")
)
nome = models.CharField(_("nome mesorregião"), max_length=100)
# Campo de busca em caixa baixa sem acento
- search_text = SearchField(field_names=['nome'])
+ search_text = SearchField(field_names=["nome"])
class Meta:
- ordering = ('uf', 'nome',)
- verbose_name = _('mesorregião'),
- verbose_name_plural = _('mesorregiões')
+ ordering = (
+ "uf",
+ "nome",
+ )
+ verbose_name = (_("mesorregião"),)
+ verbose_name_plural = _("mesorregiões")
def __str__(self):
return self.nome
+
class Microrregiao(models.Model):
codigo_ibge = models.PositiveIntegerField(
- _('código IBGE'),
+ _("código IBGE"),
primary_key=True,
unique=True,
- help_text=_('Código da microrregião segundo o IBGE')
+ help_text=_("Código da microrregião segundo o IBGE"),
)
mesorregiao = models.ForeignKey(
Mesorregiao,
on_delete=models.CASCADE,
- verbose_name=_('mesorregião'),
+ verbose_name=_("mesorregião"),
)
nome = models.CharField(_("nome microrregião"), max_length=100)
# Campo de busca em caixa baixa sem acento
- search_text = SearchField(field_names=['nome'])
+ search_text = SearchField(field_names=["nome"])
class Meta:
- ordering = ('nome',)
- verbose_name = _('microrregião')
- verbose_name_plural = _('microrregiões')
+ ordering = ("nome",)
+ verbose_name = _("microrregião")
+ verbose_name_plural = _("microrregiões")
def __str__(self):
return f"{self.nome} ({self.mesorregiao.nome})"
+
class Municipio(models.Model):
codigo_ibge = models.PositiveIntegerField(
- _('código IBGE'),
+ _("código IBGE"),
primary_key=True,
unique=True,
- help_text=_('Código do município segundo IBGE.')
+ help_text=_("Código do município segundo IBGE."),
)
microrregiao = models.ForeignKey(
Microrregiao,
on_delete=models.PROTECT,
- verbose_name=_('microrregião'),
+ verbose_name=_("microrregião"),
blank=True,
- null=True
+ null=True,
)
# codigo designado pelo Tribunal Superior Eleitoral
codigo_tse = models.PositiveIntegerField(
- _('código TSE'),
+ _("código TSE"),
unique=True,
null=True,
- help_text=_('Código do município segundo TSE.')
+ help_text=_("Código do município segundo TSE."),
)
nome = models.CharField(max_length=50)
- search_text = SearchField(field_names=[_('nome'), _('uf')])
+ search_text = SearchField(field_names=[_("nome"), _("uf")])
uf = models.ForeignKey(
- UnidadeFederativa,
- on_delete=models.PROTECT,
- verbose_name=_('UF')
+ UnidadeFederativa, on_delete=models.PROTECT, verbose_name=_("UF")
)
# verdadeiro se o município é capital do estado
- is_capital = models.BooleanField(_('capital'), default=False)
- populacao = models.PositiveIntegerField(_('população'))
- is_polo = models.BooleanField(_('pólo'), default=False)
+ is_capital = models.BooleanField(_("capital"), default=False)
+ populacao = models.PositiveIntegerField(_("população"))
+ is_polo = models.BooleanField(_("pólo"), default=False)
data_criacao = models.DateField(
- _('data de criação do município'),
- null=True,
- blank=True
+ _("data de criação do município"), null=True, blank=True
)
# posição geográfica do município
latitude = models.DecimalField(
- _('latitude'),
+ _("latitude"),
max_digits=10,
decimal_places=8,
null=True,
blank=True,
- help_text=_('Exemplo: -20,464 .')
+ help_text=_("Exemplo: -20,464 ."),
)
longitude = models.DecimalField(
- _('longitude'),
+ _("longitude"),
max_digits=11,
decimal_places=8,
null=True,
blank=True,
- help_text=_('Exemplo: -45,426 .')
+ help_text=_("Exemplo: -45,426 ."),
)
idh = models.DecimalField(
- _('IDH'),
- help_text=_('Índice de desenvolvimento Humano'),
+ _("IDH"),
+ help_text=_("Índice de desenvolvimento Humano"),
max_digits=4,
decimal_places=3,
- validators=[MinValueValidator(0), MaxValueValidator(1)]
+ validators=[MinValueValidator(0), MaxValueValidator(1)],
)
pib_total = models.DecimalField(
- _('PIB total'),
- max_digits=18,
- decimal_places=3,
- blank=True,
- null=True
+ _("PIB total"), max_digits=18, decimal_places=3, blank=True, null=True
)
pib_percapita = models.DecimalField(
- _('PIB per capita'),
+ _("PIB per capita"),
max_digits=18,
decimal_places=3,
blank=True,
- null=True
+ null=True,
)
pib_ano = models.IntegerField(
- _('Ano de apuração do PIB'),
- blank=True,
- null=True
+ _("Ano de apuração do PIB"), blank=True, null=True
)
class Meta:
- ordering = ('nome', 'codigo_ibge')
- verbose_name = _('município')
- verbose_name_plural = _('municípios')
+ ordering = ("nome", "codigo_ibge")
+ verbose_name = _("município")
+ verbose_name_plural = _("municípios")
def __str__(self):
return f"{self.nome} - {self.uf}"
+
class Telefone(models.Model):
TELEFONE_CHOICES = (
- ('F', _('Fixo')),
- ('M', _('Móvel')),
- ('X', _('Fax')),
- ('I', _('Indefinido')),
+ ("F", _("Fixo")),
+ ("M", _("Móvel")),
+ ("X", _("Fax")),
+ ("I", _("Indefinido")),
)
numero = models.CharField(
- _('número'),
+ _("número"),
max_length=64,
- help_text=_('Exemplo: (31)8851-9898 .'),
+ help_text=_("Exemplo: (31)8851-9898 ."),
)
tipo = models.CharField(
- _('tipo'),
- max_length=1,
- choices=TELEFONE_CHOICES,
- default='I'
+ _("tipo"), max_length=1, choices=TELEFONE_CHOICES, default="I"
)
nota = models.CharField(max_length=70, null=True, blank=True)
ult_alteracao = models.DateTimeField(
- _('última alteração'),
+ _("última alteração"),
null=True,
blank=True,
editable=False,
- auto_now=True
+ auto_now=True,
)
# guarda o tipo do objeto (classe) vinculado a esse registro
@@ -210,26 +204,27 @@ class Telefone(models.Model):
# identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey(
- 'content_type',
- 'object_id',
+ "content_type",
+ "object_id",
)
class Meta:
- ordering = ('numero',)
- unique_together = ('numero', 'tipo')
+ ordering = ("numero",)
+ unique_together = ("numero", "tipo")
def __str__(self):
return self.numero
+
class Contato(models.Model):
- nome = models.CharField(_('nome completo'), max_length=120)
+ nome = models.CharField(_("nome completo"), max_length=120)
nota = models.CharField(max_length=70, blank=True)
- email = models.EmailField(_('e-mail'), blank=True)
+ email = models.EmailField(_("e-mail"), blank=True)
telefones = GenericRelation(Telefone)
municipio = models.ForeignKey(
Municipio,
on_delete=models.SET_NULL,
- verbose_name=_('município'),
+ verbose_name=_("município"),
blank=True,
null=True,
)
@@ -238,70 +233,71 @@ class Contato(models.Model):
# identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey(
- 'content_type',
- 'object_id',
+ "content_type",
+ "object_id",
)
class Meta:
- ordering = ('nome',)
- verbose_name = _('contato Interlegis')
- verbose_name_plural = _('contatos Interlegis')
+ ordering = ("nome",)
+ verbose_name = _("contato Interlegis")
+ verbose_name_plural = _("contatos Interlegis")
def __str__(self):
return self.nome
+
class Endereco(models.Model):
TIPO_CHOICES = (
- ('aeroporto', _('Aeroporto')),
- ('alameda', _('Alameda')),
- ('area', _('Área')),
- ('avenida', _('Avenida')),
- ('campo', _('Campo')),
- ('chacara', _('Chácara')),
- ('colonia', _('Colônia')),
- ('condominio', _('Condomínio')),
- ('conjunto', _('Conjunto')),
- ('distrito', _('Distrito')),
- ('esplanada', _('Esplanada')),
- ('estacao', _('Estação')),
- ('estrada', _('Estrada')),
- ('favela', _('Favela')),
- ('fazenda', _('Fazenda')),
- ('feira', _('Feira')),
- ('jardim', _('Jardim')),
- ('ladeira', _('Ladeira')),
- ('lago', _('Lago')),
- ('lagoa', _('Lagoa')),
- ('largo', _('Largo')),
- ('loteamento', _('Loteamento')),
- ('morro', _('Morro')),
- ('nucleo', _('Núcleo')),
- ('parque', _('Parque')),
- ('passarela', _('Passarela')),
- ('patio', _('Pátio')),
- ('praca', _('Praça')),
- ('quadra', _('Quadra')),
- ('recanto', _('Recanto')),
- ('residencial', _('Residencial')),
- ('rodovia', _('Rodovia')),
- ('rua', _('Rua')),
- ('setor', _('Setor')),
- ('sitio', _('Sítio')),
- ('travessa', _('Travessa')),
- ('trecho', _('Trecho')),
- ('trevo', _('Trevo')),
- ('vale', _('Vale')),
- ('vereda', _('Vereda')),
- ('via', _('Via')),
- ('viaduto', _('Viaduto')),
- ('viela', _('Viela')),
- ('vila', _('Vila')),
- ('outro', _('Outro')),
+ ("aeroporto", _("Aeroporto")),
+ ("alameda", _("Alameda")),
+ ("area", _("Área")),
+ ("avenida", _("Avenida")),
+ ("campo", _("Campo")),
+ ("chacara", _("Chácara")),
+ ("colonia", _("Colônia")),
+ ("condominio", _("Condomínio")),
+ ("conjunto", _("Conjunto")),
+ ("distrito", _("Distrito")),
+ ("esplanada", _("Esplanada")),
+ ("estacao", _("Estação")),
+ ("estrada", _("Estrada")),
+ ("favela", _("Favela")),
+ ("fazenda", _("Fazenda")),
+ ("feira", _("Feira")),
+ ("jardim", _("Jardim")),
+ ("ladeira", _("Ladeira")),
+ ("lago", _("Lago")),
+ ("lagoa", _("Lagoa")),
+ ("largo", _("Largo")),
+ ("loteamento", _("Loteamento")),
+ ("morro", _("Morro")),
+ ("nucleo", _("Núcleo")),
+ ("parque", _("Parque")),
+ ("passarela", _("Passarela")),
+ ("patio", _("Pátio")),
+ ("praca", _("Praça")),
+ ("quadra", _("Quadra")),
+ ("recanto", _("Recanto")),
+ ("residencial", _("Residencial")),
+ ("rodovia", _("Rodovia")),
+ ("rua", _("Rua")),
+ ("setor", _("Setor")),
+ ("sitio", _("Sítio")),
+ ("travessa", _("Travessa")),
+ ("trecho", _("Trecho")),
+ ("trevo", _("Trevo")),
+ ("vale", _("Vale")),
+ ("vereda", _("Vereda")),
+ ("via", _("Via")),
+ ("viaduto", _("Viaduto")),
+ ("viela", _("Viela")),
+ ("vila", _("Vila")),
+ ("outro", _("Outro")),
)
- tipo = models.CharField(_('tipo'), max_length=15, choices=TIPO_CHOICES)
+ tipo = models.CharField(_("tipo"), max_length=15, choices=TIPO_CHOICES)
logradouro = models.CharField(
- _('logradouro'),
+ _("logradouro"),
max_length=100,
)
numero = models.CharField(max_length=15, blank=True)
@@ -309,16 +305,16 @@ class Endereco(models.Model):
referencia = models.CharField(max_length=100, blank=True)
bairro = models.CharField(max_length=100, blank=True)
cep = models.CharField(
- _('CEP'),
+ _("CEP"),
max_length=9,
blank=True,
null=True,
- help_text=_("Formato: XXXXX-XXX .")
+ help_text=_("Formato: XXXXX-XXX ."),
)
municipio = models.ForeignKey(
Municipio,
on_delete=models.SET_NULL,
- verbose_name=_('município'),
+ verbose_name=_("município"),
blank=True,
null=True,
)
@@ -327,15 +323,17 @@ class Endereco(models.Model):
# identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey(
- 'content_type',
- 'object_id',
+ "content_type",
+ "object_id",
)
class Meta:
- ordering = ('logradouro', 'numero')
- verbose_name = _('endereço')
- verbose_name_plural = _('endereços')
+ ordering = ("logradouro", "numero")
+ verbose_name = _("endereço")
+ verbose_name_plural = _("endereços")
def __str__(self):
- return (f"{self.tipo} {self.logradouro}, {self.numero}"
- f"{self.complemento} - {self.bairro}")
+ return (
+ f"{self.tipo} {self.logradouro}, {self.numero}"
+ f"{self.complemento} - {self.bairro}"
+ )
diff --git a/sigi/apps/convenios/admin.py b/sigi/apps/convenios/admin.py
index d8a1abe..5540a9e 100644
--- a/sigi/apps/convenios/admin.py
+++ b/sigi/apps/convenios/admin.py
@@ -2,10 +2,16 @@ from django.contrib import admin
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import gettext as _
from django.utils.safestring import mark_safe
-from sigi.apps.convenios.models import (Projeto, StatusConvenio,
- TipoSolicitacao, Convenio,
- EquipamentoPrevisto, Anexo, Tramitacao,
- Gescon)
+from sigi.apps.convenios.models import (
+ Projeto,
+ StatusConvenio,
+ TipoSolicitacao,
+ Convenio,
+ EquipamentoPrevisto,
+ Anexo,
+ Tramitacao,
+ Gescon,
+)
from sigi.apps.utils import queryset_ascii
from sigi.apps.servidores.models import Servidor
from sigi.apps.casas.admin import ConveniosInline, GerentesInterlegisFilter
@@ -13,86 +19,170 @@ from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse
from django_weasyprint.views import WeasyTemplateResponse
from sigi.apps.utils.filters import DateRangeFilter
+
class ConvenioExportResourse(LabeledResourse):
class Meta:
model = Convenio
- fields = ('num_processo_sf', 'num_convenio', 'projeto__nome',
- 'casa_legislativa__nome', 'casa_legislativa__municipio__nome',
- 'casa_legislativa__municipio__uf__sigla', 'data_sigi',
- 'data_sigad', 'data_adesao', 'data_retorno_assinatura',
- 'data_solicitacao', 'atualizacao_gescon', 'observacao_gescon',
- 'tipo_solicitacao__nome', 'status__nome',
- 'acompanha__nome_completo', 'servidor_gestao__nome_completo',
- 'observacao')
+ fields = (
+ "num_processo_sf",
+ "num_convenio",
+ "projeto__nome",
+ "casa_legislativa__nome",
+ "casa_legislativa__municipio__nome",
+ "casa_legislativa__municipio__uf__sigla",
+ "data_sigi",
+ "data_sigad",
+ "data_adesao",
+ "data_retorno_assinatura",
+ "data_solicitacao",
+ "atualizacao_gescon",
+ "observacao_gescon",
+ "tipo_solicitacao__nome",
+ "status__nome",
+ "acompanha__nome_completo",
+ "servidor_gestao__nome_completo",
+ "observacao",
+ )
export_order = fields
+
class AnexosInline(admin.TabularInline):
model = Anexo
extra = 2
- exclude = ['data_pub', ]
+ exclude = [
+ "data_pub",
+ ]
+
class AnexoAdmin(admin.ModelAdmin):
- date_hierarchy = 'data_pub'
- exclude = ['data_pub', ]
- list_display = ('arquivo', 'descricao', 'data_pub', 'convenio')
- raw_id_fields = ('convenio',)
- search_fields = ('descricao', 'convenio__id', 'arquivo',
- 'convenio__casa_legislativa__nome')
+ date_hierarchy = "data_pub"
+ exclude = [
+ "data_pub",
+ ]
+ list_display = ("arquivo", "descricao", "data_pub", "convenio")
+ raw_id_fields = ("convenio",)
+ search_fields = (
+ "descricao",
+ "convenio__id",
+ "arquivo",
+ "convenio__casa_legislativa__nome",
+ )
+
class AcompanhaFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs):
super(AcompanhaFilter, self).__init__(*args, **kwargs)
- servidores = Servidor.objects.filter(
- convenio__isnull=False).order_by('nome_completo').distinct()
+ servidores = (
+ Servidor.objects.filter(convenio__isnull=False)
+ .order_by("nome_completo")
+ .distinct()
+ )
self.lookup_choices = [(x.id, x) for x in servidores]
+
@admin.register(Convenio)
class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
fieldsets = (
- (None,
- {'fields': ('casa_legislativa', 'num_processo_sf', 'num_convenio',
- 'projeto', 'data_sigi',)}
- ),
- (_("Acompanhamento no gabinete"),
- {'fields': ('data_solicitacao', 'data_sigad', 'observacao',)}
+ (
+ None,
+ {
+ "fields": (
+ "casa_legislativa",
+ "num_processo_sf",
+ "num_convenio",
+ "projeto",
+ "data_sigi",
+ )
+ },
+ ),
+ (
+ _("Acompanhamento no gabinete"),
+ {
+ "fields": (
+ "data_solicitacao",
+ "data_sigad",
+ "observacao",
+ )
+ },
+ ),
+ (
+ _("Gestão do convênio"),
+ {
+ "fields": (
+ "servico_gestao",
+ "servidor_gestao",
+ )
+ },
),
- (_("Gestão do convênio"),
- {'fields': ('servico_gestao', 'servidor_gestao',)}
+ (
+ _("Datas"),
+ {
+ "fields": (
+ "data_retorno_assinatura",
+ "data_termino_vigencia",
+ "data_pub_diario",
+ )
+ },
),
- (_('Datas'),
- {'fields': ('data_retorno_assinatura', 'data_termino_vigencia',
- 'data_pub_diario',)}
- ),
- (_('Gescon'),
- {'fields': ('atualizacao_gescon', 'observacao_gescon', 'link_gescon')}
+ (
+ _("Gescon"),
+ {
+ "fields": (
+ "atualizacao_gescon",
+ "observacao_gescon",
+ "link_gescon",
+ )
+ },
),
)
- readonly_fields = ('data_sigi', 'atualizacao_gescon', 'observacao_gescon',
- 'link_gescon')
+ readonly_fields = (
+ "data_sigi",
+ "atualizacao_gescon",
+ "observacao_gescon",
+ "link_gescon",
+ )
inlines = (AnexosInline,)
- list_display = ('num_convenio', 'projeto','casa_legislativa', 'get_uf',
- 'status_convenio', 'link_sigad', 'data_retorno_assinatura',
- 'data_termino_vigencia',)
- list_display_links = ('num_convenio', 'casa_legislativa',)
+ list_display = (
+ "num_convenio",
+ "projeto",
+ "casa_legislativa",
+ "get_uf",
+ "status_convenio",
+ "link_sigad",
+ "data_retorno_assinatura",
+ "data_termino_vigencia",
+ )
+ list_display_links = (
+ "num_convenio",
+ "casa_legislativa",
+ )
list_filter = (
- ('data_retorno_assinatura', DateRangeFilter),
- ('data_sigi', DateRangeFilter), ('data_solicitacao', DateRangeFilter),
- ('data_sigad', DateRangeFilter),
- ('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter),
- 'projeto', 'casa_legislativa__tipo', 'conveniada','equipada',
- 'casa_legislativa__municipio__uf',
+ ("data_retorno_assinatura", DateRangeFilter),
+ ("data_sigi", DateRangeFilter),
+ ("data_solicitacao", DateRangeFilter),
+ ("data_sigad", DateRangeFilter),
+ ("casa_legislativa__gerentes_interlegis", GerentesInterlegisFilter),
+ "projeto",
+ "casa_legislativa__tipo",
+ "conveniada",
+ "equipada",
+ "casa_legislativa__municipio__uf",
)
- ordering = ('casa_legislativa', '-data_retorno_assinatura')
- raw_id_fields = ('casa_legislativa',)
+ ordering = ("casa_legislativa", "-data_retorno_assinatura")
+ raw_id_fields = ("casa_legislativa",)
get_queryset = queryset_ascii
- search_fields = ('id', 'casa_legislativa__search_text',
- 'casa_legislativa__sigla', 'num_processo_sf',
- 'num_convenio')
+ search_fields = (
+ "id",
+ "casa_legislativa__search_text",
+ "casa_legislativa__sigla",
+ "num_processo_sf",
+ "num_convenio",
+ )
resource_class = ConvenioExportResourse
reports = [
- 'report_convenios',
- 'report_convenios_camaras',
- 'report_convenios_assembleia',
+ "report_convenios",
+ "report_convenios_camaras",
+ "report_convenios_assembleia",
]
def get_queryset(self, request):
@@ -101,8 +191,9 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
def get_uf(self, obj):
return obj.casa_legislativa.municipio.uf.sigla
- get_uf.short_description = _('UF')
- get_uf.admin_order_field = 'casa_legislativa__municipio__uf__sigla'
+
+ get_uf.short_description = _("UF")
+ get_uf.admin_order_field = "casa_legislativa__municipio__uf__sigla"
def status_convenio(self, obj):
if obj.pk is None:
@@ -118,12 +209,14 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
else:
label = r"info"
return mark_safe(f'{status}
')
+
status_convenio.short_description = _("Status do convênio")
def link_sigad(self, obj):
if obj.pk is None:
return ""
return mark_safe(obj.get_sigad_url())
+
link_sigad.short_description = _("Processo no Senado")
def link_gescon(self, obj):
@@ -133,53 +226,63 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
f""
f"https://adm.senado.gov.br/gestao-contratos/api/"
- f"{obj.id_contrato_gescon} ")
+ f"{obj.id_contrato_gescon}"
+ )
+
link_gescon.short_description = _("Download MINUTA ASSINADA do Gescon")
def report_convenios(self, request):
context = {
- 'convenios': self.get_queryset(request),
- 'title': _('Relatório de convenios'),
+ "convenios": self.get_queryset(request),
+ "title": _("Relatório de convenios"),
}
return WeasyTemplateResponse(
- filename='relatorio_convenios.pdf',
+ filename="relatorio_convenios.pdf",
request=request,
template="convenios/convenios_report.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- report_convenios.title = _('Relatório de convênios')
+ report_convenios.title = _("Relatório de convênios")
def report_convenios_camaras(self, request):
context = {
- 'convenios': self.get_queryset(request).filter(casa_legislativa__tipo__legislativo = False),
- 'title': _('Relatório de convenios de camaras municipais'),
+ "convenios": self.get_queryset(request).filter(
+ casa_legislativa__tipo__legislativo=False
+ ),
+ "title": _("Relatório de convenios de camaras municipais"),
}
return WeasyTemplateResponse(
- filename='relatorio_convenios.pdf',
+ filename="relatorio_convenios.pdf",
request=request,
template="convenios/convenios_report.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- report_convenios_camaras.title = _('Relatório de convênios de camaras municipais')
+ report_convenios_camaras.title = _(
+ "Relatório de convênios de camaras municipais"
+ )
def report_convenios_assembleia(self, request):
context = {
- 'convenios': self.get_queryset(request).filter(casa_legislativa__tipo__legislativo = True),
- 'title': _('Relatório de convenios de assembleias legislativas'),
+ "convenios": self.get_queryset(request).filter(
+ casa_legislativa__tipo__legislativo=True
+ ),
+ "title": _("Relatório de convenios de assembleias legislativas"),
}
return WeasyTemplateResponse(
- filename='relatorio_convenios.pdf',
+ filename="relatorio_convenios.pdf",
request=request,
template="convenios/convenios_report.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
- report_convenios_assembleia.title = _('Relatório de convênios de assembleias legislativas')
+ report_convenios_assembleia.title = _(
+ "Relatório de convênios de assembleias legislativas"
+ )
# def relatorio(self, request, queryset):
# # queryset.order_by('casa_legislativa__municipio__uf')
@@ -206,23 +309,35 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
def get_actions(self, request):
actions = super(ConvenioAdmin, self).get_actions(request)
- if 'delete_selected' in actions:
- del actions['delete_selected']
+ if "delete_selected" in actions:
+ del actions["delete_selected"]
return actions
+
@admin.register(EquipamentoPrevisto)
class EquipamentoPrevistoAdmin(admin.ModelAdmin):
- list_display = ('convenio', 'equipamento', 'quantidade')
- list_display_links = ('convenio', 'equipamento')
- ordering = ('convenio', 'equipamento')
- raw_id_fields = ('convenio', 'equipamento')
- search_fields = ('convenio__id', 'equipamento__fabricante__nome',
- 'equipamento__modelo__modelo', 'equipamento__modelo__tipo__tipo')
+ list_display = ("convenio", "equipamento", "quantidade")
+ list_display_links = ("convenio", "equipamento")
+ ordering = ("convenio", "equipamento")
+ raw_id_fields = ("convenio", "equipamento")
+ search_fields = (
+ "convenio__id",
+ "equipamento__fabricante__nome",
+ "equipamento__modelo__modelo",
+ "equipamento__modelo__tipo__tipo",
+ )
+
@admin.register(Gescon)
class GesconAdmin(admin.ModelAdmin):
- list_display = ('url_gescon', 'email',)
- exclude = ['ultima_importacao',]
+ list_display = (
+ "url_gescon",
+ "email",
+ )
+ exclude = [
+ "ultima_importacao",
+ ]
+
admin.site.register(Projeto)
admin.site.register(StatusConvenio)
diff --git a/sigi/apps/convenios/apps.py b/sigi/apps/convenios/apps.py
index 71da54e..c866b2a 100644
--- a/sigi/apps/convenios/apps.py
+++ b/sigi/apps/convenios/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class ConveniosConfig(AppConfig):
- name = 'sigi.apps.convenios'
- verbose_name = _('convênios')
+ name = "sigi.apps.convenios"
+ verbose_name = _("convênios")
diff --git a/sigi/apps/convenios/migrations/0001_initial.py b/sigi/apps/convenios/migrations/0001_initial.py
index 605277a..3e21724 100644
--- a/sigi/apps/convenios/migrations/0001_initial.py
+++ b/sigi/apps/convenios/migrations/0001_initial.py
@@ -8,116 +8,304 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('inventario', '__first__'),
- ('casas', '0001_initial'),
+ ("inventario", "__first__"),
+ ("casas", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Anexo',
+ name="Anexo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('arquivo', models.FileField(max_length=500, upload_to='apps/convenios/anexo/arquivo')),
- ('descricao', models.CharField(max_length='70', verbose_name='descri\xe7\xe3o')),
- ('data_pub', models.DateTimeField(default=datetime.datetime.now, verbose_name='data da publica\xe7\xe3o do anexo')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "arquivo",
+ models.FileField(
+ max_length=500, upload_to="apps/convenios/anexo/arquivo"
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length="70", verbose_name="descri\xe7\xe3o"
+ ),
+ ),
+ (
+ "data_pub",
+ models.DateTimeField(
+ default=datetime.datetime.now,
+ verbose_name="data da publica\xe7\xe3o do anexo",
+ ),
+ ),
],
options={
- 'ordering': ('-data_pub',),
+ "ordering": ("-data_pub",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Convenio',
+ name="Convenio",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('search_text', sigi.apps.utils.SearchField(field_names=['casa_legislativa'], editable=False)),
- ('num_processo_sf', models.CharField(help_text='Formatos: Antigo: XXXXXX/XX-X .SIGAD: XXXXX.XXXXXX/XXXX-XX ', max_length=20, verbose_name='n\xfamero do processo SF (Senado Federal)', blank=True)),
- ('num_convenio', models.CharField(max_length=10, verbose_name='n\xfamero do conv\xeanio', blank=True)),
- ('data_adesao', models.DateField(null=True, verbose_name='Aderidas', blank=True)),
- ('data_retorno_assinatura', models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='Conveniadas', blank=True)),
- ('data_pub_diario', models.DateField(null=True, verbose_name='data da publica\xe7\xe3o no Di\xe1rio Oficial', blank=True)),
- ('data_termo_aceite', models.DateField(help_text='Equipamentos recebidos.', null=True, verbose_name='Equipadas', blank=True)),
- ('data_devolucao_via', models.DateField(help_text='Data de devolu\xe7\xe3o da via do conv\xeanio \xe0 C\xe2mara Municipal.', null=True, verbose_name='data de devolu\xe7\xe3o da via', blank=True)),
- ('data_postagem_correio', models.DateField(null=True, verbose_name='data postagem correio', blank=True)),
- ('data_devolucao_sem_assinatura', models.DateField(help_text='Data de devolu\xe7\xe3o por falta de assinatura', null=True, verbose_name='data de devolu\xe7\xe3o por falta de assinatura', blank=True)),
- ('data_retorno_sem_assinatura', models.DateField(help_text='Data do retorno do conv\xeanio sem assinatura', null=True, verbose_name='data do retorno sem assinatura', blank=True)),
- ('observacao', models.CharField(max_length=100, null=True, blank=True)),
- ('conveniada', models.BooleanField(default=False)),
- ('equipada', models.BooleanField(default=False)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=["casa_legislativa"], editable=False
+ ),
+ ),
+ (
+ "num_processo_sf",
+ models.CharField(
+ help_text="Formatos: Antigo: XXXXXX/XX-X .SIGAD: XXXXX.XXXXXX/XXXX-XX ",
+ max_length=20,
+ verbose_name="n\xfamero do processo SF (Senado Federal)",
+ blank=True,
+ ),
+ ),
+ (
+ "num_convenio",
+ models.CharField(
+ max_length=10,
+ verbose_name="n\xfamero do conv\xeanio",
+ blank=True,
+ ),
+ ),
+ (
+ "data_adesao",
+ models.DateField(
+ null=True, verbose_name="Aderidas", blank=True
+ ),
+ ),
+ (
+ "data_retorno_assinatura",
+ models.DateField(
+ help_text="Conv\xeanio firmado.",
+ null=True,
+ verbose_name="Conveniadas",
+ blank=True,
+ ),
+ ),
+ (
+ "data_pub_diario",
+ models.DateField(
+ null=True,
+ verbose_name="data da publica\xe7\xe3o no Di\xe1rio Oficial",
+ blank=True,
+ ),
+ ),
+ (
+ "data_termo_aceite",
+ models.DateField(
+ help_text="Equipamentos recebidos.",
+ null=True,
+ verbose_name="Equipadas",
+ blank=True,
+ ),
+ ),
+ (
+ "data_devolucao_via",
+ models.DateField(
+ help_text="Data de devolu\xe7\xe3o da via do conv\xeanio \xe0 C\xe2mara Municipal.",
+ null=True,
+ verbose_name="data de devolu\xe7\xe3o da via",
+ blank=True,
+ ),
+ ),
+ (
+ "data_postagem_correio",
+ models.DateField(
+ null=True,
+ verbose_name="data postagem correio",
+ blank=True,
+ ),
+ ),
+ (
+ "data_devolucao_sem_assinatura",
+ models.DateField(
+ help_text="Data de devolu\xe7\xe3o por falta de assinatura",
+ null=True,
+ verbose_name="data de devolu\xe7\xe3o por falta de assinatura",
+ blank=True,
+ ),
+ ),
+ (
+ "data_retorno_sem_assinatura",
+ models.DateField(
+ help_text="Data do retorno do conv\xeanio sem assinatura",
+ null=True,
+ verbose_name="data do retorno sem assinatura",
+ blank=True,
+ ),
+ ),
+ (
+ "observacao",
+ models.CharField(max_length=100, null=True, blank=True),
+ ),
+ ("conveniada", models.BooleanField(default=False)),
+ ("equipada", models.BooleanField(default=False)),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('id',),
- 'get_latest_by': 'id',
- 'verbose_name': 'conv\xeanio',
+ "ordering": ("id",),
+ "get_latest_by": "id",
+ "verbose_name": "conv\xeanio",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='EquipamentoPrevisto',
+ name="EquipamentoPrevisto",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('quantidade', models.PositiveSmallIntegerField(default=1)),
- ('convenio', models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE)),
- ('equipamento', models.ForeignKey(to='inventario.Equipamento', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("quantidade", models.PositiveSmallIntegerField(default=1)),
+ (
+ "convenio",
+ models.ForeignKey(
+ verbose_name="conv\xeanio",
+ to="convenios.Convenio",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "equipamento",
+ models.ForeignKey(
+ to="inventario.Equipamento", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'verbose_name': 'equipamento previsto',
- 'verbose_name_plural': 'equipamentos previstos',
+ "verbose_name": "equipamento previsto",
+ "verbose_name_plural": "equipamentos previstos",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Projeto',
+ name="Projeto",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=50)),
- ('sigla', models.CharField(max_length=10)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=50)),
+ ("sigla", models.CharField(max_length=10)),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Tramitacao',
+ name="Tramitacao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('data', models.DateField()),
- ('observacao', models.CharField(max_length='512', null=True, verbose_name='observa\xe7\xe3o', blank=True)),
- ('convenio', models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("data", models.DateField()),
+ (
+ "observacao",
+ models.CharField(
+ max_length="512",
+ null=True,
+ verbose_name="observa\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "convenio",
+ models.ForeignKey(
+ verbose_name="conv\xeanio",
+ to="convenios.Convenio",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'verbose_name_plural': 'Tramita\xe7\xf5es',
+ "verbose_name_plural": "Tramita\xe7\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='UnidadeAdministrativa',
+ name="UnidadeAdministrativa",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('sigla', models.CharField(max_length='10')),
- ('nome', models.CharField(max_length='100')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("sigla", models.CharField(max_length="10")),
+ ("nome", models.CharField(max_length="100")),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.AddField(
- model_name='tramitacao',
- name='unid_admin',
- field=models.ForeignKey(verbose_name='Unidade Administrativa', to='convenios.UnidadeAdministrativa', on_delete=models.CASCADE),
+ model_name="tramitacao",
+ name="unid_admin",
+ field=models.ForeignKey(
+ verbose_name="Unidade Administrativa",
+ to="convenios.UnidadeAdministrativa",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='projeto',
- field=models.ForeignKey(to='convenios.Projeto', on_delete=models.CASCADE),
+ model_name="convenio",
+ name="projeto",
+ field=models.ForeignKey(
+ to="convenios.Projeto", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='anexo',
- name='convenio',
- field=models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE),
+ model_name="anexo",
+ name="convenio",
+ field=models.ForeignKey(
+ verbose_name="conv\xeanio",
+ to="convenios.Convenio",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0002_convenio_duracao.py b/sigi/apps/convenios/migrations/0002_convenio_duracao.py
index 7314354..772eab1 100644
--- a/sigi/apps/convenios/migrations/0002_convenio_duracao.py
+++ b/sigi/apps/convenios/migrations/0002_convenio_duracao.py
@@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0001_initial'),
+ ("convenios", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='duracao',
- field=models.PositiveIntegerField(help_text='Deixar em branco caso a dura\xe7\xe3o seja indefinida', null=True, verbose_name='Dura\xe7\xe3o (meses)', blank=True),
+ model_name="convenio",
+ name="duracao",
+ field=models.PositiveIntegerField(
+ help_text="Deixar em branco caso a dura\xe7\xe3o seja indefinida",
+ null=True,
+ verbose_name="Dura\xe7\xe3o (meses)",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py b/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py
index d241f52..30ca8f2 100644
--- a/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py
+++ b/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py
@@ -6,15 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0002_convenio_duracao'),
- ('casas', '0014_auto_20210406_1945'),
+ ("convenios", "0002_convenio_duracao"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='convenio',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="convenio",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py b/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py
index 0b64bea..fcf7634 100644
--- a/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py
+++ b/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py
@@ -7,71 +7,119 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('convenios', '0003_auto_20210406_1945'),
+ ("servidores", "0001_initial"),
+ ("convenios", "0003_auto_20210406_1945"),
]
operations = [
migrations.CreateModel(
- name='StatusConvenio',
+ name="StatusConvenio",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100)),
- ('cancela', models.BooleanField(default=False, verbose_name='Cancela o conv\xeanio')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=100)),
+ (
+ "cancela",
+ models.BooleanField(
+ default=False, verbose_name="Cancela o conv\xeanio"
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'Estado de convenios',
- 'verbose_name_plural': 'Estados de convenios',
+ "ordering": ("nome",),
+ "verbose_name": "Estado de convenios",
+ "verbose_name_plural": "Estados de convenios",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='convenio',
- name='acompanha',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='acompanhado por', blank=True, to='servidores.Servidor', null=True),
+ model_name="convenio",
+ name="acompanha",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="acompanhado por",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='status',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='estado atual', blank=True, to='convenios.StatusConvenio', null=True),
+ model_name="convenio",
+ name="status",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="estado atual",
+ blank=True,
+ to="convenios.StatusConvenio",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='\xf3rg\xe3o conveniado', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="convenio",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="\xf3rg\xe3o conveniado",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='data_adesao',
- field=models.DateField(null=True, verbose_name='aderidas', blank=True),
+ model_name="convenio",
+ name="data_adesao",
+ field=models.DateField(
+ null=True, verbose_name="aderidas", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='data_retorno_assinatura',
- field=models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='conveniadas', blank=True),
+ model_name="convenio",
+ name="data_retorno_assinatura",
+ field=models.DateField(
+ help_text="Conv\xeanio firmado.",
+ null=True,
+ verbose_name="conveniadas",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='data_termo_aceite',
- field=models.DateField(help_text='Equipamentos recebidos.', null=True, verbose_name='equipadas', blank=True),
+ model_name="convenio",
+ name="data_termo_aceite",
+ field=models.DateField(
+ help_text="Equipamentos recebidos.",
+ null=True,
+ verbose_name="equipadas",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='duracao',
- field=models.PositiveIntegerField(help_text='Deixar em branco caso a dura\xe7\xe3o seja indefinida', null=True, verbose_name='dura\xe7\xe3o (meses)', blank=True),
+ model_name="convenio",
+ name="duracao",
+ field=models.PositiveIntegerField(
+ help_text="Deixar em branco caso a dura\xe7\xe3o seja indefinida",
+ null=True,
+ verbose_name="dura\xe7\xe3o (meses)",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='observacao',
- field=models.TextField(null=True, verbose_name='observa\xe7\xf5es', blank=True),
+ model_name="convenio",
+ name="observacao",
+ field=models.TextField(
+ null=True, verbose_name="observa\xe7\xf5es", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py b/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py
index 78d1385..08e22eb 100644
--- a/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py
+++ b/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py
@@ -6,20 +6,26 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0004_auto_20210407_1928'),
+ ("convenios", "0004_auto_20210407_1928"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='data_sigad',
- field=models.DateField(null=True, verbose_name='data de cadastro no SIGAD', blank=True),
+ model_name="convenio",
+ name="data_sigad",
+ field=models.DateField(
+ null=True, verbose_name="data de cadastro no SIGAD", blank=True
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='data_sigi',
- field=models.DateField(auto_now_add=True, verbose_name='data de cadastro no SIGI', null=True),
+ model_name="convenio",
+ name="data_sigi",
+ field=models.DateField(
+ auto_now_add=True,
+ verbose_name="data de cadastro no SIGI",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0006_auto_20210416_0841.py b/sigi/apps/convenios/migrations/0006_auto_20210416_0841.py
index f3d4fbe..8b7aa7d 100644
--- a/sigi/apps/convenios/migrations/0006_auto_20210416_0841.py
+++ b/sigi/apps/convenios/migrations/0006_auto_20210416_0841.py
@@ -7,26 +7,37 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0005_auto_20210409_0842'),
+ ("convenios", "0005_auto_20210409_0842"),
]
operations = [
migrations.AlterField(
- model_name='convenio',
- name='casa_legislativa',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='\xf3rg\xe3o conveniado', to='casas.Orgao'),
+ model_name="convenio",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="\xf3rg\xe3o conveniado",
+ to="casas.Orgao",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='projeto',
- field=models.ForeignKey(to='convenios.Projeto', on_delete=django.db.models.deletion.PROTECT),
+ model_name="convenio",
+ name="projeto",
+ field=models.ForeignKey(
+ to="convenios.Projeto",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='tramitacao',
- name='unid_admin',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Unidade Administrativa', to='convenios.UnidadeAdministrativa'),
+ model_name="tramitacao",
+ name="unid_admin",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Unidade Administrativa",
+ to="convenios.UnidadeAdministrativa",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0007_auto_20210416_0918.py b/sigi/apps/convenios/migrations/0007_auto_20210416_0918.py
index 200b83c..fe28c47 100644
--- a/sigi/apps/convenios/migrations/0007_auto_20210416_0918.py
+++ b/sigi/apps/convenios/migrations/0007_auto_20210416_0918.py
@@ -7,33 +7,51 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0006_auto_20210416_0841'),
+ ("convenios", "0006_auto_20210416_0841"),
]
operations = [
migrations.CreateModel(
- name='TipoSolicitacao',
+ name="TipoSolicitacao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=100)),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'tipo de solicita\xe7\xe3o',
- 'verbose_name_plural': 'Tipos de solicita\xe7\xe3o',
+ "ordering": ("nome",),
+ "verbose_name": "tipo de solicita\xe7\xe3o",
+ "verbose_name_plural": "Tipos de solicita\xe7\xe3o",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='convenio',
- name='data_solicitacao',
- field=models.DateField(null=True, verbose_name='data do e-mail de solicita\xe7\xe3o', blank=True),
+ model_name="convenio",
+ name="data_solicitacao",
+ field=models.DateField(
+ null=True,
+ verbose_name="data do e-mail de solicita\xe7\xe3o",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='tipo_solicitacao',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='tipo de solicita\xe7\xe3o', blank=True, to='convenios.TipoSolicitacao', null=True),
+ model_name="convenio",
+ name="tipo_solicitacao",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="tipo de solicita\xe7\xe3o",
+ blank=True,
+ to="convenios.TipoSolicitacao",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0008_auto_20210422_1907.py b/sigi/apps/convenios/migrations/0008_auto_20210422_1907.py
index 83f1aec..a3f0f23 100644
--- a/sigi/apps/convenios/migrations/0008_auto_20210422_1907.py
+++ b/sigi/apps/convenios/migrations/0008_auto_20210422_1907.py
@@ -7,27 +7,47 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0004_auto_20210422_1907'),
- ('convenios', '0007_auto_20210416_0918'),
+ ("servidores", "0004_auto_20210422_1907"),
+ ("convenios", "0007_auto_20210416_0918"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='servico_gestao',
- field=models.ForeignKey(related_name='convenios_geridos', on_delete=django.db.models.deletion.SET_NULL, verbose_name='servi\xe7o de gest\xe3o', blank=True, to='servidores.Servico', null=True),
+ model_name="convenio",
+ name="servico_gestao",
+ field=models.ForeignKey(
+ related_name="convenios_geridos",
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="servi\xe7o de gest\xe3o",
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='servidor_gestao',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='servidor de gest\xe3o', blank=True, to='servidores.Servidor', null=True),
+ model_name="convenio",
+ name="servidor_gestao",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="servidor de gest\xe3o",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convenio',
- name='acompanha',
- field=models.ForeignKey(related_name='convenios_acompanhados', on_delete=django.db.models.deletion.SET_NULL, verbose_name='acompanhado por', blank=True, to='servidores.Servidor', null=True),
+ model_name="convenio",
+ name="acompanha",
+ field=models.ForeignKey(
+ related_name="convenios_acompanhados",
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="acompanhado por",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0009_auto_20210611_0946.py b/sigi/apps/convenios/migrations/0009_auto_20210611_0946.py
index 7d39264..6b57de9 100644
--- a/sigi/apps/convenios/migrations/0009_auto_20210611_0946.py
+++ b/sigi/apps/convenios/migrations/0009_auto_20210611_0946.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0008_auto_20210422_1907'),
+ ("convenios", "0008_auto_20210422_1907"),
]
operations = [
migrations.AlterModelOptions(
- name='projeto',
- options={'ordering': ('nome',)},
+ name="projeto",
+ options={"ordering": ("nome",)},
),
]
diff --git a/sigi/apps/convenios/migrations/0010_auto_20210819_0833.py b/sigi/apps/convenios/migrations/0010_auto_20210819_0833.py
index 8c8a8ac..1fc9795 100644
--- a/sigi/apps/convenios/migrations/0010_auto_20210819_0833.py
+++ b/sigi/apps/convenios/migrations/0010_auto_20210819_0833.py
@@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0009_auto_20210611_0946'),
+ ("convenios", "0009_auto_20210611_0946"),
]
operations = [
migrations.AlterField(
- model_name='convenio',
- name='data_retorno_assinatura',
- field=models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='data in\xedcio vig\xeancia', blank=True),
+ model_name="convenio",
+ name="data_retorno_assinatura",
+ field=models.DateField(
+ help_text="Conv\xeanio firmado.",
+ null=True,
+ verbose_name="data in\xedcio vig\xeancia",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py b/sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py
index 5eb61ad..0838215 100644
--- a/sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py
+++ b/sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py
@@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0010_auto_20210819_0833'),
+ ("convenios", "0010_auto_20210819_0833"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='data_termino_vigencia',
- field=models.DateField(help_text='T\xe9rmino da vig\xeancia do conv\xeanio.', null=True, verbose_name='Data t\xe9rmino vig\xeancia', blank=True),
+ model_name="convenio",
+ name="data_termino_vigencia",
+ field=models.DateField(
+ help_text="T\xe9rmino da vig\xeancia do conv\xeanio.",
+ null=True,
+ verbose_name="Data t\xe9rmino vig\xeancia",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0012_auto_20210831_0844.py b/sigi/apps/convenios/migrations/0012_auto_20210831_0844.py
index 5536a9e..e9f19e1 100644
--- a/sigi/apps/convenios/migrations/0012_auto_20210831_0844.py
+++ b/sigi/apps/convenios/migrations/0012_auto_20210831_0844.py
@@ -2,11 +2,12 @@ from __future__ import unicode_literals
from datetime import date
from django.db import models, migrations
+
def migra_data_termino_vigencia(apps, schema_editor):
- Convenio = apps.get_model('convenios', 'Convenio')
+ Convenio = apps.get_model("convenios", "Convenio")
for c in Convenio.objects.all():
- if (c.data_retorno_assinatura is None or c.duracao is None):
+ if c.data_retorno_assinatura is None or c.duracao is None:
continue
ano = c.data_retorno_assinatura.year + int(c.duracao / 12)
@@ -18,7 +19,7 @@ def migra_data_termino_vigencia(apps, schema_editor):
while True:
try:
- data_fim = date(year=ano, month=mes,day=dia)
+ data_fim = date(year=ano, month=mes, day=dia)
break
except:
dia = dia - 1
@@ -26,10 +27,11 @@ def migra_data_termino_vigencia(apps, schema_editor):
c.data_termino_vigencia = data_fim
c.save()
+
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0011_convenio_data_termino_vigencia'),
+ ("convenios", "0011_convenio_data_termino_vigencia"),
]
operations = [
diff --git a/sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py b/sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py
index 41a399c..409dfbd 100644
--- a/sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py
+++ b/sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0012_auto_20210831_0844'),
+ ("convenios", "0012_auto_20210831_0844"),
]
operations = [
migrations.RemoveField(
- model_name='convenio',
- name='duracao',
+ model_name="convenio",
+ name="duracao",
),
]
diff --git a/sigi/apps/convenios/migrations/0014_gescon.py b/sigi/apps/convenios/migrations/0014_gescon.py
index 05beb81..247e3a8 100644
--- a/sigi/apps/convenios/migrations/0014_gescon.py
+++ b/sigi/apps/convenios/migrations/0014_gescon.py
@@ -6,23 +6,65 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0013_remove_convenio_duracao'),
+ ("convenios", "0013_remove_convenio_duracao"),
]
operations = [
migrations.CreateModel(
- name='Gescon',
+ name="Gescon",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('url_gescon', models.URLField(default='https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie={s}', help_text='Informe o ponto de consulta do webservice do Gescon, inclusive com a querystring. No ponto onde deve ser inserida a sigla da subespecie do contrato, use a marca\xe7\xe3o {s}.Por exemplo: https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie={s} ', verbose_name='Webservice Gescon')),
- ('subespecies', models.TextField(default='AC=ACT\nPI=PI\nCN=PML\nTA=PML', help_text='Informe as siglas das subesp\xe9cies de contratos que devem ser pesquisados no Gescon com a sigla correspondente do projeto no SIGI. Coloque um par de siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. As siglas n\xe3o encontradas ser\xe3o ignoradas.', verbose_name='Subesp\xe9cies')),
- ('palavras', models.TextField(default='ILB\nINTERLEGIS', help_text='Palavras que devem aparecer no campo OBJETO dos dados do Gescon para identificar se o contrato pertence ao ILB. Informe uma palavra por linha. Ocorrendo qualquer uma das palavras, o contrato ser\xe1 importado. ', verbose_name='Palavras de filtro')),
- ('email', models.EmailField(help_text='Caixa de e-mail para onde o relat\xf3rio di\xe1rio de importa\xe7\xe3o ser\xe1 enviado.', max_length=75, verbose_name='E-mail')),
- ('ultima_importacao', models.TextField(verbose_name='Resultado da \xfaltima importa\xe7\xe3o', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "url_gescon",
+ models.URLField(
+ default="https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie={s}",
+ help_text="Informe o ponto de consulta do webservice do Gescon, inclusive com a querystring. No ponto onde deve ser inserida a sigla da subespecie do contrato, use a marca\xe7\xe3o {s}.Por exemplo: https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie={s} ",
+ verbose_name="Webservice Gescon",
+ ),
+ ),
+ (
+ "subespecies",
+ models.TextField(
+ default="AC=ACT\nPI=PI\nCN=PML\nTA=PML",
+ help_text="Informe as siglas das subesp\xe9cies de contratos que devem ser pesquisados no Gescon com a sigla correspondente do projeto no SIGI. Coloque um par de siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. As siglas n\xe3o encontradas ser\xe3o ignoradas.",
+ verbose_name="Subesp\xe9cies",
+ ),
+ ),
+ (
+ "palavras",
+ models.TextField(
+ default="ILB\nINTERLEGIS",
+ help_text="Palavras que devem aparecer no campo OBJETO dos dados do Gescon para identificar se o contrato pertence ao ILB. Informe uma palavra por linha. Ocorrendo qualquer uma das palavras, o contrato ser\xe1 importado. ",
+ verbose_name="Palavras de filtro",
+ ),
+ ),
+ (
+ "email",
+ models.EmailField(
+ help_text="Caixa de e-mail para onde o relat\xf3rio di\xe1rio de importa\xe7\xe3o ser\xe1 enviado.",
+ max_length=75,
+ verbose_name="E-mail",
+ ),
+ ),
+ (
+ "ultima_importacao",
+ models.TextField(
+ verbose_name="Resultado da \xfaltima importa\xe7\xe3o",
+ blank=True,
+ ),
+ ),
],
options={
- 'verbose_name': 'Configura\xe7\xe3o do Gescon',
- 'verbose_name_plural': 'Configura\xe7\xf5es do Gescon',
+ "verbose_name": "Configura\xe7\xe3o do Gescon",
+ "verbose_name_plural": "Configura\xe7\xf5es do Gescon",
},
bases=(models.Model,),
),
diff --git a/sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py b/sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py
index b5b338a..69d7777 100644
--- a/sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py
+++ b/sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py
@@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0014_gescon'),
+ ("convenios", "0014_gescon"),
]
operations = [
migrations.RemoveField(
- model_name='convenio',
- name='search_text',
+ model_name="convenio",
+ name="search_text",
),
]
diff --git a/sigi/apps/convenios/migrations/0016_auto_20210909_0732.py b/sigi/apps/convenios/migrations/0016_auto_20210909_0732.py
index f6c565f..c74569f 100644
--- a/sigi/apps/convenios/migrations/0016_auto_20210909_0732.py
+++ b/sigi/apps/convenios/migrations/0016_auto_20210909_0732.py
@@ -6,20 +6,27 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0015_remove_convenio_search_text'),
+ ("convenios", "0015_remove_convenio_search_text"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='atualizacao_gescon',
- field=models.DateTimeField(null=True, verbose_name='Data de atualiza\xe7\xe3o pelo Gescon', blank=True),
+ model_name="convenio",
+ name="atualizacao_gescon",
+ field=models.DateTimeField(
+ null=True,
+ verbose_name="Data de atualiza\xe7\xe3o pelo Gescon",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convenio',
- name='observacao_gescon',
- field=models.TextField(verbose_name='Observa\xe7\xf5es da atualiza\xe7\xe3o do Gescon', blank=True),
+ model_name="convenio",
+ name="observacao_gescon",
+ field=models.TextField(
+ verbose_name="Observa\xe7\xf5es da atualiza\xe7\xe3o do Gescon",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py b/sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py
index 270e601..de8df4c 100644
--- a/sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py
+++ b/sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py
@@ -6,14 +6,20 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0016_auto_20210909_0732'),
+ ("convenios", "0016_auto_20210909_0732"),
]
operations = [
migrations.AddField(
- model_name='convenio',
- name='id_contrato_gescon',
- field=models.CharField(default='', verbose_name='ID do contrato no Gescon', max_length=20, editable=False, blank=True),
+ model_name="convenio",
+ name="id_contrato_gescon",
+ field=models.CharField(
+ default="",
+ verbose_name="ID do contrato no Gescon",
+ max_length=20,
+ editable=False,
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0018_auto_20211208_1256.py b/sigi/apps/convenios/migrations/0018_auto_20211208_1256.py
index 1755956..2fc383a 100644
--- a/sigi/apps/convenios/migrations/0018_auto_20211208_1256.py
+++ b/sigi/apps/convenios/migrations/0018_auto_20211208_1256.py
@@ -7,14 +7,18 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0017_convenio_id_contrato_gescon'),
+ ("convenios", "0017_convenio_id_contrato_gescon"),
]
operations = [
migrations.AlterField(
- model_name='convenio',
- name='projeto',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo de Convenio', to='convenios.Projeto'),
+ model_name="convenio",
+ name="projeto",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Tipo de Convenio",
+ to="convenios.Projeto",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/convenios/migrations/0019_alter_anexo_arquivo_alter_anexo_descricao_and_more.py b/sigi/apps/convenios/migrations/0019_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
index 62ae556..e3fee8d 100644
--- a/sigi/apps/convenios/migrations/0019_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
+++ b/sigi/apps/convenios/migrations/0019_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
@@ -6,88 +6,147 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0018_auto_20211208_1256'),
+ ("convenios", "0018_auto_20211208_1256"),
]
operations = [
migrations.AlterField(
- model_name='anexo',
- name='arquivo',
- field=models.FileField(max_length=500, upload_to='apps/convenios/anexo/arquivo'),
- ),
- migrations.AlterField(
- model_name='anexo',
- name='descricao',
- field=models.CharField(max_length=70, verbose_name='descrição'),
- ),
- migrations.AlterField(
- model_name='anexo',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='convenio',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='convenio',
- name='id_contrato_gescon',
- field=models.CharField(blank=True, default='', editable=False, max_length=20, verbose_name='ID do contrato no Gescon'),
- ),
- migrations.AlterField(
- model_name='equipamentoprevisto',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='gescon',
- name='email',
- field=models.EmailField(help_text='Caixa de e-mail para onde o relatório diário de importação será enviado.', max_length=254, verbose_name='E-mail'),
- ),
- migrations.AlterField(
- model_name='gescon',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='projeto',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='statusconvenio',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='tiposolicitacao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='tramitacao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='tramitacao',
- name='observacao',
- field=models.CharField(blank=True, max_length=512, null=True, verbose_name='observação'),
- ),
- migrations.AlterField(
- model_name='unidadeadministrativa',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
- ),
- migrations.AlterField(
- model_name='unidadeadministrativa',
- name='nome',
+ model_name="anexo",
+ name="arquivo",
+ field=models.FileField(
+ max_length=500, upload_to="apps/convenios/anexo/arquivo"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="anexo",
+ name="descricao",
+ field=models.CharField(max_length=70, verbose_name="descrição"),
+ ),
+ migrations.AlterField(
+ model_name="anexo",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="convenio",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="convenio",
+ name="id_contrato_gescon",
+ field=models.CharField(
+ blank=True,
+ default="",
+ editable=False,
+ max_length=20,
+ verbose_name="ID do contrato no Gescon",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="equipamentoprevisto",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="gescon",
+ name="email",
+ field=models.EmailField(
+ help_text="Caixa de e-mail para onde o relatório diário de importação será enviado.",
+ max_length=254,
+ verbose_name="E-mail",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="gescon",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="projeto",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="statusconvenio",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="tiposolicitacao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="tramitacao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="tramitacao",
+ name="observacao",
+ field=models.CharField(
+ blank=True, max_length=512, null=True, verbose_name="observação"
+ ),
+ ),
+ migrations.AlterField(
+ model_name="unidadeadministrativa",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="unidadeadministrativa",
+ name="nome",
field=models.CharField(max_length=100),
),
migrations.AlterField(
- model_name='unidadeadministrativa',
- name='sigla',
+ model_name="unidadeadministrativa",
+ name="sigla",
field=models.CharField(max_length=10),
),
]
diff --git a/sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py b/sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py
index 22adc43..9eab6be 100644
--- a/sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py
+++ b/sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py
@@ -6,13 +6,20 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0019_alter_anexo_arquivo_alter_anexo_descricao_and_more'),
+ (
+ "convenios",
+ "0019_alter_anexo_arquivo_alter_anexo_descricao_and_more",
+ ),
]
operations = [
migrations.AddField(
- model_name='gescon',
- name='orgaos_gestores',
- field=models.TextField(default='SCCO', help_text='Siglas de órgãos gestores que devem aparecer no campoORGAOSGESTORESTITULARESInforme um sigla por linha. Ocorrendo qualquer uma das siglas, o contrato será importado. ', verbose_name='Órgãos gestores'),
+ model_name="gescon",
+ name="orgaos_gestores",
+ field=models.TextField(
+ default="SCCO",
+ help_text="Siglas de órgãos gestores que devem aparecer no campoORGAOSGESTORESTITULARESInforme um sigla por linha. Ocorrendo qualquer uma das siglas, o contrato será importado. ",
+ verbose_name="Órgãos gestores",
+ ),
),
]
diff --git a/sigi/apps/convenios/models.py b/sigi/apps/convenios/models.py
index 6e450d7..22d6319 100644
--- a/sigi/apps/convenios/models.py
+++ b/sigi/apps/convenios/models.py
@@ -20,99 +20,93 @@ class Projeto(models.Model):
return self.sigla
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
+
class StatusConvenio(models.Model):
nome = models.CharField(max_length=100)
cancela = models.BooleanField(_("Cancela o convênio"), default=False)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
verbose_name = _("Estado de convenios")
verbose_name_plural = _("Estados de convenios")
def __str__(self):
return self.nome
+
class TipoSolicitacao(models.Model):
nome = models.CharField(max_length=100)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
verbose_name = _("tipo de solicitação")
verbose_name_plural = _("Tipos de solicitação")
def __str__(self):
return self.nome
+
class Convenio(models.Model):
casa_legislativa = models.ForeignKey(
- 'casas.Orgao',
+ "casas.Orgao",
on_delete=models.PROTECT,
- verbose_name=_('órgão conveniado')
+ verbose_name=_("órgão conveniado"),
)
projeto = models.ForeignKey(
- Projeto,
- on_delete=models.PROTECT,
- verbose_name=_('Tipo de Convenio')
+ Projeto, on_delete=models.PROTECT, verbose_name=_("Tipo de Convenio")
)
# numero designado pelo Senado Federal para o convênio
num_processo_sf = models.CharField(
- _('número do processo SF (Senado Federal)'),
+ _("número do processo SF (Senado Federal)"),
max_length=20,
blank=True,
- help_text=_('Formatos: Antigo: XXXXXX/XX-X .SIGAD: XXXXX.XXXXXX/XXXX-XX ')
+ help_text=_(
+ "Formatos: Antigo: XXXXXX/XX-X .SIGAD: XXXXX.XXXXXX/XXXX-XX "
+ ),
)
# link_processo_stf = ('get_sigad_url')
num_convenio = models.CharField(
- _('número do convênio'),
- max_length=10,
- blank=True
+ _("número do convênio"), max_length=10, blank=True
)
id_contrato_gescon = models.CharField(
_("ID do contrato no Gescon"),
max_length=20,
blank=True,
default="",
- editable=False
+ editable=False,
)
data_sigi = models.DateField(
- _("data de cadastro no SIGI"),
- blank=True,
- null=True,
- auto_now_add=True
+ _("data de cadastro no SIGI"), blank=True, null=True, auto_now_add=True
)
data_sigad = models.DateField(
- _("data de cadastro no SIGAD"),
- null=True,
- blank=True
+ _("data de cadastro no SIGAD"), null=True, blank=True
)
data_solicitacao = models.DateField(
- _("data do e-mail de solicitação"),
- null=True,
- blank=True
+ _("data do e-mail de solicitação"), null=True, blank=True
)
tipo_solicitacao = models.ForeignKey(
TipoSolicitacao,
on_delete=models.PROTECT,
null=True,
blank=True,
- verbose_name=_("tipo de solicitação")
+ verbose_name=_("tipo de solicitação"),
)
status = models.ForeignKey(
StatusConvenio,
on_delete=models.SET_NULL,
verbose_name=_("estado atual"),
null=True,
- blank=True
+ blank=True,
)
acompanha = models.ForeignKey(
Servidor,
on_delete=models.SET_NULL,
- related_name='convenios_acompanhados',
+ related_name="convenios_acompanhados",
verbose_name=_("acompanhado por"),
null=True,
- blank=True
+ blank=True,
)
observacao = models.TextField(
_("observações"),
@@ -124,77 +118,72 @@ class Convenio(models.Model):
on_delete=models.SET_NULL,
null=True,
blank=True,
- related_name='convenios_geridos',
- verbose_name=_("serviço de gestão")
+ related_name="convenios_geridos",
+ verbose_name=_("serviço de gestão"),
)
servidor_gestao = models.ForeignKey(
Servidor,
on_delete=models.SET_NULL,
null=True,
blank=True,
- verbose_name=_("servidor de gestão")
+ verbose_name=_("servidor de gestão"),
)
data_adesao = models.DateField(
- _('aderidas'),
+ _("aderidas"),
null=True,
blank=True,
)
data_retorno_assinatura = models.DateField(
- _('data início vigência'),
+ _("data início vigência"),
null=True,
blank=True,
- help_text=_('Convênio firmado.')
+ help_text=_("Convênio firmado."),
)
data_termino_vigencia = models.DateField(
- _('Data término vigência'),
+ _("Data término vigência"),
null=True,
blank=True,
- help_text=_('Término da vigência do convênio.')
+ help_text=_("Término da vigência do convênio."),
)
data_pub_diario = models.DateField(
- _('data da publicação no Diário Oficial'),
- null=True,
- blank=True
+ _("data da publicação no Diário Oficial"), null=True, blank=True
)
data_termo_aceite = models.DateField(
- _('equipadas'),
+ _("equipadas"),
null=True,
blank=True,
- help_text=_('Equipamentos recebidos.')
+ help_text=_("Equipamentos recebidos."),
)
data_devolucao_via = models.DateField(
- _('data de devolução da via'),
+ _("data de devolução da via"),
null=True,
blank=True,
- help_text=_('Data de devolução da via do convênio à Câmara Municipal.')
+ help_text=_("Data de devolução da via do convênio à Câmara Municipal."),
)
data_postagem_correio = models.DateField(
- _('data postagem correio'),
+ _("data postagem correio"),
null=True,
blank=True,
)
data_devolucao_sem_assinatura = models.DateField(
- _('data de devolução por falta de assinatura'),
+ _("data de devolução por falta de assinatura"),
null=True,
blank=True,
- help_text=_('Data de devolução por falta de assinatura'),
+ help_text=_("Data de devolução por falta de assinatura"),
)
data_retorno_sem_assinatura = models.DateField(
- _('data do retorno sem assinatura'),
+ _("data do retorno sem assinatura"),
null=True,
blank=True,
- help_text=_('Data do retorno do convênio sem assinatura'),
+ help_text=_("Data do retorno do convênio sem assinatura"),
)
conveniada = models.BooleanField(default=False)
equipada = models.BooleanField(default=False)
atualizacao_gescon = models.DateTimeField(
- _("Data de atualização pelo Gescon"),
- blank=True,
- null=True
+ _("Data de atualização pelo Gescon"), blank=True, null=True
)
observacao_gescon = models.TextField(
- _("Observações da atualização do Gescon"),
- blank=True
+ _("Observações da atualização do Gescon"), blank=True
)
def get_status(self):
@@ -207,12 +196,16 @@ class Convenio(models.Model):
return _("Vencido")
return _("Vigente")
- if (self.data_retorno_assinatura is None and
- self.data_devolucao_sem_assinatura is None and
- self.data_retorno_sem_assinatura is None):
+ if (
+ self.data_retorno_assinatura is None
+ and self.data_devolucao_sem_assinatura is None
+ and self.data_retorno_sem_assinatura is None
+ ):
return _("Pendente")
- if (self.data_devolucao_sem_assinatura is not None or
- self.data_retorno_sem_assinatura is not None):
+ if (
+ self.data_devolucao_sem_assinatura is not None
+ or self.data_retorno_sem_assinatura is not None
+ ):
return _("Desistência")
return _("Indefinido")
@@ -224,14 +217,14 @@ class Convenio(models.Model):
def get_sigad_url(self):
m = re.match(
- r'(?P00100|00200)\.(?P\d{6})/(?P\d{4})-\d{2}',
- self.num_processo_sf
+ r"(?P00100|00200)\.(?P\d{6})/(?P\d{4})-\d{2}",
+ self.num_processo_sf,
)
if m:
orgao, sequencial, ano = m.groups()
return (
f'{self.num_processo_sf} '
)
@@ -243,78 +236,82 @@ class Convenio(models.Model):
super(Convenio, self).save(*args, **kwargs)
class Meta:
- get_latest_by = 'id'
- ordering = ('id',)
- verbose_name = _('convênio')
+ get_latest_by = "id"
+ ordering = ("id",)
+ verbose_name = _("convênio")
def __str__(self):
from django.conf import settings
+
SDF = settings.SHORT_DATE_FORMAT
number = self.num_convenio
- project=self.projeto.sigla
- if ((self.data_retorno_assinatura is None) and
- (self.equipada and self.data_termo_aceite is not None)):
+ project = self.projeto.sigla
+ if (self.data_retorno_assinatura is None) and (
+ self.equipada and self.data_termo_aceite is not None
+ ):
date = date_format(self.data_termo_aceite, SDF)
return _(f"{project} nº {number} - equipada em {date}")
elif self.data_retorno_assinatura is None:
- date = (date_format(self.data_adesao, SDF)
- if self.data_adesao else "")
+ date = (
+ date_format(self.data_adesao, SDF) if self.data_adesao else ""
+ )
return _(f"{project}, nº {number}, início em {date}")
- if ((self.data_retorno_assinatura is not None) and not
- (self.equipada and self.data_termo_aceite is not None)):
+ if (self.data_retorno_assinatura is not None) and not (
+ self.equipada and self.data_termo_aceite is not None
+ ):
date = date_format(self.data_retorno_assinatura, SDF)
- status=self.get_status()
+ status = self.get_status()
return _(
f"{project}, nº {number}, inicio em {date}. Status: {status}"
)
- if ((self.data_retorno_assinatura is not None) and
- (self.equipada and self.data_termo_aceite is not None)):
+ if (self.data_retorno_assinatura is not None) and (
+ self.equipada and self.data_termo_aceite is not None
+ ):
date = date_format(self.data_retorno_assinatura, SDF)
- equipped_date=date_format(self.data_termo_aceite, SDF)
+ equipped_date = date_format(self.data_termo_aceite, SDF)
return _(
f"{project}, nº {number}, início em {date} e equipada em "
f"{equipped_date}. Status: {self.get_status()}"
)
+
class EquipamentoPrevisto(models.Model):
convenio = models.ForeignKey(
- Convenio,
- on_delete=models.CASCADE,
- verbose_name=_('convênio')
+ Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
)
equipamento = models.ForeignKey(
- 'inventario.Equipamento',
- on_delete=models.CASCADE
+ "inventario.Equipamento", on_delete=models.CASCADE
)
quantidade = models.PositiveSmallIntegerField(default=1)
class Meta:
- verbose_name = _('equipamento previsto')
- verbose_name_plural = _('equipamentos previstos')
+ verbose_name = _("equipamento previsto")
+ verbose_name_plural = _("equipamentos previstos")
def __str__(self):
return _(f"{self.quantidade} {self.equipamento}(s)")
+
class Anexo(models.Model):
convenio = models.ForeignKey(
- Convenio,
- on_delete=models.CASCADE,
- verbose_name=_('convênio')
+ Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
)
# caminho no sistema para o documento anexo
- arquivo = models.FileField(upload_to='apps/convenios/anexo/arquivo', max_length=500)
- descricao = models.CharField(_('descrição'), max_length=70)
+ arquivo = models.FileField(
+ upload_to="apps/convenios/anexo/arquivo", max_length=500
+ )
+ descricao = models.CharField(_("descrição"), max_length=70)
data_pub = models.DateTimeField(
- _('data da publicação do anexo'),
- default=datetime.now
+ _("data da publicação do anexo"), default=datetime.now
)
class Meta:
- ordering = ('-data_pub',)
+ ordering = ("-data_pub",)
def __str__(self):
return _(f"{self.descricao} publicado em {self.data_pub}")
+
class UnidadeAdministrativa(models.Model):
sigla = models.CharField(max_length=10)
nome = models.CharField(max_length=100)
@@ -322,82 +319,93 @@ class UnidadeAdministrativa(models.Model):
def __str__(self):
return self.sigla
+
class Tramitacao(models.Model):
convenio = models.ForeignKey(
- Convenio,
- on_delete=models.CASCADE,
- verbose_name=_('convênio')
+ Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
)
unid_admin = models.ForeignKey(
UnidadeAdministrativa,
on_delete=models.PROTECT,
- verbose_name=_('Unidade Administrativa')
+ verbose_name=_("Unidade Administrativa"),
)
data = models.DateField()
observacao = models.CharField(
- _('observação'),
+ _("observação"),
max_length=512,
null=True,
blank=True,
)
class Meta:
- verbose_name_plural = _('Tramitações')
+ verbose_name_plural = _("Tramitações")
def __str__(self):
- in_date = _(f"em {self.data}") # for focused translation
+ in_date = _(f"em {self.data}") # for focused translation
result = f"{self.unid_admin} {in_date}"
if self.observacao:
result = f"{result} ({self.observacao})"
return result
+
class Gescon(models.Model):
url_gescon = models.URLField(
_("Webservice Gescon"),
- default=("https://adm.senado.gov.br/gestao-contratos/api/contratos"
- "/busca?especie={s}"),
- help_text=_("Informe o ponto de consulta do webservice do Gescon, "
- "inclusive com a querystring. No ponto onde deve ser "
- "inserida a sigla da subespecie do contrato, use a "
- "marcação {s}.Por exemplo: "
- "https://adm.senado.gov.br/gestao-contratos/api/contratos"
- "/busca?especie={s} ")
+ default=(
+ "https://adm.senado.gov.br/gestao-contratos/api/contratos"
+ "/busca?especie={s}"
+ ),
+ help_text=_(
+ "Informe o ponto de consulta do webservice do Gescon, "
+ "inclusive com a querystring. No ponto onde deve ser "
+ "inserida a sigla da subespecie do contrato, use a "
+ "marcação {s}.Por exemplo: "
+ "https://adm.senado.gov.br/gestao-contratos/api/contratos"
+ "/busca?especie={s} "
+ ),
)
subespecies = models.TextField(
_("Subespécies"),
default="AC=ACT\nPI=PI\nCN=PML\nTA=PML",
- help_text=_("Informe as siglas das subespécies de contratos que "
- "devem ser pesquisados no Gescon com a sigla "
- "correspondente do projeto no SIGI. Coloque um par de "
- "siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. "
- "As siglas não encontradas serão ignoradas.")
+ help_text=_(
+ "Informe as siglas das subespécies de contratos que "
+ "devem ser pesquisados no Gescon com a sigla "
+ "correspondente do projeto no SIGI. Coloque um par de "
+ "siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. "
+ "As siglas não encontradas serão ignoradas."
+ ),
)
palavras = models.TextField(
_("Palavras de filtro"),
default="ILB\nINTERLEGIS",
- help_text=_("Palavras que devem aparecer no campo OBJETO dos dados do "
- "Gescon para identificar se o contrato pertence ao ILB. "
- "Informe uma palavra por linha. "
- "Ocorrendo qualquer uma das palavras, o contrato será "
- "importado. ")
+ help_text=_(
+ "Palavras que devem aparecer no campo OBJETO dos dados do "
+ "Gescon para identificar se o contrato pertence ao ILB. "
+ "Informe uma palavra por linha. "
+ "Ocorrendo qualquer uma das palavras, o contrato será "
+ "importado. "
+ ),
)
orgaos_gestores = models.TextField(
_("Órgãos gestores"),
default="SCCO",
- help_text=_("Siglas de órgãos gestores que devem aparecer no campo"
- "ORGAOSGESTORESTITULARES"
- "Informe um sigla por linha. "
- "Ocorrendo qualquer uma das siglas, o contrato será "
- "importado. ")
+ help_text=_(
+ "Siglas de órgãos gestores que devem aparecer no campo"
+ "ORGAOSGESTORESTITULARES"
+ "Informe um sigla por linha. "
+ "Ocorrendo qualquer uma das siglas, o contrato será "
+ "importado. "
+ ),
)
email = models.EmailField(
_("E-mail"),
- help_text=_("Caixa de e-mail para onde o relatório diário de "
- "importação será enviado.")
+ help_text=_(
+ "Caixa de e-mail para onde o relatório diário de "
+ "importação será enviado."
+ ),
)
ultima_importacao = models.TextField(
- _("Resultado da última importação"),
- blank=True
+ _("Resultado da última importação"), blank=True
)
class Meta:
@@ -408,11 +416,11 @@ class Gescon(models.Model):
return self.url_gescon
def save(self, *args, **kwargs):
- self.pk = 1 # Highlander (singleton pattern)
+ self.pk = 1 # Highlander (singleton pattern)
return super(Gescon, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- pass # Highlander is immortal
+ pass # Highlander is immortal
def add_message(self, msg, save=False):
self.ultima_importacao += msg + "\n"
@@ -426,7 +434,7 @@ class Gescon(models.Model):
subject=_("Relatório de importação GESCON"),
message=self.ultima_importacao,
recipient_list=self.email,
- fail_silently=True
+ fail_silently=True,
)
else:
self.ultima_importacao += _(
@@ -438,17 +446,25 @@ class Gescon(models.Model):
def importa_contratos(self):
self.ultima_importacao = ""
self.add_message(
- _(f"Importação iniciada em {datetime.now():%d/%m/%Y %H:%M:%S}\n"
- "==========================================================\n")
+ _(
+ f"Importação iniciada em {datetime.now():%d/%m/%Y %H:%M:%S}\n"
+ "==========================================================\n"
+ )
)
if self.palavras == "" or self.orgaos_gestores == "":
- self.add_message(_("Nenhuma palavra de pesquisa ou orgãos "
- "gestores definidos - processo abortado."), True)
+ self.add_message(
+ _(
+ "Nenhuma palavra de pesquisa ou orgãos "
+ "gestores definidos - processo abortado."
+ ),
+ True,
+ )
if self.subespecies == "":
- self.add_message(_("Nenhuma subespécie definida - processo "
- "abortado."), True)
+ self.add_message(
+ _("Nenhuma subespécie definida - processo " "abortado."), True
+ )
return
if "{s}" not in self.url_gescon:
@@ -458,16 +474,18 @@ class Gescon(models.Model):
"inserir a sigla da subespécia na consulta ao webservice "
"- processo abortado."
),
- True
+ True,
)
return
palavras = self.palavras.split()
orgaos = self.orgaos_gestores.split()
subespecies = {tuple(s.split("=")) for s in self.subespecies.split()}
- lista_cnpj = {re.sub("[^\d]", "", o.cnpj).zfill(14): o
- for o in Orgao.objects.exclude(cnpj="")
- if re.sub("[^\d]", "", o.cnpj) != ''}
+ lista_cnpj = {
+ re.sub("[^\d]", "", o.cnpj).zfill(14): o
+ for o in Orgao.objects.exclude(cnpj="")
+ if re.sub("[^\d]", "", o.cnpj) != ""
+ }
for sigla_gescon, sigla_sigi in subespecies:
self.add_message(_(f"\nImportando subespécie {sigla_gescon}"))
@@ -487,9 +505,13 @@ class Gescon(models.Model):
)
continue
- if not 'application/json' in response.headers.get('Content-Type'):
- self.add_message(_(f"\tResultado da consulta à {url} não "
- "retornou dados em formato json"))
+ if not "application/json" in response.headers.get("Content-Type"):
+ self.add_message(
+ _(
+ f"\tResultado da consulta à {url} não "
+ "retornou dados em formato json"
+ )
+ )
continue
contratos = response.json()
@@ -497,11 +519,14 @@ class Gescon(models.Model):
# Pegar só os contratos que possuem alguma das palavras-chave
nossos = [
- c for c in contratos
- if any(palavra in c['objeto'] for palavra in palavras) or
- any(orgao in c['orgaosGestoresTitulares']
- for orgao in orgaos
- if c['orgaosGestoresTitulares'] is not None)
+ c
+ for c in contratos
+ if any(palavra in c["objeto"] for palavra in palavras)
+ or any(
+ orgao in c["orgaosGestoresTitulares"]
+ for orgao in orgaos
+ if c["orgaosGestoresTitulares"] is not None
+ )
]
self.add_message(
@@ -514,23 +539,25 @@ class Gescon(models.Model):
atualizados = 0
for contrato in nossos:
- numero = contrato['numero'].zfill(8)
+ numero = contrato["numero"].zfill(8)
numero = f"{numero[:4]}/{numero[4:]}"
- sigad = contrato['processo'].zfill(17)
+ sigad = contrato["processo"].zfill(17)
sigad = f"{sigad[:5]}.{sigad[5:11]}/{sigad[11:15]}-{sigad[15:]}"
- if contrato['cnpjCpfFornecedor']:
- cnpj = contrato['cnpjCpfFornecedor'].zfill(14)
- cnpj_masked = (f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/"
- f"{cnpj[8:12]}-{cnpj[12:]}")
+ if contrato["cnpjCpfFornecedor"]:
+ cnpj = contrato["cnpjCpfFornecedor"].zfill(14)
+ cnpj_masked = (
+ f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/"
+ f"{cnpj[8:12]}-{cnpj[12:]}"
+ )
else:
cnpj = None
- if contrato['nomeFornecedor']:
- nome = contrato['nomeFornecedor']
- nome = nome.replace('VEREADORES DE', '')
- nome = nome.split('-')[0]
- nome = nome.split('/')[0]
+ if contrato["nomeFornecedor"]:
+ nome = contrato["nomeFornecedor"]
+ nome = nome.replace("VEREADORES DE", "")
+ nome = nome.split("-")[0]
+ nome = nome.split("/")[0]
nome = nome.strip()
nome = nome.replace(" ", " ")
nome = to_ascii(nome)
@@ -539,8 +566,10 @@ class Gescon(models.Model):
if (cnpj is None) and (nome is None):
self.add_message(
- _(f"\tO contrato {numero} no Gescon não informa o CNPJ"
- "nem o nome do órgão.")
+ _(
+ f"\tO contrato {numero} no Gescon não informa o CNPJ"
+ "nem o nome do órgão."
+ )
)
erros += 1
continue
@@ -555,26 +584,30 @@ class Gescon(models.Model):
orgao = Orgao.objects.get(cnpj=cnpj_masked)
except (
Orgao.DoesNotExist,
- Orgao.MultipleObjectsReturned) as e:
- orgao = None
- pass
+ Orgao.MultipleObjectsReturned,
+ ) as e:
+ orgao = None
+ pass
if (orgao is None) and (nome is not None):
try:
orgao = Orgao.objects.get(search_text__iexact=nome)
except (
Orgao.DoesNotExist,
- Orgao.MultipleObjectsReturned) as e:
- orgao = None
- pass
+ Orgao.MultipleObjectsReturned,
+ ) as e:
+ orgao = None
+ pass
if orgao is None:
self.add_message(
- _(f"\tÓrgão não encontrado no SIGI ou mais de um órgão"
- f"encontrado com o mesmo CNPJ ou nome. Favor "
- f"regularizar o cadastro: "
- f"CNPJ: {contrato['cnpjCpfFornecedor']}, "
- f"Nome: {contrato['nomeFornecedor']}")
+ _(
+ f"\tÓrgão não encontrado no SIGI ou mais de um órgão"
+ f"encontrado com o mesmo CNPJ ou nome. Favor "
+ f"regularizar o cadastro: "
+ f"CNPJ: {contrato['cnpjCpfFornecedor']}, "
+ f"Nome: {contrato['nomeFornecedor']}"
+ )
)
erros += 1
continue
@@ -587,8 +620,7 @@ class Gescon(models.Model):
# NUP não encontrado, talvez exista apenas com o número
# do GESCON
convenios = Convenio.objects.filter(
- Q(num_convenio=numero) |
- Q(num_processo_sf=numero)
+ Q(num_convenio=numero) | Q(num_processo_sf=numero)
)
chk = convenios.count()
if chk > 1:
@@ -608,14 +640,15 @@ class Gescon(models.Model):
num_processo_sf=sigad,
num_convenio=numero,
data_sigi=date.today(),
- data_sigad=contrato['assinatura'],
- observacao=contrato['objeto'],
- data_retorno_assinatura=contrato['inicioVigencia'],
- data_termino_vigencia=contrato['terminoVigencia'],
- data_pub_diario=contrato['publicacao'],
+ data_sigad=contrato["assinatura"],
+ observacao=contrato["objeto"],
+ data_retorno_assinatura=contrato["inicioVigencia"],
+ data_termino_vigencia=contrato["terminoVigencia"],
+ data_pub_diario=contrato["publicacao"],
atualizacao_gescon=datetime.now(),
- observacao_gescon=_("Importado integralmente do"
- "Gescon")
+ observacao_gescon=_(
+ "Importado integralmente do" "Gescon"
+ ),
)
convenio.save()
novos += 1
@@ -623,15 +656,17 @@ class Gescon(models.Model):
elif chk == 1:
convenio = convenios.get()
convenio.atualizacao_gescon = datetime.now()
- convenio.observacao_gescon = ''
+ convenio.observacao_gescon = ""
if convenio.casa_legislativa != orgao:
self.add_message(
- _(f"\tO órgao no convênio {convenio.id} diverge do "
- f"que consta no Gescon ({cnpj}, "
- f"{contrato['nomeFornecedor']})")
+ _(
+ f"\tO órgao no convênio {convenio.id} diverge do "
+ f"que consta no Gescon ({cnpj}, "
+ f"{contrato['nomeFornecedor']})"
+ )
)
convenio.observacao_gescon = _(
- 'ERRO: Órgão diverge do Gescon. Não atualizado!'
+ "ERRO: Órgão diverge do Gescon. Não atualizado!"
)
convenio.save()
erros += 1
@@ -639,11 +674,13 @@ class Gescon(models.Model):
if convenio.num_processo_sf != sigad:
self.add_message(
- _(f"\tO contrato Gescon nº {numero} corresponde"
- f" ao convênio SIGI {convenio.id}, mas o NUP "
- f"sigad diverge (Gescon: {sigad}, "
- f"SIGI: {convenio.num_processo_sf}). "
- "CORRIGIDO!")
+ _(
+ f"\tO contrato Gescon nº {numero} corresponde"
+ f" ao convênio SIGI {convenio.id}, mas o NUP "
+ f"sigad diverge (Gescon: {sigad}, "
+ f"SIGI: {convenio.num_processo_sf}). "
+ "CORRIGIDO!"
+ )
)
convenio.num_processo_sf = sigad
convenio.observacao_gescon += _(
@@ -653,11 +690,13 @@ class Gescon(models.Model):
if convenio.num_convenio != numero:
self.add_message(
- _(f"\tO contrato Gescon ID {contrato['id']} "
- f"corresponde ao convênio SIGI {convenio.id}, "
- "mas o número do convênio diverge ("
- f"Gescon: {numero}, SIGI: {convenio.num_convenio}"
- "). CORRIGIDO!")
+ _(
+ f"\tO contrato Gescon ID {contrato['id']} "
+ f"corresponde ao convênio SIGI {convenio.id}, "
+ "mas o número do convênio diverge ("
+ f"Gescon: {numero}, SIGI: {convenio.num_convenio}"
+ "). CORRIGIDO!"
+ )
)
convenio.num_convenio = numero
convenio.observacao_gescon += _(
@@ -665,23 +704,21 @@ class Gescon(models.Model):
)
alertas += 1
- if contrato['objeto'] not in convenio.observacao:
- convenio.observacao += "\n" + contrato['objeto']
+ if contrato["objeto"] not in convenio.observacao:
+ convenio.observacao += "\n" + contrato["objeto"]
convenio.observacao_gescon += _(
"Observação atualizada.\n"
)
- convenio.data_sigad = contrato['assinatura']
+ convenio.data_sigad = contrato["assinatura"]
convenio.data_retorno_assinatura = contrato[
- 'inicioVigencia'
- ]
- convenio.data_termino_vigencia = contrato[
- 'terminoVigencia'
+ "inicioVigencia"
]
- convenio.data_pub_diario = contrato['publicacao']
- if contrato['codTextoContrato']:
+ convenio.data_termino_vigencia = contrato["terminoVigencia"]
+ convenio.data_pub_diario = contrato["publicacao"]
+ if contrato["codTextoContrato"]:
convenio.id_contrato_gescon = contrato[
- 'codTextoContrato'
+ "codTextoContrato"
]
else:
convenio.id_contrato_gescon = ""
@@ -690,10 +727,12 @@ class Gescon(models.Model):
convenio.save()
except Exception as e:
self.add_message(
- _("Ocorreu um erro ao salvar o convênio "
- f"{convenio.id} no SIGI. Alguma informação do "
- "Gescon pode ter quebrado o sistema. Informe ao "
- f"suporte. Erro: {e.message}")
+ _(
+ "Ocorreu um erro ao salvar o convênio "
+ f"{convenio.id} no SIGI. Alguma informação do "
+ "Gescon pode ter quebrado o sistema. Informe ao "
+ f"suporte. Erro: {e.message}"
+ )
)
erros += 1
continue
@@ -701,17 +740,21 @@ class Gescon(models.Model):
atualizados += 1
else:
self.add_message(
- _(f"\tExistem {chk} convênios no SIGI que "
- "correspondem ao mesmo contrato no Gescon (contrato "
- f"{numero}, sigad {sigad})")
+ _(
+ f"\tExistem {chk} convênios no SIGI que "
+ "correspondem ao mesmo contrato no Gescon (contrato "
+ f"{numero}, sigad {sigad})"
+ )
)
erros += 1
continue
self.add_message(
- _(f"\t{novos} novos convenios adicionados ao SIGI, "
- f"{atualizados} atualizados, sendo {alertas} com alertas, e "
- f"{erros} reportados com erro.")
+ _(
+ f"\t{novos} novos convenios adicionados ao SIGI, "
+ f"{atualizados} atualizados, sendo {alertas} com alertas, e "
+ f"{erros} reportados com erro."
+ )
)
self.save()
diff --git a/sigi/apps/convenios/reports.py b/sigi/apps/convenios/reports.py
index f0893ca..60f0fdd 100644
--- a/sigi/apps/convenios/reports.py
+++ b/sigi/apps/convenios/reports.py
@@ -1,11 +1,17 @@
from django.utils.translation import gettext as _
-from geraldo import ReportBand, ObjectValue, Label, ReportGroup, FIELD_ACTION_SUM
+from geraldo import (
+ ReportBand,
+ ObjectValue,
+ Label,
+ ReportGroup,
+ FIELD_ACTION_SUM,
+)
from reportlab.lib.units import cm
from sigi.apps.relatorios.reports import ReportDefault
-#from abc import ABCMeta
+# from abc import ABCMeta
class CasasAderidasReport(object):
@@ -25,7 +31,7 @@ class SemEquipamentosReport(object):
class ConvenioReport(ReportDefault):
- title = _('Relatório de Parcerias')
+ title = _("Relatório de Parcerias")
class band_page_header(ReportDefault.band_page_header):
@@ -86,40 +92,41 @@ class ConvenioReport(ReportDefault):
elements = [
ObjectValue(
- attribute_name='casa_legislativa.municipio.uf.sigla',
- left=label_left[0] * cm
- ),
- ObjectValue(
- attribute_name='casa_legislativa.municipio.nome',
- left=label_left[1] * cm
+ attribute_name="casa_legislativa.municipio.uf.sigla",
+ left=label_left[0] * cm,
),
ObjectValue(
- attribute_name='num_convenio',
- left=label_left[2] * cm
+ attribute_name="casa_legislativa.municipio.nome",
+ left=label_left[1] * cm,
),
+ ObjectValue(attribute_name="num_convenio", left=label_left[2] * cm),
ObjectValue(
- attribute_name='projeto.sigla',
- left=label_left[3] * cm
+ attribute_name="projeto.sigla", left=label_left[3] * cm
),
ObjectValue(
- attribute_name='data_retorno_assinatura',
+ attribute_name="data_retorno_assinatura",
left=label_left[4] * cm,
- get_value=lambda instance:
- instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura is not None else '-'
+ get_value=lambda instance: instance.data_retorno_assinatura.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_retorno_assinatura is not None
+ else "-",
),
ObjectValue(
- attribute_name='data_pub_diario',
+ attribute_name="data_pub_diario",
left=label_left[5] * cm,
- get_value=lambda instance:
- instance.data_pub_diario.strftime('%d/%m/%Y') if instance.data_pub_diario is not None else '-'
+ get_value=lambda instance: instance.data_pub_diario.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_pub_diario is not None
+ else "-",
),
ObjectValue(
- attribute_name='casa_legislativa.nome',
- left=label_left[6] * cm
+ attribute_name="casa_legislativa.nome", left=label_left[6] * cm
),
]
- #groups = [
+ # groups = [
# ReportGroup(attribute_name='casa_legislativa.municipio.uf',
# band_header=ReportBand(
# height=0.7 * cm,
@@ -131,11 +138,10 @@ class ConvenioReport(ReportDefault):
# borders={'top': True},
# )
# )
- #]
+ # ]
class ConvenioReportSemAceite(ConvenioReport):
-
class band_page_header(ReportDefault.band_page_header):
label_top = ReportDefault.band_page_header.label_top
@@ -186,39 +192,38 @@ class ConvenioReportSemAceite(ConvenioReport):
elements = [
ObjectValue(
- attribute_name='casa_legislativa.municipio.uf.sigla',
- left=label_left[0] * cm
- ),
- ObjectValue(
- attribute_name='casa_legislativa.municipio.nome',
- left=label_left[1] * cm
+ attribute_name="casa_legislativa.municipio.uf.sigla",
+ left=label_left[0] * cm,
),
ObjectValue(
- attribute_name='num_convenio',
- left=label_left[2] * cm
+ attribute_name="casa_legislativa.municipio.nome",
+ left=label_left[1] * cm,
),
+ ObjectValue(attribute_name="num_convenio", left=label_left[2] * cm),
ObjectValue(
- attribute_name='projeto.sigla',
+ attribute_name="projeto.sigla",
left=label_left[3],
),
ObjectValue(
- attribute_name='data_retorno_assinatura',
+ attribute_name="data_retorno_assinatura",
left=label_left[4] * cm,
- get_value=lambda instance:
- instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura is not None else '-'
+ get_value=lambda instance: instance.data_retorno_assinatura.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_retorno_assinatura is not None
+ else "-",
),
ObjectValue(
- attribute_name='casa_legislativa.nome',
- left=label_left[5] * cm
+ attribute_name="casa_legislativa.nome", left=label_left[5] * cm
),
]
-float_duas_casas = lambda instance: '%.2f' % (instance)
+float_duas_casas = lambda instance: "%.2f" % (instance)
class ConvenioReportRegiao(ReportDefault):
- title = _('Relatório de Parcerias por Região')
+ title = _("Relatório de Parcerias por Região")
class band_page_header(ReportDefault.band_page_header):
label_top = ReportDefault.band_page_header.label_top
@@ -228,57 +233,103 @@ class ConvenioReportRegiao(ReportDefault):
elements = list(ReportDefault.band_page_header.elements)
elements += [
- Label(text=_("UF"), left=label_left[0] * cm, top=label_top,),
- Label(text=_("Total"), left=label_left[1] * cm, top=label_top,),
- Label(text=_("Aderidas"), left=label_left[2] * cm, top=label_top,),
+ Label(
+ text=_("UF"),
+ left=label_left[0] * cm,
+ top=label_top,
+ ),
+ Label(
+ text=_("Total"),
+ left=label_left[1] * cm,
+ top=label_top,
+ ),
+ Label(
+ text=_("Aderidas"),
+ left=label_left[2] * cm,
+ top=label_top,
+ ),
Label(text="%", left=label_left[3] * cm, top=label_top),
- Label(text=_("Ñ Aderidas"), left=label_left[4] * cm, top=label_top,),
+ Label(
+ text=_("Ñ Aderidas"),
+ left=label_left[4] * cm,
+ top=label_top,
+ ),
Label(text="%", left=label_left[5] * cm, top=label_top),
]
class band_detail(ReportDefault.band_detail):
label_left = [0.5, 6, 8, 10, 12, 14]
display_inline = True
- float_duas_casas = lambda instance: '%.2f' % (instance.porc_casas_aderidas)
- default_style = {'fontName': 'Helvetica', 'fontSize': 11}
+ float_duas_casas = lambda instance: "%.2f" % (
+ instance.porc_casas_aderidas
+ )
+ default_style = {"fontName": "Helvetica", "fontSize": 11}
elements = [
- ObjectValue(attribute_name='estado', left=label_left[0] * cm, ),
- ObjectValue(attribute_name='quant_casas', left=label_left[1] * cm,),
- ObjectValue(attribute_name='quant_casas_aderidas', left=label_left[2] * cm),
- ObjectValue(attribute_name='porc_casas_aderidas', left=label_left[3] * cm),
- ObjectValue(attribute_name='quant_casas_nao_aderidas', left=label_left[4] * cm),
- ObjectValue(attribute_name='porc_casas_nao_aderidas', left=label_left[5] * cm,),
+ ObjectValue(
+ attribute_name="estado",
+ left=label_left[0] * cm,
+ ),
+ ObjectValue(
+ attribute_name="quant_casas",
+ left=label_left[1] * cm,
+ ),
+ ObjectValue(
+ attribute_name="quant_casas_aderidas", left=label_left[2] * cm
+ ),
+ ObjectValue(
+ attribute_name="porc_casas_aderidas", left=label_left[3] * cm
+ ),
+ ObjectValue(
+ attribute_name="quant_casas_nao_aderidas",
+ left=label_left[4] * cm,
+ ),
+ ObjectValue(
+ attribute_name="porc_casas_nao_aderidas",
+ left=label_left[5] * cm,
+ ),
]
class band_summary(ReportBand):
label_left = [0.5, 6, 8, 10, 12, 14]
elements = [
Label(text=_("Total"), top=0.1 * cm, left=label_left[0] * cm),
- ObjectValue(attribute_name='quant_casas', action=FIELD_ACTION_SUM, left=label_left[1] * cm, ),
- ObjectValue(attribute_name='quant_casas_aderidas', action=FIELD_ACTION_SUM, left=label_left[2] * cm),
+ ObjectValue(
+ attribute_name="quant_casas",
+ action=FIELD_ACTION_SUM,
+ left=label_left[1] * cm,
+ ),
+ ObjectValue(
+ attribute_name="quant_casas_aderidas",
+ action=FIELD_ACTION_SUM,
+ left=label_left[2] * cm,
+ ),
# ObjectValue(attribute_name='porc_casas_aderidas', action=FIELD_ACTION_AVG, left=label_left[3]*cm,
# get_value= lambda instance : lambda instance: '%.2f' % (instance.porc_casas_aderidas),
# ),
- ObjectValue(attribute_name='quant_casas_nao_aderidas', action=FIELD_ACTION_SUM, left=label_left[4] * cm),
+ ObjectValue(
+ attribute_name="quant_casas_nao_aderidas",
+ action=FIELD_ACTION_SUM,
+ left=label_left[4] * cm,
+ ),
# ObjectValue(attribute_name='porc_casas_nao_aderidas', left=label_left[5]*cm,
# get_value=lambda x: teste(),
# ),
]
- borders = {'top': True}
+ borders = {"top": True}
class ConvenioPorCMReport(ConvenioReport):
- title = _('Relatório de Parcerias por Câmara Municipal')
+ title = _("Relatório de Parcerias por Câmara Municipal")
class ConvenioPorALReport(ConvenioReport):
- title = _('Relatório de Parcerias por Assembléia Legislativa')
+ title = _("Relatório de Parcerias por Assembléia Legislativa")
class ConvenioReportSemAceiteCM(ConvenioReportSemAceite):
- title = _('Relatório de Parcerias por Câmara Municipal')
+ title = _("Relatório de Parcerias por Câmara Municipal")
class ConvenioReportSemAceiteAL(ConvenioReportSemAceite):
- title = _('Relatório de Parcerias por Assembléia Legislativa')
+ title = _("Relatório de Parcerias por Assembléia Legislativa")
diff --git a/sigi/apps/convenios/urls.py b/sigi/apps/convenios/urls.py
index cfb8f55..8d7181c 100644
--- a/sigi/apps/convenios/urls.py
+++ b/sigi/apps/convenios/urls.py
@@ -2,8 +2,12 @@ from django.urls import path
from sigi.apps.convenios import views
urlpatterns = [
- path('reportsRegiao//', views.report_regiao, name='convenios-report_regiao_pdf'),
- path('importar/', views.importar_gescon, name='importar-gescon'),
+ path(
+ "reportsRegiao//",
+ views.report_regiao,
+ name="convenios-report_regiao_pdf",
+ ),
+ path("importar/", views.importar_gescon, name="importar-gescon"),
]
# urlpatterns = patterns(
diff --git a/sigi/apps/convenios/views.py b/sigi/apps/convenios/views.py
index 817e43c..af5a87e 100644
--- a/sigi/apps/convenios/views.py
+++ b/sigi/apps/convenios/views.py
@@ -1,9 +1,11 @@
import csv
import datetime
+
# from django.contrib import messages
from django.contrib import admin
from django.http.response import HttpResponseForbidden
+
# from django.conf import settings
# from django.core.paginator import Paginator, InvalidPage, EmptyPage
# from django.http import HttpResponse, HttpResponseRedirect
@@ -15,6 +17,7 @@ from django_weasyprint.views import WeasyTemplateResponse
from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.convenios.models import Convenio, Gescon, Projeto
+
# from sigi.apps.convenios.reports import (ConvenioReport,
# ConvenioReportSemAceite,
# ConvenioPorCMReport,
@@ -22,14 +25,15 @@ from sigi.apps.convenios.models import Convenio, Gescon, Projeto
# ConvenioReportSemAceiteAL,
# ConvenioReportSemAceiteCM)
+
@login_required
def report_regiao(request, regiao):
REGIAO_CHOICES = dict(UnidadeFederativa.REGIAO_CHOICES)
projetos = Projeto.objects.all()
- camaras = Orgao.objects.filter(tipo__sigla='CM')
+ camaras = Orgao.objects.filter(tipo__sigla="CM")
tabelas = list()
- convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM')
+ convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla="CM")
tabela = casas_estado_to_tabela(camaras, convenios, regiao)
tabela["projeto"] = _("Geral")
@@ -42,22 +46,23 @@ def report_regiao(request, regiao):
tabelas.append(tabela)
context = {
- 'tabelas': tabelas,
- 'regiao': REGIAO_CHOICES[regiao],
+ "tabelas": tabelas,
+ "regiao": REGIAO_CHOICES[regiao],
}
return WeasyTemplateResponse(
- filename=f'relatorio_regiao_{ regiao }.pdf',
+ filename=f"relatorio_regiao_{ regiao }.pdf",
request=request,
- template='convenios/tabela_regiao.html',
+ template="convenios/tabela_regiao.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
+
def casas_estado_to_tabela(casas, convenios, regiao):
estados = get_list_or_404(UnidadeFederativa, regiao=regiao)
- class LinhaEstado():
+ class LinhaEstado:
pass
lista = []
@@ -107,21 +112,21 @@ def casas_estado_to_tabela(casas, convenios, regiao):
casas_regiao.count(),
casas_regiao.exclude(convenio__in=convenios_regiao).distinct().count(),
casas_regiao.filter(convenio__in=convenios_regiao).distinct().count(),
- casas_regiao.filter(
- convenio__in=convenios_regiao_publicados
- ).distinct().count(),
- casas_regiao.filter(
- convenio__in=convenios_regiao_equipados
- ).distinct().count(),
+ casas_regiao.filter(convenio__in=convenios_regiao_publicados)
+ .distinct()
+ .count(),
+ casas_regiao.filter(convenio__in=convenios_regiao_equipados)
+ .distinct()
+ .count(),
)
cabecalho_topo = (
- _('UF'),
- _('Câmaras municipais'),
- _('Não Aderidas'),
- _('Aderidas'),
- _('Conveniadas'),
- _('Equipadas')
+ _("UF"),
+ _("Câmaras municipais"),
+ _("Não Aderidas"),
+ _("Aderidas"),
+ _("Conveniadas"),
+ _("Equipadas"),
)
return {
@@ -130,6 +135,7 @@ def casas_estado_to_tabela(casas, convenios, regiao):
"sumario": sumario,
}
+
@login_required
def importar_gescon(request):
if not request.user.is_superuser:
@@ -137,18 +143,17 @@ def importar_gescon(request):
context = admin.site.each_context(request)
- action = request.GET.get('action', "")
+ action = request.GET.get("action", "")
gescon = Gescon.load()
- if action == 'importar':
+ if action == "importar":
gescon.importa_contratos()
- context['gescon'] = gescon
+ context["gescon"] = gescon
return render(request, "convenios/importar_gescon.html", context)
-
"""
def query_ordena(qs, o, ot):
list_display = ('num_convenio', 'casa_legislativa',
@@ -163,18 +168,23 @@ def query_ordena(qs, o, ot):
qs = qs.order_by("-" + aux)
return qs
"""
+
+
def normaliza_data(get, nome_param):
import re
+
if nome_param in get:
- value = get.get(nome_param, '')
- if value == '':
+ value = get.get(nome_param, "")
+ if value == "":
del get[nome_param]
- elif re.match('^\d*$', value): # Year only
+ elif re.match("^\d*$", value): # Year only
# Complete with january 1st
get[nome_param] = "%s-01-01" % value
- elif re.match('^\d*\D\d*$', value): # Year and month
+ elif re.match("^\d*\D\d*$", value): # Year and month
# Complete with 1st day of month
- get[nome_param] = '%s-01' % value
+ get[nome_param] = "%s-01" % value
+
+
"""
def get_for_qs(get, qs):
kwargs = {}
@@ -398,4 +408,4 @@ def export_csv(request):
return response
-"""
\ No newline at end of file
+"""
diff --git a/sigi/apps/diagnosticos/admin.py b/sigi/apps/diagnosticos/admin.py
index adfca8f..a85cc12 100644
--- a/sigi/apps/diagnosticos/admin.py
+++ b/sigi/apps/diagnosticos/admin.py
@@ -6,7 +6,14 @@ from django.utils.translation import gettext as _
from eav.admin import BaseEntityAdmin, BaseSchemaAdmin
from sigi.apps.diagnosticos.forms import DiagnosticoForm
-from sigi.apps.diagnosticos.models import Diagnostico, Pergunta, Escolha, Equipe, Anexo, Categoria
+from sigi.apps.diagnosticos.models import (
+ Diagnostico,
+ Pergunta,
+ Escolha,
+ Equipe,
+ Anexo,
+ Categoria,
+)
from sigi.apps.utils.base_admin import BaseModelAdmin
@@ -22,14 +29,22 @@ def publicar_diagnostico(self, request, queryset):
if email:
diagnostico.email_diagnostico_publicado(email, request.get_host())
self.message_user(request, _("Diagnóstico(s) publicado(s) com sucesso!"))
-publicar_diagnostico.short_description = _("""
- Definir diagnósticos como publicado""")
+
+
+publicar_diagnostico.short_description = _(
+ """
+ Definir diagnósticos como publicado"""
+)
def despublicar_diagnostico(self, request, queryset):
queryset.update(publicado=False)
-despublicar_diagnostico.short_description = _("""
- Definir diagnósticos como não publicado""")
+
+
+despublicar_diagnostico.short_description = _(
+ """
+ Definir diagnósticos como não publicado"""
+)
class EquipeInline(admin.TabularInline):
@@ -39,32 +54,69 @@ class EquipeInline(admin.TabularInline):
class AnexosInline(admin.TabularInline):
model = Anexo
extra = 2
- exclude = ['data_pub', ]
+ exclude = [
+ "data_pub",
+ ]
class AnexoAdmin(BaseModelAdmin):
- date_hierarchy = 'data_pub'
- exclude = ['data_pub', ]
- list_display = ('arquivo', 'descricao', 'data_pub', 'diagnostico')
- raw_id_fields = ('diagnostico',)
- search_fields = ('descricao', 'diagnostico__id', 'arquivo',
- 'diagnostico__casa_legislativa__nome')
+ date_hierarchy = "data_pub"
+ exclude = [
+ "data_pub",
+ ]
+ list_display = ("arquivo", "descricao", "data_pub", "diagnostico")
+ raw_id_fields = ("diagnostico",)
+ search_fields = (
+ "descricao",
+ "diagnostico__id",
+ "arquivo",
+ "diagnostico__casa_legislativa__nome",
+ )
class DiagnosticoAdmin(BaseEntityAdmin):
form = DiagnosticoForm
actions = [publicar_diagnostico, despublicar_diagnostico]
inlines = (EquipeInline, AnexosInline)
- search_fields = ('casa_legislativa__nome',)
- list_display = ('casa_legislativa', 'get_uf', 'data_visita_inicio', 'data_visita_fim', 'responsavel', 'publicado')
- list_filter = ('publicado', 'casa_legislativa__municipio__uf__nome', 'casa_legislativa', 'data_publicacao', 'data_visita_inicio', 'data_visita_fim')
- raw_id_fields = ('casa_legislativa',)
- ordering = ('casa_legislativa',)
+ search_fields = ("casa_legislativa__nome",)
+ list_display = (
+ "casa_legislativa",
+ "get_uf",
+ "data_visita_inicio",
+ "data_visita_fim",
+ "responsavel",
+ "publicado",
+ )
+ list_filter = (
+ "publicado",
+ "casa_legislativa__municipio__uf__nome",
+ "casa_legislativa",
+ "data_publicacao",
+ "data_visita_inicio",
+ "data_visita_fim",
+ )
+ raw_id_fields = ("casa_legislativa",)
+ ordering = ("casa_legislativa",)
eav_fieldsets = (
- ('00. Identificação do Diagnóstico', {'fields': ('responsavel', 'data_visita_inicio', 'data_visita_fim',)}),
- ('01. Identificação da Casa Legislativa', {'fields': ('casa_legislativa',)}),
- ('02. Identificação de Competências da Casa Legislativa', {'fields': ()})
+ (
+ "00. Identificação do Diagnóstico",
+ {
+ "fields": (
+ "responsavel",
+ "data_visita_inicio",
+ "data_visita_fim",
+ )
+ },
+ ),
+ (
+ "01. Identificação da Casa Legislativa",
+ {"fields": ("casa_legislativa",)},
+ ),
+ (
+ "02. Identificação de Competências da Casa Legislativa",
+ {"fields": ()},
+ ),
)
# popula o eav fieldsets ordenando as categorias e as perguntas
@@ -72,72 +124,94 @@ class DiagnosticoAdmin(BaseEntityAdmin):
try:
for categoria in Categoria.objects.all():
# ordena as perguntas pelo title e utiliza o name no fieldset
- perguntas_by_title = [(p.title, p.name) for p in categoria.perguntas.all()]
+ perguntas_by_title = [
+ (p.title, p.name) for p in categoria.perguntas.all()
+ ]
perguntas = [pergunta[1] for pergunta in sorted(perguntas_by_title)]
- eav_fieldsets += ((categoria, {
- 'fields': tuple(perguntas),
- 'classes': ['collapse']
- }),)
+ eav_fieldsets += (
+ (
+ categoria,
+ {"fields": tuple(perguntas), "classes": ["collapse"]},
+ ),
+ )
except OperationalError:
pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database
except ProgrammingError:
pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database
def get_uf(self, obj):
- return '%s' % (obj.casa_legislativa.municipio.uf)
- get_uf.short_description = _('UF')
- get_uf.admin_order_field = 'casa_legislativa__municipio__uf__nome'
+ return "%s" % (obj.casa_legislativa.municipio.uf)
+
+ get_uf.short_description = _("UF")
+ get_uf.admin_order_field = "casa_legislativa__municipio__uf__nome"
def lookup_allowed(self, lookup, value):
- return super(DiagnosticoAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact']
+ return super(DiagnosticoAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in ["casa_legislativa__municipio__uf__codigo_ibge__exact"]
def changelist_view(self, request, extra_context=None):
import re
+
request.GET._mutable = True
- if 'data_visita_inicio__gte' in request.GET:
- value = request.GET.get('data_visita_inicio__gte', '')
- if value == '':
- del request.GET['data_visita_inicio__gte']
- elif re.match('^\d*$', value): # Year only
- request.GET['data_visita_inicio__gte'] = "%s-01-01" % value # Complete with january 1st
- elif re.match('^\d*\D\d*$', value): # Year and month
- request.GET['data_visita_inicio__gte'] = '%s-01' % value # Complete with 1st day of month
- if 'data_visita_inicio__lte' in request.GET:
- value = request.GET.get('data_visita_inicio__lte', '')
- if value == '':
- del request.GET['data_visita_inicio__lte']
- elif re.match('^\d*$', value): # Year only
- request.GET['data_visita_inicio__lte'] = "%s-01-01" % value # Complete with january 1st
- elif re.match('^\d*\D\d*$', value): # Year and month
- request.GET['data_visita_inicio__lte'] = '%s-01' % value # Complete with 1st day of month
+ if "data_visita_inicio__gte" in request.GET:
+ value = request.GET.get("data_visita_inicio__gte", "")
+ if value == "":
+ del request.GET["data_visita_inicio__gte"]
+ elif re.match("^\d*$", value): # Year only
+ request.GET["data_visita_inicio__gte"] = (
+ "%s-01-01" % value
+ ) # Complete with january 1st
+ elif re.match("^\d*\D\d*$", value): # Year and month
+ request.GET["data_visita_inicio__gte"] = (
+ "%s-01" % value
+ ) # Complete with 1st day of month
+ if "data_visita_inicio__lte" in request.GET:
+ value = request.GET.get("data_visita_inicio__lte", "")
+ if value == "":
+ del request.GET["data_visita_inicio__lte"]
+ elif re.match("^\d*$", value): # Year only
+ request.GET["data_visita_inicio__lte"] = (
+ "%s-01-01" % value
+ ) # Complete with january 1st
+ elif re.match("^\d*\D\d*$", value): # Year and month
+ request.GET["data_visita_inicio__lte"] = (
+ "%s-01" % value
+ ) # Complete with 1st day of month
request.GET._mutable = False
- return super(DiagnosticoAdmin, self).changelist_view(request, extra_context)
+ return super(DiagnosticoAdmin, self).changelist_view(
+ request, extra_context
+ )
class EscolhaAdmin(BaseModelAdmin):
- search_fields = ('title',)
- list_display = ('title', 'schema', 'schema_to_open')
- raw_id_fields = ('schema', 'schema_to_open')
- ordering = ('schema', 'title')
+ search_fields = ("title",)
+ list_display = ("title", "schema", "schema_to_open")
+ raw_id_fields = ("schema", "schema_to_open")
+ ordering = ("schema", "title")
class EscolhaInline(admin.TabularInline):
model = Escolha
- fk_name = 'schema'
- raw_id_fields = ('schema_to_open',)
- verbose_name = _('Escolhas (apenas para choices ou multiple choices)')
+ fk_name = "schema"
+ raw_id_fields = ("schema_to_open",)
+ verbose_name = _("Escolhas (apenas para choices ou multiple choices)")
extra = 0
-class PerguntaAdmin (BaseSchemaAdmin):
- search_fields = ('title', 'help_text', 'name',)
- list_display = ('title', 'categoria', 'datatype', 'help_text', 'required')
- list_filter = ('datatype', 'categoria', 'required')
+class PerguntaAdmin(BaseSchemaAdmin):
+ search_fields = (
+ "title",
+ "help_text",
+ "name",
+ )
+ list_display = ("title", "categoria", "datatype", "help_text", "required")
+ list_filter = ("datatype", "categoria", "required")
inlines = (EscolhaInline,)
+
admin.site.register(Diagnostico, DiagnosticoAdmin)
admin.site.register(Pergunta, PerguntaAdmin)
admin.site.register(Escolha, EscolhaAdmin)
diff --git a/sigi/apps/diagnosticos/decorators.py b/sigi/apps/diagnosticos/decorators.py
index 253f403..ea3b19b 100644
--- a/sigi/apps/diagnosticos/decorators.py
+++ b/sigi/apps/diagnosticos/decorators.py
@@ -7,12 +7,14 @@ from sigi.apps.diagnosticos.models import Diagnostico
def validate_diagnostico(func):
def decorator(request, id_diagnostico, *args, **kwargs):
- """ Retorna 404 caso o diagnostico esteja publicado
+ """Retorna 404 caso o diagnostico esteja publicado
ou o usuario nao seja um membro da equipe
"""
try:
- diagnostico = Diagnostico.objects.filter(publicado=False).get(pk=id_diagnostico)
- if (request.user.servidor in diagnostico.membros):
+ diagnostico = Diagnostico.objects.filter(publicado=False).get(
+ pk=id_diagnostico
+ )
+ if request.user.servidor in diagnostico.membros:
# continua o processamento normal da view
return func(request, id_diagnostico, *args, **kwargs)
except Diagnostico.DoesNotExist:
@@ -20,5 +22,6 @@ def validate_diagnostico(func):
# renderiza a pagina de 404
context = RequestContext(request, {})
- return render_to_response('mobile/404.html', context)
+ return render_to_response("mobile/404.html", context)
+
return decorator
diff --git a/sigi/apps/diagnosticos/forms.py b/sigi/apps/diagnosticos/forms.py
index 48ed782..7ee088b 100644
--- a/sigi/apps/diagnosticos/forms.py
+++ b/sigi/apps/diagnosticos/forms.py
@@ -3,9 +3,15 @@ from copy import deepcopy
from django import forms
from django.contrib.contenttypes.generic import generic_inlineformset_factory
-from django.forms import (BooleanField, CharField, DateField,
- FloatField, ModelChoiceField, Textarea,
- ModelMultipleChoiceField)
+from django.forms import (
+ BooleanField,
+ CharField,
+ DateField,
+ FloatField,
+ ModelChoiceField,
+ Textarea,
+ ModelMultipleChoiceField,
+)
from django.forms.forms import BoundField
from django.utils.translation import gettext as _
from eav.fields import RangeField
@@ -14,7 +20,10 @@ from eav.forms import BaseDynamicEntityForm
from sigi.apps.casas.models import Orgao, Funcionario
from sigi.apps.contatos.models import Telefone
from sigi.apps.diagnosticos.models import Diagnostico
-from sigi.apps.diagnosticos.widgets import EavCheckboxSelectMultiple, EavRadioSelect
+from sigi.apps.diagnosticos.widgets import (
+ EavCheckboxSelectMultiple,
+ EavRadioSelect,
+)
class DiagnosticoForm(BaseDynamicEntityForm):
@@ -22,6 +31,7 @@ class DiagnosticoForm(BaseDynamicEntityForm):
"""Classe responsável por contruir o formulário,
vinculando ao modelo Diagnostico
"""
+
model = Diagnostico
def __init__(self, *args, **kwargs):
@@ -29,7 +39,7 @@ class DiagnosticoForm(BaseDynamicEntityForm):
for k, f in self.fields.iteritems():
if isinstance(f, CharField):
- f.widget = forms.widgets.Textarea(attrs={'cols': '80'})
+ f.widget = forms.widgets.Textarea(attrs={"cols": "80"})
class DiagnosticoMobileForm(BaseDynamicEntityForm):
@@ -41,36 +51,40 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
"""
FIELD_CLASSES = {
- 'text': CharField,
- 'float': FloatField,
- 'date': DateField,
- 'bool': BooleanField,
- 'one': ModelChoiceField,
- 'many': ModelMultipleChoiceField,
- 'range': RangeField,
+ "text": CharField,
+ "float": FloatField,
+ "date": DateField,
+ "bool": BooleanField,
+ "one": ModelChoiceField,
+ "many": ModelMultipleChoiceField,
+ "range": RangeField,
}
FIELD_EXTRA = {
- 'one': {'widget': EavRadioSelect},
- 'many': {'widget': EavCheckboxSelectMultiple},
+ "one": {"widget": EavRadioSelect},
+ "many": {"widget": EavCheckboxSelectMultiple},
}
FIELD_WIDGET = {
- 'consideracoes_gerais': {'widget': Textarea},
- 'descreva_5_cursos_prioritarios_para_treinamento_de_parlamentares_da_camara_municipal': {'widget': Textarea},
- 'descreva_5_cursos_prioritarios_para_treinamento_de_servidores_da_camara_municipal': {'widget': Textarea},
- 'sugestoes_para_a_area_de_capacitacao': {'widget': Textarea},
- 'sugestoes_para_a_area_de_comunicacao': {'widget': Textarea},
- 'sugestoes_para_a_area_de_informacao': {'widget': Textarea},
- 'sugestoes_para_a_area_de_ti': {'widget': Textarea},
- 'inscricoes_para_lista_gitec': {'widget': Textarea},
- 'inscricoes_para_lista_gial': {'widget': Textarea},
- 'inscricoes_para_lista_gicom': {'widget': Textarea},
+ "consideracoes_gerais": {"widget": Textarea},
+ "descreva_5_cursos_prioritarios_para_treinamento_de_parlamentares_da_camara_municipal": {
+ "widget": Textarea
+ },
+ "descreva_5_cursos_prioritarios_para_treinamento_de_servidores_da_camara_municipal": {
+ "widget": Textarea
+ },
+ "sugestoes_para_a_area_de_capacitacao": {"widget": Textarea},
+ "sugestoes_para_a_area_de_comunicacao": {"widget": Textarea},
+ "sugestoes_para_a_area_de_informacao": {"widget": Textarea},
+ "sugestoes_para_a_area_de_ti": {"widget": Textarea},
+ "inscricoes_para_lista_gitec": {"widget": Textarea},
+ "inscricoes_para_lista_gial": {"widget": Textarea},
+ "inscricoes_para_lista_gicom": {"widget": Textarea},
}
class Meta:
model = Diagnostico
- fields = '__all__'
+ fields = "__all__"
def __init__(self, data=None, category=None, *args, **kwargs):
super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs)
@@ -78,7 +92,9 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
def __iter__(self):
# ordena os campos do formulario usando o atributo label
- fields_by_label = [(field.label, name, field) for name, field in self.fields.items()]
+ fields_by_label = [
+ (field.label, name, field) for name, field in self.fields.items()
+ ]
for label, name, field in sorted(fields_by_label):
yield BoundField(self, field, name)
@@ -90,7 +106,10 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
"""
# Caso seja as duas primeiras categorias, utilize
# os campos do modelo
- if int(category) in (0, 1, ):
+ if int(category) in (
+ 0,
+ 1,
+ ):
self.fields = deepcopy(self.base_fields)
else:
self.fields = dict()
@@ -100,26 +119,34 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
for schema in self.instance.get_schemata(int(category)):
defaults = {
- 'label': schema.title,
- 'required': schema.required,
- 'help_text': schema.help_text,
+ "label": schema.title,
+ "required": schema.required,
+ "help_text": schema.help_text,
}
datatype = schema.datatype
if datatype == schema.TYPE_MANY:
choices = getattr(self.instance, schema.name)
- defaults.update({'queryset': schema.get_choices(),
- 'initial': [x.pk for x in choices]})
+ defaults.update(
+ {
+ "queryset": schema.get_choices(),
+ "initial": [x.pk for x in choices],
+ }
+ )
elif datatype == schema.TYPE_ONE:
choice = getattr(self.instance, schema.name)
- defaults.update({'queryset': schema.get_choices(),
- 'initial': choice.pk if choice else None,
- # if schema is required remove --------- from ui
- 'empty_label': None if schema.required else "---------"})
+ defaults.update(
+ {
+ "queryset": schema.get_choices(),
+ "initial": choice.pk if choice else None,
+ # if schema is required remove --------- from ui
+ "empty_label": None if schema.required else "---------",
+ }
+ )
extra = self.FIELD_EXTRA.get(datatype, {})
extra.update(self.FIELD_WIDGET.get(schema.name, {}))
- if hasattr(extra, '__call__'):
+ if hasattr(extra, "__call__"):
extra = extra(schema)
defaults.update(extra)
@@ -128,28 +155,43 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
# fill initial data (if attribute was already defined)
value = getattr(self.instance, schema.name)
- if value and not datatype in (schema.TYPE_ONE, schema.TYPE_MANY): # choices are already done above
+ if value and not datatype in (
+ schema.TYPE_ONE,
+ schema.TYPE_MANY,
+ ): # choices are already done above
self.initial[schema.name] = value
class OrgaoMobileForm(forms.ModelForm):
- data_instalacao = forms.DateField(label=_('Data de instalação da Casa Legislativa'), required=False)
+ data_instalacao = forms.DateField(
+ label=_("Data de instalação da Casa Legislativa"), required=False
+ )
data_criacao = forms.DateField()
class Meta:
model = Orgao
- fields = ('cnpj', 'data_criacao', 'data_instalacao', 'logradouro', 'bairro', 'cep', 'email', 'pagina_web')
+ fields = (
+ "cnpj",
+ "data_criacao",
+ "data_instalacao",
+ "logradouro",
+ "bairro",
+ "cep",
+ "email",
+ "pagina_web",
+ )
def __init__(self, *args, **kwargs):
super(OrgaoMobileForm, self).__init__(*args, **kwargs)
- self.fields['data_criacao'] = forms.DateField(
- label=_('Data de criação do Município'),
+ self.fields["data_criacao"] = forms.DateField(
+ label=_("Data de criação do Município"),
initial=self.instance.municipio.data_criacao,
- required=False)
+ required=False,
+ )
def save(self, commit=True):
super(OrgaoMobileForm, self).save(commit=True)
- self.instance.municipio.data_criacao = self.cleaned_data['data_criacao']
+ self.instance.municipio.data_criacao = self.cleaned_data["data_criacao"]
if commit:
self.instance.municipio.save()
return self.instance
@@ -160,18 +202,27 @@ class TelefoneMobileForm(forms.ModelForm):
class Meta:
model = Telefone
- fields = ('numero', 'tipo')
+ fields = ("numero", "tipo")
class FuncionariosMobileForm(forms.ModelForm):
- TelefoneFormSet = generic_inlineformset_factory(Telefone, TelefoneMobileForm, extra=1, can_delete=False)
+ TelefoneFormSet = generic_inlineformset_factory(
+ Telefone, TelefoneMobileForm, extra=1, can_delete=False
+ )
def __init__(self, data=None, prefix=None, instance=None, *args, **kwargs):
- super(FuncionariosMobileForm, self).__init__(data, prefix=prefix, instance=instance, *args, **kwargs)
- self.telefones = self.TelefoneFormSet(data, prefix=prefix, instance=instance)
+ super(FuncionariosMobileForm, self).__init__(
+ data, prefix=prefix, instance=instance, *args, **kwargs
+ )
+ self.telefones = self.TelefoneFormSet(
+ data, prefix=prefix, instance=instance
+ )
def is_valid(self):
- return self.telefones.is_valid() and super(FuncionariosMobileForm, self).is_valid()
+ return (
+ self.telefones.is_valid()
+ and super(FuncionariosMobileForm, self).is_valid()
+ )
def save(self, commit=True):
self.telefones.save(commit)
@@ -179,4 +230,11 @@ class FuncionariosMobileForm(forms.ModelForm):
class Meta:
model = Funcionario
- fields = ('nome', 'email', 'cargo', 'funcao', 'tempo_de_servico', 'sexo')
+ fields = (
+ "nome",
+ "email",
+ "cargo",
+ "funcao",
+ "tempo_de_servico",
+ "sexo",
+ )
diff --git a/sigi/apps/diagnosticos/management/commands/ls_export.py b/sigi/apps/diagnosticos/management/commands/ls_export.py
index 672579e..2925612 100644
--- a/sigi/apps/diagnosticos/management/commands/ls_export.py
+++ b/sigi/apps/diagnosticos/management/commands/ls_export.py
@@ -7,13 +7,8 @@ from sigi.apps.casas.models import Funcionario
from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.diagnosticos.models import Categoria, Diagnostico, Resposta
-DATATYPES = {
- 'text': 'T',
- 'float': 'N',
- 'date': 'D',
- 'one': 'L',
- 'many': 'M'
-}
+DATATYPES = {"text": "T", "float": "N", "date": "D", "one": "L", "many": "M"}
+
class Command(BaseCommand):
help = """Exporta dados do diagnóstico para o formato Tab-Separated-Values
@@ -22,191 +17,684 @@ class Command(BaseCommand):
def handle(self, *args, **options):
def normalize(l):
- return [s.encode('utf-8') for s in l]
+ return [s.encode("utf-8") for s in l]
- nonum = lambda s: s[s.index(' ')+1:]
- avalue = lambda e: ('Y' if e.title == 'Sim' else 'N'
- if e.title == 'Não' else e.id)
+ nonum = lambda s: s[s.index(" ") + 1 :]
+ avalue = lambda e: (
+ "Y" if e.title == "Sim" else "N" if e.title == "Não" else e.id
+ )
- setores = [(i+1, s[0], s[1]) for i, s in enumerate(
- Funcionario.SETOR_CHOICES)]
+ setores = [
+ (i + 1, s[0], s[1]) for i, s in enumerate(Funcionario.SETOR_CHOICES)
+ ]
if len(args) < 2:
raise CommandError("Use: ls_export survey_id struct.txt data.csv")
survey_id = args[0]
- lsf = csv.writer(open(args[1], 'wb+'), delimiter="\t",
- quoting=csv.QUOTE_MINIMAL)
+ lsf = csv.writer(
+ open(args[1], "wb+"), delimiter="\t", quoting=csv.QUOTE_MINIMAL
+ )
- struct = ['id', 'token', 'submitdate', 'lastpage', 'startlanguage',
- 'seed']
+ struct = [
+ "id",
+ "token",
+ "submitdate",
+ "lastpage",
+ "startlanguage",
+ "seed",
+ ]
self.stdout.write("Exporting survey structure: ")
# Structure headers #
self.stdout.write("\tStructure headers...", ending=" ")
- lsf.writerow(['id', 'related_id', 'class', 'type/scale', 'name',
- 'relevance', 'text', 'help', 'language', 'validation',
- 'mandatory', 'other', 'default', 'same_default'])
- lsf.writerows([
- ['', '', 'S', '', 'sid', '', survey_id],
- ['', '', 'S', '', 'format', '', 'G'],
- ['', '', 'S', '', 'language', '', 'pt-BR'],
- ['', '', 'SL', '', 'surveyls_survey_id', '', survey_id, '',
- 'pt-BR'],
- ['', '', 'SL', '', 'surveyls_language', '', 'pt-BR', '', 'pt-BR'],
- ['', '', 'SL', '', 'surveyls_title', '',
- 'Diagnóstico PML'.encode('utf-8'), '', 'pt-BR']])
+ lsf.writerow(
+ [
+ "id",
+ "related_id",
+ "class",
+ "type/scale",
+ "name",
+ "relevance",
+ "text",
+ "help",
+ "language",
+ "validation",
+ "mandatory",
+ "other",
+ "default",
+ "same_default",
+ ]
+ )
+ lsf.writerows(
+ [
+ ["", "", "S", "", "sid", "", survey_id],
+ ["", "", "S", "", "format", "", "G"],
+ ["", "", "S", "", "language", "", "pt-BR"],
+ [
+ "",
+ "",
+ "SL",
+ "",
+ "surveyls_survey_id",
+ "",
+ survey_id,
+ "",
+ "pt-BR",
+ ],
+ [
+ "",
+ "",
+ "SL",
+ "",
+ "surveyls_language",
+ "",
+ "pt-BR",
+ "",
+ "pt-BR",
+ ],
+ [
+ "",
+ "",
+ "SL",
+ "",
+ "surveyls_title",
+ "",
+ "Diagnóstico PML".encode("utf-8"),
+ "",
+ "pt-BR",
+ ],
+ ]
+ )
self.stdout.write("Done!")
# Identificação da Casa Legislativa e sua equipe #
self.stdout.write("\tIdentificação da Casa...", ending=" ")
- lsf.writerow(normalize(['1000', '', 'G', '', 'Identificação da Casa',
- '', '', '', 'pt-BR']))
- lsf.writerow(normalize(['1001', '', 'Q', 'L', 'c001q001', '1',
- 'Região', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c001q001')
- lsf.writerows([normalize(['1001', '', 'A', '0', sigla, '', nome, '',
- 'pt-BR']) for sigla, nome in UnidadeFederativa.REGIAO_CHOICES])
- lsf.writerow(normalize(['1002', '', 'Q', '!', 'c001q002', '1',
- 'Estado (UF)', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c001q002')
- lsf.writerows([normalize(['1002', '', 'A', '0', u.sigla, '', u.nome, '',
- 'pt-BR']) for u in UnidadeFederativa.objects.all()])
- lsf.writerow(normalize(['1003', '', 'Q', 'S', 'c001q003', '1',
- 'Município', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c001q003')
- lsf.writerow(normalize(['1004', '', 'Q', 'D', 'c001q004', '1',
- 'Data de criação do município', '', 'pt-BR', '', 'Y', 'N', '',
- '0']))
- struct.append('c001q004')
- lsf.writerow(normalize(['1005', '', 'Q', 'S', 'c001q005', '1',
- 'Nome da Casa', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c001q005')
- lsf.writerow(normalize(['1006', '', 'Q', 'D', 'c001q006', '1',
- 'Data de instalação do legislativo', '', 'pt-BR', '', 'Y', 'N', '',
- '0']))
- struct.append('c001q006')
- lsf.writerow(normalize(['1007', '', 'Q', 'T', 'c001q007', '1',
- 'Endereço', '', 'pt-BR', '', 'N', 'N', '', '0']))
- struct.append('c001q007')
- lsf.writerow(normalize(['1008', '', 'Q', 'S', 'c001q008', '1',
- 'CNPJ', '', 'pt-BR', '', 'N', 'N', '', '0']))
- struct.append('c001q008')
- lsf.writerow(normalize(['1009', '', 'Q', 'S', 'c001q009', '1',
- 'E-mail principal', '', 'pt-BR', '', 'N', 'N', '', '0']))
- struct.append('c001q009')
- lsf.writerow(normalize(['1010', '', 'Q', 'S', 'c001q010', '1',
- 'Endereço Web', '', 'pt-BR', '', 'N', 'N', '', '0']))
- struct.append('c001q010')
- lsf.writerow(normalize(['1011', '', 'Q', ';', 'c001q011', '1',
- 'Pessoas de contato', '', 'pt-BR', '', 'N', 'N', '', '0']))
- lsf.writerow(normalize(['101198', '', 'SQ', '1', 'SQ00101', '', 'Nome',
- '', 'pt-BR', '', '', 'N', '', '0']))
- lsf.writerow(normalize(['101199', '', 'SQ', '1', 'SQ00102', '',
- 'E-mail', '', 'pt-BR', '', '', 'N', '', '0']))
+ lsf.writerow(
+ normalize(
+ [
+ "1000",
+ "",
+ "G",
+ "",
+ "Identificação da Casa",
+ "",
+ "",
+ "",
+ "pt-BR",
+ ]
+ )
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "1001",
+ "",
+ "Q",
+ "L",
+ "c001q001",
+ "1",
+ "Região",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q001")
+ lsf.writerows(
+ [
+ normalize(["1001", "", "A", "0", sigla, "", nome, "", "pt-BR"])
+ for sigla, nome in UnidadeFederativa.REGIAO_CHOICES
+ ]
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "1002",
+ "",
+ "Q",
+ "!",
+ "c001q002",
+ "1",
+ "Estado (UF)",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q002")
+ lsf.writerows(
+ [
+ normalize(
+ ["1002", "", "A", "0", u.sigla, "", u.nome, "", "pt-BR"]
+ )
+ for u in UnidadeFederativa.objects.all()
+ ]
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "1003",
+ "",
+ "Q",
+ "S",
+ "c001q003",
+ "1",
+ "Município",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q003")
+ lsf.writerow(
+ normalize(
+ [
+ "1004",
+ "",
+ "Q",
+ "D",
+ "c001q004",
+ "1",
+ "Data de criação do município",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q004")
+ lsf.writerow(
+ normalize(
+ [
+ "1005",
+ "",
+ "Q",
+ "S",
+ "c001q005",
+ "1",
+ "Nome da Casa",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q005")
+ lsf.writerow(
+ normalize(
+ [
+ "1006",
+ "",
+ "Q",
+ "D",
+ "c001q006",
+ "1",
+ "Data de instalação do legislativo",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q006")
+ lsf.writerow(
+ normalize(
+ [
+ "1007",
+ "",
+ "Q",
+ "T",
+ "c001q007",
+ "1",
+ "Endereço",
+ "",
+ "pt-BR",
+ "",
+ "N",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q007")
+ lsf.writerow(
+ normalize(
+ [
+ "1008",
+ "",
+ "Q",
+ "S",
+ "c001q008",
+ "1",
+ "CNPJ",
+ "",
+ "pt-BR",
+ "",
+ "N",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q008")
+ lsf.writerow(
+ normalize(
+ [
+ "1009",
+ "",
+ "Q",
+ "S",
+ "c001q009",
+ "1",
+ "E-mail principal",
+ "",
+ "pt-BR",
+ "",
+ "N",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q009")
+ lsf.writerow(
+ normalize(
+ [
+ "1010",
+ "",
+ "Q",
+ "S",
+ "c001q010",
+ "1",
+ "Endereço Web",
+ "",
+ "pt-BR",
+ "",
+ "N",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c001q010")
+ lsf.writerow(
+ normalize(
+ [
+ "1011",
+ "",
+ "Q",
+ ";",
+ "c001q011",
+ "1",
+ "Pessoas de contato",
+ "",
+ "pt-BR",
+ "",
+ "N",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "101198",
+ "",
+ "SQ",
+ "1",
+ "SQ00101",
+ "",
+ "Nome",
+ "",
+ "pt-BR",
+ "",
+ "",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "101199",
+ "",
+ "SQ",
+ "1",
+ "SQ00102",
+ "",
+ "E-mail",
+ "",
+ "pt-BR",
+ "",
+ "",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
for i, k, v in setores:
- lsf.writerow(normalize(['10110{0}'.format(i), '', 'SQ', '',
- 'SQ1010{0}'.format(i), '1', v, '', 'pt-BR', '', '', 'N',
- '', '0']))
- struct.extend([
- 'c001q011_SQ1010{0}_SQ00101'.format(i),
- 'c001q011_SQ1010{0}_SQ00102'.format(i),
- ])
+ lsf.writerow(
+ normalize(
+ [
+ "10110{0}".format(i),
+ "",
+ "SQ",
+ "",
+ "SQ1010{0}".format(i),
+ "1",
+ v,
+ "",
+ "pt-BR",
+ "",
+ "",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.extend(
+ [
+ "c001q011_SQ1010{0}_SQ00101".format(i),
+ "c001q011_SQ1010{0}_SQ00102".format(i),
+ ]
+ )
self.stdout.write("Done!")
# Equipe de diagnóstico #
self.stdout.write("\tEquipe de diagnóstico...", ending=" ")
- lsf.writerow(normalize(['2000', '', 'G', '', 'Equipe de diagnóstico',
- '', '', '', 'pt-BR']))
- lsf.writerow(normalize(['2001', '', 'Q', 'D', 'c002q001', '1',
- 'Data de início da visita', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c002q001')
- lsf.writerow(normalize(['2002', '', 'Q', 'D', 'c002q002', '1',
- 'Data de término da visita', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c002q002')
- lsf.writerow(normalize(['2003', '', 'Q', 'S', 'c002q003', '1',
- 'Líder da equipe', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c002q003')
- lsf.writerow(normalize(['2004', '', 'Q', 'T', 'c002q004', '1',
- 'Membros da equipe', '', 'pt-BR', '', 'Y', 'N', '', '0']))
- struct.append('c002q004')
+ lsf.writerow(
+ normalize(
+ [
+ "2000",
+ "",
+ "G",
+ "",
+ "Equipe de diagnóstico",
+ "",
+ "",
+ "",
+ "pt-BR",
+ ]
+ )
+ )
+ lsf.writerow(
+ normalize(
+ [
+ "2001",
+ "",
+ "Q",
+ "D",
+ "c002q001",
+ "1",
+ "Data de início da visita",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c002q001")
+ lsf.writerow(
+ normalize(
+ [
+ "2002",
+ "",
+ "Q",
+ "D",
+ "c002q002",
+ "1",
+ "Data de término da visita",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c002q002")
+ lsf.writerow(
+ normalize(
+ [
+ "2003",
+ "",
+ "Q",
+ "S",
+ "c002q003",
+ "1",
+ "Líder da equipe",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c002q003")
+ lsf.writerow(
+ normalize(
+ [
+ "2004",
+ "",
+ "Q",
+ "T",
+ "c002q004",
+ "1",
+ "Membros da equipe",
+ "",
+ "pt-BR",
+ "",
+ "Y",
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ struct.append("c002q004")
self.stdout.write("Done!")
for c in Categoria.objects.all():
- self.stdout.write("\t{0}...".format(nonum(c.nome).encode('utf-8')), ending=" ")
- lsf.writerow(normalize([str(c.id), '', 'G', '',
- nonum(c.nome), '', nonum(c.nome), '',
- 'pt-BR']))
+ self.stdout.write(
+ "\t{0}...".format(nonum(c.nome).encode("utf-8")), ending=" "
+ )
+ lsf.writerow(
+ normalize(
+ [
+ str(c.id),
+ "",
+ "G",
+ "",
+ nonum(c.nome),
+ "",
+ nonum(c.nome),
+ "",
+ "pt-BR",
+ ]
+ )
+ )
perguntas = sorted([(p.title, p) for p in c.perguntas.all()])
for t, p in perguntas:
lstype = DATATYPES[p.datatype]
# Hack para perguntas SIM/NÃO que foram cadastradas como Choice
- if lstype == 'L':
- if ("".join([e.title for e in p.choices.all()]) in
- ["SimNão", "NãoSim"]):
- lstype = 'Y'
+ if lstype == "L":
+ if "".join([e.title for e in p.choices.all()]) in [
+ "SimNão",
+ "NãoSim",
+ ]:
+ lstype = "Y"
########
relevance = "1"
if p.abre_por.exists():
- relevance = "(" + " or ".join(
- ['({sid}X{gid}X{qid}.NAOK == "{value}")'.format(
- sid=survey_id, gid=e.schema.categoria.id,
- qid=e.schema.id, value=avalue(e)) for e in
- p.abre_por.all()]) + ")"
+ relevance = (
+ "("
+ + " or ".join(
+ [
+ '({sid}X{gid}X{qid}.NAOK == "{value}")'.format(
+ sid=survey_id,
+ gid=e.schema.categoria.id,
+ qid=e.schema.id,
+ value=avalue(e),
+ )
+ for e in p.abre_por.all()
+ ]
+ )
+ + ")"
+ )
- lsf.writerow(normalize([str(p.id), '', 'Q', lstype,
- 'c{0:03}q{1:03}'.format(c.id, p.id), relevance,
- nonum(p.title), p.help_text, 'pt-BR', '', 'NY'[p.required],
- 'N', '', '0']))
- if lstype == 'L':
- lsf.writerows([normalize([str(p.id), '', 'A', '0',
- str(e.id), '', e.title, '', 'pt-BR'])
- for e in p.choices.all()])
- if lstype == 'M':
- lsf.writerows([normalize([str(p.id*1000+e.id), '', 'SQ',
- '', str(e.id), '1', e.title, '', 'pt-BR'])
- for e in p.choices.all()])
- struct.extend(['c{0:03}q{1:03}_{2}'.format(c.id, p.id,
- e.id) for e in p.choices.all()])
+ lsf.writerow(
+ normalize(
+ [
+ str(p.id),
+ "",
+ "Q",
+ lstype,
+ "c{0:03}q{1:03}".format(c.id, p.id),
+ relevance,
+ nonum(p.title),
+ p.help_text,
+ "pt-BR",
+ "",
+ "NY"[p.required],
+ "N",
+ "",
+ "0",
+ ]
+ )
+ )
+ if lstype == "L":
+ lsf.writerows(
+ [
+ normalize(
+ [
+ str(p.id),
+ "",
+ "A",
+ "0",
+ str(e.id),
+ "",
+ e.title,
+ "",
+ "pt-BR",
+ ]
+ )
+ for e in p.choices.all()
+ ]
+ )
+ if lstype == "M":
+ lsf.writerows(
+ [
+ normalize(
+ [
+ str(p.id * 1000 + e.id),
+ "",
+ "SQ",
+ "",
+ str(e.id),
+ "1",
+ e.title,
+ "",
+ "pt-BR",
+ ]
+ )
+ for e in p.choices.all()
+ ]
+ )
+ struct.extend(
+ [
+ "c{0:03}q{1:03}_{2}".format(c.id, p.id, e.id)
+ for e in p.choices.all()
+ ]
+ )
else:
- struct.extend(['c{0:03}q{1:03}'.format(c.id, p.id)])
+ struct.extend(["c{0:03}q{1:03}".format(c.id, p.id)])
self.stdout.write("Done!")
- if len(args) < 3: # No data export
+ if len(args) < 3: # No data export
return
self.stdout.write("Exporting survey data: ")
- dtf = csv.writer(open(args[2], 'wb+'), delimiter='\t',
- quoting=csv.QUOTE_MINIMAL)
+ dtf = csv.writer(
+ open(args[2], "wb+"), delimiter="\t", quoting=csv.QUOTE_MINIMAL
+ )
dtf.writerow(struct)
for d in Diagnostico.objects.all():
self.stdout.write("\t{0}".format(d.casa_legislativa.nome))
- form = OrderedDict.fromkeys(struct, '{question_not_shown}')
+ form = OrderedDict.fromkeys(struct, "{question_not_shown}")
- form['id'] = str(d.id)
+ form["id"] = str(d.id)
if d.data_publicacao:
- form['submitdate'] = d.data_publicacao.isoformat()
+ form["submitdate"] = d.data_publicacao.isoformat()
# form['lastpage'] = '8'
- form['startlanguage'] = 'pt-BR'
+ form["startlanguage"] = "pt-BR"
# form['seed'] = '123456'
# Identificação da Casa Legislativa e sua equipe #
- form['c001q001'] = d.casa_legislativa.municipio.uf.regiao
- form['c001q002'] = d.casa_legislativa.municipio.uf.sigla
- form['c001q003'] = d.casa_legislativa.municipio.nome
+ form["c001q001"] = d.casa_legislativa.municipio.uf.regiao
+ form["c001q002"] = d.casa_legislativa.municipio.uf.sigla
+ form["c001q003"] = d.casa_legislativa.municipio.nome
if d.casa_legislativa.municipio.data_criacao:
- form['c001q004'] = \
- d.casa_legislativa.municipio.data_criacao.isoformat()
- form['c001q005'] = d.casa_legislativa.nome
+ form[
+ "c001q004"
+ ] = d.casa_legislativa.municipio.data_criacao.isoformat()
+ form["c001q005"] = d.casa_legislativa.nome
if d.casa_legislativa.data_instalacao:
- form['c001q006'] = \
- d.casa_legislativa.data_instalacao.isoformat()
- form['c001q007'] = (
+ form[
+ "c001q006"
+ ] = d.casa_legislativa.data_instalacao.isoformat()
+ form["c001q007"] = (
"{logradouro}{{cr}}{{newline}}"
"{bairro}{{cr}}{{newline}}"
"{cep} - {municipio} - {uf}".format(
@@ -214,62 +702,64 @@ class Command(BaseCommand):
bairro=d.casa_legislativa.bairro,
cep=d.casa_legislativa.cep,
municipio=d.casa_legislativa.municipio.nome,
- uf=d.casa_legislativa.municipio.uf.sigla
- ))
- form['c001q008'] = d.casa_legislativa.cnpj
- form['c001q009'] = d.casa_legislativa.email
- form['c001q010'] = d.casa_legislativa.pagina_web
+ uf=d.casa_legislativa.municipio.uf.sigla,
+ )
+ )
+ form["c001q008"] = d.casa_legislativa.cnpj
+ form["c001q009"] = d.casa_legislativa.email
+ form["c001q010"] = d.casa_legislativa.pagina_web
for i, k, v in setores:
q = d.casa_legislativa.funcionario_set.filter(setor=k)
if q.exists():
f = q.first()
- knome = 'c001q011_SQ1010{0}_SQ00101'.format(i)
- kmail = 'c001q011_SQ1010{0}_SQ00102'.format(i)
+ knome = "c001q011_SQ1010{0}_SQ00101".format(i)
+ kmail = "c001q011_SQ1010{0}_SQ00102".format(i)
form[knome] = f.nome
form[kmail] = f.email
if d.data_visita_inicio:
- form['c002q001'] = d.data_visita_inicio.isoformat()
+ form["c002q001"] = d.data_visita_inicio.isoformat()
if d.data_visita_fim:
- form['c002q002'] = d.data_visita_fim.isoformat()
- form['c002q003'] = d.responsavel.nome_completo
- form['c002q004'] = "{cr}{newline}".join(
- [e.membro.nome_completo for e in d.equipe_set.all()])
+ form["c002q002"] = d.data_visita_fim.isoformat()
+ form["c002q003"] = d.responsavel.nome_completo
+ form["c002q004"] = "{cr}{newline}".join(
+ [e.membro.nome_completo for e in d.equipe_set.all()]
+ )
for r in Resposta.objects.filter(entity_id=d.id):
- if r.schema.datatype == 'many':
+ if r.schema.datatype == "many":
key = "c{cid:03}q{qid:03}_{sqid}".format(
cid=r.schema.categoria.id,
qid=r.schema.id,
- sqid=r.value.id
+ sqid=r.value.id,
)
- value = 'Y'
+ value = "Y"
else:
- key = "c{cid:03}q{qid:03}".format(cid=r.schema.categoria.id,
- qid=r.schema.id)
+ key = "c{cid:03}q{qid:03}".format(
+ cid=r.schema.categoria.id, qid=r.schema.id
+ )
value = r.value
- if r.schema.datatype == 'one':
+ if r.schema.datatype == "one":
if value is None:
- value = '{question_not_shown}'
- elif value.title == 'Sim':
- value = 'Y'
- elif value.title == 'Não':
- value = 'N'
+ value = "{question_not_shown}"
+ elif value.title == "Sim":
+ value = "Y"
+ elif value.title == "Não":
+ value = "N"
else:
value = r.value.id
- elif r.schema.datatype == 'text':
- value = value.\
- replace('\r\n', '{cr}{newline}').\
- replace('\r', '{cr}{newline}').\
- replace('\n', '{cr}{newline}').\
- replace('\t', ' ')
+ elif r.schema.datatype == "text":
+ value = (
+ value.replace("\r\n", "{cr}{newline}")
+ .replace("\r", "{cr}{newline}")
+ .replace("\n", "{cr}{newline}")
+ .replace("\t", " ")
+ )
if value is None:
- value = '{question_not_shown}'
- form[key] = '{0}'.format(value)
+ value = "{question_not_shown}"
+ form[key] = "{0}".format(value)
dtf.writerow(normalize(form.values()))
- self.stdout.write('Done!')
-
-
+ self.stdout.write("Done!")
diff --git a/sigi/apps/diagnosticos/migrations/0001_initial.py b/sigi/apps/diagnosticos/migrations/0001_initial.py
index 77b21eb..31bd2b5 100644
--- a/sigi/apps/diagnosticos/migrations/0001_initial.py
+++ b/sigi/apps/diagnosticos/migrations/0001_initial.py
@@ -10,139 +10,340 @@ import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('contenttypes', '0001_initial'),
- ('casas', '0001_initial'),
+ ("servidores", "0001_initial"),
+ ("contenttypes", "0001_initial"),
+ ("casas", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Anexo',
+ name="Anexo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('arquivo', models.FileField(max_length=500, upload_to=b'apps/diagnostico/anexo/arquivo')),
- ('descricao', models.CharField(max_length=b'70', verbose_name='descri\xe7\xe3o')),
- ('data_pub', models.DateTimeField(default=datetime.datetime.now, verbose_name='data da publica\xe7\xe3o do anexo')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "arquivo",
+ models.FileField(
+ max_length=500,
+ upload_to=b"apps/diagnostico/anexo/arquivo",
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length=b"70", verbose_name="descri\xe7\xe3o"
+ ),
+ ),
+ (
+ "data_pub",
+ models.DateTimeField(
+ default=datetime.datetime.now,
+ verbose_name="data da publica\xe7\xe3o do anexo",
+ ),
+ ),
],
options={
- 'ordering': ('-data_pub',),
+ "ordering": ("-data_pub",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Categoria',
+ name="Categoria",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=255)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=255)),
],
options={
- 'ordering': ('nome',),
+ "ordering": ("nome",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Diagnostico',
+ name="Diagnostico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('search_text', sigi.apps.utils.SearchField(field_names=[b'casa_legislativa'], editable=False)),
- ('data_visita_inicio', models.DateField(null=True, verbose_name='data inicial da visita', blank=True)),
- ('data_visita_fim', models.DateField(null=True, verbose_name='data final da visita', blank=True)),
- ('publicado', models.BooleanField(default=False)),
- ('data_publicacao', models.DateField(null=True, verbose_name='data de publica\xe7\xe3o do diagn\xf3stico', blank=True)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa')),
- ('responsavel', models.ForeignKey(verbose_name='respons\xe1vel', to='servidores.Servidor')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "search_text",
+ sigi.apps.utils.SearchField(
+ field_names=[b"casa_legislativa"], editable=False
+ ),
+ ),
+ (
+ "data_visita_inicio",
+ models.DateField(
+ null=True,
+ verbose_name="data inicial da visita",
+ blank=True,
+ ),
+ ),
+ (
+ "data_visita_fim",
+ models.DateField(
+ null=True,
+ verbose_name="data final da visita",
+ blank=True,
+ ),
+ ),
+ ("publicado", models.BooleanField(default=False)),
+ (
+ "data_publicacao",
+ models.DateField(
+ null=True,
+ verbose_name="data de publica\xe7\xe3o do diagn\xf3stico",
+ blank=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ ),
+ ),
+ (
+ "responsavel",
+ models.ForeignKey(
+ verbose_name="respons\xe1vel", to="servidores.Servidor"
+ ),
+ ),
],
options={
- 'verbose_name': 'diagn\xf3stico',
- 'verbose_name_plural': 'diagn\xf3sticos',
+ "verbose_name": "diagn\xf3stico",
+ "verbose_name_plural": "diagn\xf3sticos",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Equipe',
+ name="Equipe",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('diagnostico', models.ForeignKey(to='diagnosticos.Diagnostico')),
- ('membro', models.ForeignKey(to='servidores.Servidor')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "diagnostico",
+ models.ForeignKey(to="diagnosticos.Diagnostico"),
+ ),
+ ("membro", models.ForeignKey(to="servidores.Servidor")),
],
options={
- 'verbose_name': 'equipe',
- 'verbose_name_plural': 'equipe',
+ "verbose_name": "equipe",
+ "verbose_name_plural": "equipe",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Escolha',
+ name="Escolha",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('title', models.CharField(max_length=100)),
- ('ordem', models.PositiveIntegerField(null=True, blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("title", models.CharField(max_length=100)),
+ ("ordem", models.PositiveIntegerField(null=True, blank=True)),
],
options={
- 'ordering': ('schema', 'ordem'),
- 'verbose_name': 'escolha',
- 'verbose_name_plural': 'escolhas',
+ "ordering": ("schema", "ordem"),
+ "verbose_name": "escolha",
+ "verbose_name_plural": "escolhas",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Pergunta',
+ name="Pergunta",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('title', models.CharField(help_text='user-friendly attribute name', max_length=250, verbose_name='title')),
- ('name', autoslug.fields.AutoSlugField(max_length=250, verbose_name='name', blank=True)),
- ('help_text', models.CharField(help_text='short description for administrator', max_length=250, verbose_name='help text', blank=True)),
- ('datatype', models.CharField(max_length=5, verbose_name='data type', choices=[(b'text', 'text'), (b'float', 'number'), (b'date', 'date'), (b'bool', 'boolean'), (b'one', 'choice'), (b'many', 'multiple choices'), (b'range', 'numeric range')])),
- ('required', models.BooleanField(default=False, verbose_name='required')),
- ('searched', models.BooleanField(default=False, verbose_name='include in search')),
- ('filtered', models.BooleanField(default=False, verbose_name='include in filters')),
- ('sortable', models.BooleanField(default=False, verbose_name='allow sorting')),
- ('categoria', models.ForeignKey(related_name=b'perguntas', to='diagnosticos.Categoria')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "title",
+ models.CharField(
+ help_text="user-friendly attribute name",
+ max_length=250,
+ verbose_name="title",
+ ),
+ ),
+ (
+ "name",
+ autoslug.fields.AutoSlugField(
+ max_length=250, verbose_name="name", blank=True
+ ),
+ ),
+ (
+ "help_text",
+ models.CharField(
+ help_text="short description for administrator",
+ max_length=250,
+ verbose_name="help text",
+ blank=True,
+ ),
+ ),
+ (
+ "datatype",
+ models.CharField(
+ max_length=5,
+ verbose_name="data type",
+ choices=[
+ (b"text", "text"),
+ (b"float", "number"),
+ (b"date", "date"),
+ (b"bool", "boolean"),
+ (b"one", "choice"),
+ (b"many", "multiple choices"),
+ (b"range", "numeric range"),
+ ],
+ ),
+ ),
+ (
+ "required",
+ models.BooleanField(default=False, verbose_name="required"),
+ ),
+ (
+ "searched",
+ models.BooleanField(
+ default=False, verbose_name="include in search"
+ ),
+ ),
+ (
+ "filtered",
+ models.BooleanField(
+ default=False, verbose_name="include in filters"
+ ),
+ ),
+ (
+ "sortable",
+ models.BooleanField(
+ default=False, verbose_name="allow sorting"
+ ),
+ ),
+ (
+ "categoria",
+ models.ForeignKey(
+ related_name=b"perguntas", to="diagnosticos.Categoria"
+ ),
+ ),
],
options={
- 'ordering': ('title',),
- 'verbose_name': 'pergunta',
- 'verbose_name_plural': 'perguntas',
+ "ordering": ("title",),
+ "verbose_name": "pergunta",
+ "verbose_name_plural": "perguntas",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Resposta',
+ name="Resposta",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('entity_id', models.IntegerField()),
- ('value_text', models.TextField(null=True, blank=True)),
- ('value_float', models.FloatField(null=True, blank=True)),
- ('value_date', models.DateField(null=True, blank=True)),
- ('value_bool', models.NullBooleanField()),
- ('value_range_min', models.FloatField(null=True, blank=True)),
- ('value_range_max', models.FloatField(null=True, blank=True)),
- ('choice', models.ForeignKey(verbose_name='escolha', blank=True, to='diagnosticos.Escolha', null=True)),
- ('entity_type', models.ForeignKey(to='contenttypes.ContentType')),
- ('schema', models.ForeignKey(related_name=b'attrs', verbose_name='pergunta', to='diagnosticos.Pergunta')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("entity_id", models.IntegerField()),
+ ("value_text", models.TextField(null=True, blank=True)),
+ ("value_float", models.FloatField(null=True, blank=True)),
+ ("value_date", models.DateField(null=True, blank=True)),
+ ("value_bool", models.NullBooleanField()),
+ ("value_range_min", models.FloatField(null=True, blank=True)),
+ ("value_range_max", models.FloatField(null=True, blank=True)),
+ (
+ "choice",
+ models.ForeignKey(
+ verbose_name="escolha",
+ blank=True,
+ to="diagnosticos.Escolha",
+ null=True,
+ ),
+ ),
+ (
+ "entity_type",
+ models.ForeignKey(to="contenttypes.ContentType"),
+ ),
+ (
+ "schema",
+ models.ForeignKey(
+ related_name=b"attrs",
+ verbose_name="pergunta",
+ to="diagnosticos.Pergunta",
+ ),
+ ),
],
options={
- 'verbose_name': 'resposta',
- 'verbose_name_plural': 'respostas',
+ "verbose_name": "resposta",
+ "verbose_name_plural": "respostas",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='escolha',
- name='schema',
- field=models.ForeignKey(related_name=b'choices', verbose_name='pergunta', to='diagnosticos.Pergunta'),
+ model_name="escolha",
+ name="schema",
+ field=models.ForeignKey(
+ related_name=b"choices",
+ verbose_name="pergunta",
+ to="diagnosticos.Pergunta",
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='escolha',
- name='schema_to_open',
- field=models.ForeignKey(related_name=b'', verbose_name='pergunta para abrir', blank=True, to='diagnosticos.Pergunta', null=True),
+ model_name="escolha",
+ name="schema_to_open",
+ field=models.ForeignKey(
+ related_name=b"",
+ verbose_name="pergunta para abrir",
+ blank=True,
+ to="diagnosticos.Pergunta",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='anexo',
- name='diagnostico',
- field=models.ForeignKey(verbose_name='diagn\xf3stico', to='diagnosticos.Diagnostico'),
+ model_name="anexo",
+ name="diagnostico",
+ field=models.ForeignKey(
+ verbose_name="diagn\xf3stico", to="diagnosticos.Diagnostico"
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py b/sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py
index 68be0de..8587818 100644
--- a/sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py
+++ b/sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py
@@ -9,14 +9,21 @@ import eav.models
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0001_initial'),
+ ("diagnosticos", "0001_initial"),
]
operations = [
migrations.AlterField(
- model_name='pergunta',
- name='name',
- field=autoslug.fields.AutoSlugField(populate_from=b'title', editable=True, max_length=250, blank=True, verbose_name='name', slugify=eav.models.slugify_attr_name),
+ model_name="pergunta",
+ name="name",
+ field=autoslug.fields.AutoSlugField(
+ populate_from=b"title",
+ editable=True,
+ max_length=250,
+ blank=True,
+ verbose_name="name",
+ slugify=eav.models.slugify_attr_name,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py b/sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py
index 68be0de..8587818 100644
--- a/sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py
+++ b/sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py
@@ -9,14 +9,21 @@ import eav.models
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0001_initial'),
+ ("diagnosticos", "0001_initial"),
]
operations = [
migrations.AlterField(
- model_name='pergunta',
- name='name',
- field=autoslug.fields.AutoSlugField(populate_from=b'title', editable=True, max_length=250, blank=True, verbose_name='name', slugify=eav.models.slugify_attr_name),
+ model_name="pergunta",
+ name="name",
+ field=autoslug.fields.AutoSlugField(
+ populate_from=b"title",
+ editable=True,
+ max_length=250,
+ blank=True,
+ verbose_name="name",
+ slugify=eav.models.slugify_attr_name,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py b/sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py
index a5af789..fcd3324 100644
--- a/sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py
+++ b/sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py
@@ -7,14 +7,20 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0002_auto_20170407_1024'),
+ ("diagnosticos", "0002_auto_20170407_1024"),
]
operations = [
migrations.AlterField(
- model_name='escolha',
- name='schema_to_open',
- field=models.ForeignKey(related_name='abre_por', verbose_name='pergunta para abrir', blank=True, to='diagnosticos.Pergunta', null=True),
+ model_name="escolha",
+ name="schema_to_open",
+ field=models.ForeignKey(
+ related_name="abre_por",
+ verbose_name="pergunta para abrir",
+ blank=True,
+ to="diagnosticos.Pergunta",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py b/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py
index 78a6bd0..a64f16f 100644
--- a/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py
+++ b/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py
@@ -7,15 +7,17 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0003_auto_20201101_2240'),
- ('casas', '0014_auto_20210406_1945'),
+ ("diagnosticos", "0003_auto_20201101_2240"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='diagnostico',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
+ model_name="diagnostico",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa", to="casas.Orgao"
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py b/sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py
index ec1a081..b295a3b 100644
--- a/sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py
+++ b/sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py
@@ -8,44 +8,73 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0004_auto_20210406_1945'),
+ ("diagnosticos", "0004_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='diagnostico',
- name='casa_legislativa',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa Legislativa', to='casas.Orgao'),
+ model_name="diagnostico",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Casa Legislativa",
+ to="casas.Orgao",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='diagnostico',
- name='responsavel',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='respons\xe1vel', to='servidores.Servidor'),
+ model_name="diagnostico",
+ name="responsavel",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="respons\xe1vel",
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='equipe',
- name='membro',
- field=models.ForeignKey(to='servidores.Servidor', on_delete=django.db.models.deletion.PROTECT),
+ model_name="equipe",
+ name="membro",
+ field=models.ForeignKey(
+ to="servidores.Servidor",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='escolha',
- name='schema_to_open',
- field=models.ForeignKey(related_name='abre_por', on_delete=django.db.models.deletion.SET_NULL, verbose_name='pergunta para abrir', blank=True, to='diagnosticos.Pergunta', null=True),
+ model_name="escolha",
+ name="schema_to_open",
+ field=models.ForeignKey(
+ related_name="abre_por",
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="pergunta para abrir",
+ blank=True,
+ to="diagnosticos.Pergunta",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='resposta',
- name='choice',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='escolha', blank=True, to='diagnosticos.Escolha', null=True),
+ model_name="resposta",
+ name="choice",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="escolha",
+ blank=True,
+ to="diagnosticos.Escolha",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='resposta',
- name='schema',
- field=models.ForeignKey(related_name='attrs', on_delete=django.db.models.deletion.PROTECT, verbose_name='pergunta', to='diagnosticos.Pergunta'),
+ model_name="resposta",
+ name="schema",
+ field=models.ForeignKey(
+ related_name="attrs",
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="pergunta",
+ to="diagnosticos.Pergunta",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/diagnosticos/migrations/0006_merge.py b/sigi/apps/diagnosticos/migrations/0006_merge.py
index ae7feba..bc36184 100644
--- a/sigi/apps/diagnosticos/migrations/0006_merge.py
+++ b/sigi/apps/diagnosticos/migrations/0006_merge.py
@@ -7,9 +7,8 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('diagnosticos', '0002_auto_20160719_0920'),
- ('diagnosticos', '0005_auto_20210416_0841'),
+ ("diagnosticos", "0002_auto_20160719_0920"),
+ ("diagnosticos", "0005_auto_20210416_0841"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/diagnosticos/models.py b/sigi/apps/diagnosticos/models.py
index cd8e135..475e15d 100644
--- a/sigi/apps/diagnosticos/models.py
+++ b/sigi/apps/diagnosticos/models.py
@@ -10,48 +10,49 @@ from sigi.apps.utils.email import enviar_email
class Diagnostico(BaseEntity):
- """ Modelo para representar unm diagnostico realizado
+ """Modelo para representar unm diagnostico realizado
em uma Casa Legislativa
"""
+
casa_legislativa = models.ForeignKey(
- 'casas.Orgao',
+ "casas.Orgao",
on_delete=models.PROTECT,
- verbose_name=_('Casa Legislativa')
+ verbose_name=_("Casa Legislativa"),
)
# campo de busca em caixa baixa e sem acento
- search_text = SearchField(field_names=['casa_legislativa'])
+ search_text = SearchField(field_names=["casa_legislativa"])
# casa_legislativa.casa_uf_filter = True
# casa_legislativa.casa_tipo_filter = True
data_visita_inicio = models.DateField(
- 'data inicial da visita',
+ "data inicial da visita",
null=True,
blank=True,
)
data_visita_fim = models.DateField(
- 'data final da visita',
+ "data final da visita",
null=True,
blank=True,
)
publicado = models.BooleanField(default=False)
data_publicacao = models.DateField(
- 'data de publicação do diagnóstico',
+ "data de publicação do diagnóstico",
null=True,
blank=True,
)
responsavel = models.ForeignKey(
- 'servidores.Servidor',
+ "servidores.Servidor",
on_delete=models.PROTECT,
- verbose_name=_('responsável')
+ verbose_name=_("responsável"),
)
class Meta:
- verbose_name, verbose_name_plural = _('diagnóstico'), _('diagnósticos')
+ verbose_name, verbose_name_plural = _("diagnóstico"), _("diagnósticos")
@property
def membros(self):
- """ Retorna a lista de membros do diagnostico,
+ """Retorna a lista de membros do diagnostico,
isto é responsavel + equipe
"""
membros = set([self.responsavel])
@@ -68,11 +69,13 @@ class Diagnostico(BaseEntity):
@property
def categorias_respondidas(self):
- """ Retorna uma listas das categorias dinamicas que tem
+ """Retorna uma listas das categorias dinamicas que tem
ao menos uma resposta
"""
# unifica as categorias das perguntas dessas respostas
- categoria_com_respostas = set([r.schema.categoria for r in self._get_respostas()])
+ categoria_com_respostas = set(
+ [r.schema.categoria for r in self._get_respostas()]
+ )
return list(categoria_com_respostas)
@@ -90,16 +93,19 @@ class Diagnostico(BaseEntity):
* host - O Host do sistema, para ser usado na
construção do endereço do diagnóstico
"""
- enviar_email(from_email, _("Diagnóstico publicado"),
- 'diagnosticos/email_diagnostico_publicado.txt',
- {
- 'responsavel': self.responsavel.nome_completo,
- 'casa_legislativa': self.casa_legislativa,
- 'data_diagnostico': self.data_visita_inicio,
- 'host': host,
- 'url_diagnostico': self.get_absolute_url(),
- 'status': _("Publicado"),
- })
+ enviar_email(
+ from_email,
+ _("Diagnóstico publicado"),
+ "diagnosticos/email_diagnostico_publicado.txt",
+ {
+ "responsavel": self.responsavel.nome_completo,
+ "casa_legislativa": self.casa_legislativa,
+ "data_diagnostico": self.data_visita_inicio,
+ "host": host,
+ "url_diagnostico": self.get_absolute_url(),
+ "status": _("Publicado"),
+ },
+ )
def email_diagnostico_alterado(self, from_email, host):
"""Enviando email quando o status do diagnóstico
@@ -108,20 +114,22 @@ class Diagnostico(BaseEntity):
* host - O Host do sistema, para ser usado na
construção do endereço do diagnóstico
"""
- enviar_email(from_email, _("Diagnóstico alterado"),
- 'diagnosticos/email_diagnostico_alterado.txt',
- {
- 'servidor': self.responsavel.nome_completo,
- 'casa_legislativa': self.casa_legislativa,
- 'data_diagnostico': self.data_visita_inicio,
- 'host': host,
- 'url_diagnostico': self.get_absolute_url(),
- 'status': _("Alterado"),
- })
+ enviar_email(
+ from_email,
+ _("Diagnóstico alterado"),
+ "diagnosticos/email_diagnostico_alterado.txt",
+ {
+ "servidor": self.responsavel.nome_completo,
+ "casa_legislativa": self.casa_legislativa,
+ "data_diagnostico": self.data_visita_inicio,
+ "host": host,
+ "url_diagnostico": self.get_absolute_url(),
+ "status": _("Alterado"),
+ },
+ )
def get_schemata(self, category=None, *args, **kwargs):
- """ Se existir uma categoria retorna apenas as questões dessa.
- """
+ """Se existir uma categoria retorna apenas as questões dessa."""
schemas = super(Diagnostico, self).get_schemata(*args, **kwargs)
if category:
schemas = [s for s in schemas if s.categoria_id == category]
@@ -134,21 +142,22 @@ class Diagnostico(BaseEntity):
return Pergunta.objects.all()
def __unicode__(self):
- return str(self.casa_legislativa).decode('utf8')
+ return str(self.casa_legislativa).decode("utf8")
def get_absolute_url(self):
- return "/diagnosticos/diagnostico/%i.pdf" % (self.id, )
+ return "/diagnosticos/diagnostico/%i.pdf" % (self.id,)
class Categoria(models.Model):
- """ Modelo para representar a categoria de uma pergunta
+ """Modelo para representar a categoria de uma pergunta
e sua ordem na hora de exibir no formulário
"""
+
nome = models.CharField(max_length=255)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
def __unicode__(self):
return self.nome
@@ -156,27 +165,30 @@ class Categoria(models.Model):
class Pergunta(BaseSchema):
- """ Modelo que representa uma pergunta no questionário
+ """Modelo que representa uma pergunta no questionário
e sua ordem dentro da categoria
Uma pergunta tem o nome e o tipo da resposta
"""
+
categoria = models.ForeignKey(
- Categoria,
- on_delete=models.CASCADE,
- related_name='perguntas'
+ Categoria, on_delete=models.CASCADE, related_name="perguntas"
)
def group_choices(self):
from django.db import connection, transaction
+
cursor = connection.cursor()
- cursor.execute("""
+ cursor.execute(
+ """
SELECT choice_id, sum(1)
FROM diagnosticos_resposta
WHERE schema_id=%s and choice_id is not null
GROUP BY choice_id;
- """, [self.id])
+ """,
+ [self.id],
+ )
return [
(Escolha.objects.get(id=int(row[0])), row[1])
@@ -185,82 +197,85 @@ class Pergunta(BaseSchema):
def total_anwsers(self):
from django.db import connection, transaction
+
cursor = connection.cursor()
- cursor.execute("""
+ cursor.execute(
+ """
SELECT sum(1)
FROM diagnosticos_resposta
WHERE schema_id=%s
- """, [self.id])
+ """,
+ [self.id],
+ )
return cursor.fetchone()
class Meta:
- ordering = ('title',)
- verbose_name, verbose_name_plural = _('pergunta'), _('perguntas')
+ ordering = ("title",)
+ verbose_name, verbose_name_plural = _("pergunta"), _("perguntas")
class Escolha(BaseChoice):
- """ Perguntas de multiplas escolhas tem as opções
+ """Perguntas de multiplas escolhas tem as opções
cadastradas neste modelo
"""
+
schema = models.ForeignKey(
Pergunta,
on_delete=models.CASCADE,
- related_name='choices',
- verbose_name=_('pergunta')
+ related_name="choices",
+ verbose_name=_("pergunta"),
)
schema_to_open = models.ForeignKey(
Pergunta,
on_delete=models.SET_NULL,
- related_name='abre_por',
- verbose_name=_('pergunta para abrir'),
+ related_name="abre_por",
+ verbose_name=_("pergunta para abrir"),
blank=True,
- null=True
+ null=True,
)
ordem = models.PositiveIntegerField(blank=True, null=True)
class Meta:
- ordering = ('schema', 'ordem')
- verbose_name, verbose_name_plural = _('escolha'), _('escolhas')
+ ordering = ("schema", "ordem")
+ verbose_name, verbose_name_plural = _("escolha"), _("escolhas")
class Resposta(BaseAttribute):
- """ Modelo para guardar as respostas das perguntas
+ """Modelo para guardar as respostas das perguntas
de um diagnosico
"""
+
schema = models.ForeignKey(
Pergunta,
on_delete=models.PROTECT,
- related_name='attrs',
- verbose_name=_('pergunta')
+ related_name="attrs",
+ verbose_name=_("pergunta"),
)
choice = models.ForeignKey(
Escolha,
on_delete=models.PROTECT,
- verbose_name=_('escolha'),
+ verbose_name=_("escolha"),
blank=True,
- null=True
+ null=True,
)
class Meta:
- verbose_name, verbose_name_plural = _('resposta'), _('respostas')
+ verbose_name, verbose_name_plural = _("resposta"), _("respostas")
class Equipe(models.Model):
- """ Modelo que representa a equipe de um diagnóstico
- """
+ """Modelo que representa a equipe de um diagnóstico"""
+
diagnostico = models.ForeignKey(Diagnostico, on_delete=models.CASCADE)
- membro = models.ForeignKey(
- 'servidores.Servidor',
- on_delete=models.PROTECT
- )
+ membro = models.ForeignKey("servidores.Servidor", on_delete=models.PROTECT)
class Meta:
- verbose_name, verbose_name_plural = _('equipe'), _('equipe')
+ verbose_name, verbose_name_plural = _("equipe"), _("equipe")
def __unicode__(self):
return self.membro.__unicode__()
@@ -268,21 +283,23 @@ class Equipe(models.Model):
class Anexo(models.Model):
- """ Modelo para representar os documentos levantados
+ """Modelo para representar os documentos levantados
no processo de diagnóstico. Podem ser fotos, contratos, etc.
"""
+
diagnostico = models.ForeignKey(
- Diagnostico,
- on_delete=models.CASCADE,
- verbose_name='diagnóstico'
+ Diagnostico, on_delete=models.CASCADE, verbose_name="diagnóstico"
+ )
+ arquivo = models.FileField(
+ upload_to="apps/diagnostico/anexo/arquivo", max_length=500
+ )
+ descricao = models.CharField(_("descrição"), max_length="70")
+ data_pub = models.DateTimeField(
+ _("data da publicação do anexo"), default=datetime.now
)
- arquivo = models.FileField(upload_to='apps/diagnostico/anexo/arquivo', max_length=500)
- descricao = models.CharField(_('descrição'), max_length='70')
- data_pub = models.DateTimeField(_('data da publicação do anexo'),
- default=datetime.now)
class Meta:
- ordering = ('-data_pub',)
+ ordering = ("-data_pub",)
def __unicode__(self):
return unicode(self.arquivo.name)
diff --git a/sigi/apps/diagnosticos/templatetags/smart_if.py b/sigi/apps/diagnosticos/templatetags/smart_if.py
index 5a09cd3..1895210 100644
--- a/sigi/apps/diagnosticos/templatetags/smart_if.py
+++ b/sigi/apps/diagnosticos/templatetags/smart_if.py
@@ -13,12 +13,12 @@ from django import template
register = template.Library()
-#==============================================================================
+# ==============================================================================
# Calculation objects
-#==============================================================================
+# ==============================================================================
-class BaseCalc(object):
+class BaseCalc(object):
def __init__(self, var1, var2=None, negate=False):
self.var1 = var1
self.var2 = var2
@@ -43,54 +43,48 @@ class BaseCalc(object):
class Or(BaseCalc):
-
def calculate(self, var1, var2):
return var1 or var2
class And(BaseCalc):
-
def calculate(self, var1, var2):
return var1 and var2
class Equals(BaseCalc):
-
def calculate(self, var1, var2):
return var1 == var2
class Greater(BaseCalc):
-
def calculate(self, var1, var2):
return var1 > var2
class GreaterOrEqual(BaseCalc):
-
def calculate(self, var1, var2):
return var1 >= var2
class In(BaseCalc):
-
def calculate(self, var1, var2):
return var1 in var2
OPERATORS = {
- '=': (Equals, True),
- '==': (Equals, True),
- '!=': (Equals, False),
- '>': (Greater, True),
- '>=': (GreaterOrEqual, True),
- '<=': (Greater, False),
- '<': (GreaterOrEqual, False),
- 'or': (Or, True),
- 'and': (And, True),
- 'in': (In, True),
+ "=": (Equals, True),
+ "==": (Equals, True),
+ "!=": (Equals, False),
+ ">": (Greater, True),
+ ">=": (GreaterOrEqual, True),
+ "<=": (Greater, False),
+ "<": (GreaterOrEqual, False),
+ "or": (Or, True),
+ "and": (And, True),
+ "in": (In, True),
}
-BOOL_OPERATORS = ('or', 'and')
+BOOL_OPERATORS = ("or", "and")
class IfParser(object):
@@ -111,7 +105,7 @@ class IfParser(object):
def parse(self):
if self.at_end():
- raise self.error_class('No variables provided.')
+ raise self.error_class("No variables provided.")
var1 = self.get_bool_var()
while not self.at_end():
op, negate = self.get_operator()
@@ -123,7 +117,7 @@ class IfParser(object):
negate = True
token = None
pos = self.pos
- while token is None or token == 'not':
+ while token is None or token == "not":
if pos >= self.len:
if eof_message is None:
raise self.error_class()
@@ -152,28 +146,32 @@ class IfParser(object):
var = self.get_var()
if not self.at_end():
op_token = self.get_token(lookahead=True)[0]
- if isinstance(op_token, basestring) and (op_token not in
- BOOL_OPERATORS):
+ if isinstance(op_token, basestring) and (
+ op_token not in BOOL_OPERATORS
+ ):
op, negate = self.get_operator()
return op(var, self.get_var(), negate=negate)
return var
def get_var(self):
- token, negate = self.get_token('Reached end of statement, still '
- 'expecting a variable.')
+ token, negate = self.get_token(
+ "Reached end of statement, still " "expecting a variable."
+ )
if isinstance(token, basestring) and token in OPERATORS:
- raise self.error_class('Expected variable, got operator (%s).' %
- token)
+ raise self.error_class(
+ "Expected variable, got operator (%s)." % token
+ )
var = self.create_var(token)
if negate:
return Or(var, negate=True)
return var
def get_operator(self):
- token, negate = self.get_token('Reached end of statement, still '
- 'expecting an operator.')
+ token, negate = self.get_token(
+ "Reached end of statement, still " "expecting an operator."
+ )
if not isinstance(token, basestring) or token not in OPERATORS:
- raise self.error_class('%s is not a valid operator.' % token)
+ raise self.error_class("%s is not a valid operator." % token)
if self.at_end():
raise self.error_class('No variable provided after "%s".' % token)
op, true = OPERATORS[token]
@@ -182,9 +180,10 @@ class IfParser(object):
return op, negate
-#==============================================================================
+# ==============================================================================
# Actual templatetag code.
-#==============================================================================
+# ==============================================================================
+
class TemplateIfParser(IfParser):
error_class = template.TemplateSyntaxError
@@ -198,7 +197,6 @@ class TemplateIfParser(IfParser):
class SmartIfNode(template.Node):
-
def __init__(self, var, nodelist_true, nodelist_false=None):
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.var = var
@@ -208,7 +206,7 @@ class SmartIfNode(template.Node):
return self.nodelist_true.render(context)
if self.nodelist_false:
return self.nodelist_false.render(context)
- return ''
+ return ""
def __repr__(self):
return ""
@@ -230,7 +228,7 @@ class SmartIfNode(template.Node):
return nodes
-@register.tag('if')
+@register.tag("if")
def smart_if(parser, token):
"""
A smarter {% if %} tag for django templates.
@@ -249,10 +247,10 @@ def smart_if(parser, token):
"""
bits = token.split_contents()[1:]
var = TemplateIfParser(parser, bits).parse()
- nodelist_true = parser.parse(('else', 'endif'))
+ nodelist_true = parser.parse(("else", "endif"))
token = parser.next_token()
- if token.contents == 'else':
- nodelist_false = parser.parse(('endif',))
+ if token.contents == "else":
+ nodelist_false = parser.parse(("endif",))
parser.delete_first_token()
else:
nodelist_false = None
diff --git a/sigi/apps/diagnosticos/templatetags/test_smart_if.py b/sigi/apps/diagnosticos/templatetags/test_smart_if.py
index 9101bf9..d1c2250 100644
--- a/sigi/apps/diagnosticos/templatetags/test_smart_if.py
+++ b/sigi/apps/diagnosticos/templatetags/test_smart_if.py
@@ -19,7 +19,6 @@ class TestVar(object):
class TestIfParser(IfParser):
-
def create_var(self, value):
return TestVar(value)
@@ -27,6 +26,7 @@ class TestIfParser(IfParser):
class ValueHolder(object):
pass
+
VALORES = ValueHolder()
VALORES.true = TestVar(True)
VALORES.false = TestVar(False)
@@ -100,67 +100,67 @@ def test_parse_bits():
var = TestIfParser([False]).parse()
assert not var.resolve({})
- var = TestIfParser([False, 'or', True]).parse()
+ var = TestIfParser([False, "or", True]).parse()
assert var.resolve({})
- var = TestIfParser([False, 'and', True]).parse()
+ var = TestIfParser([False, "and", True]).parse()
assert not var.resolve({})
- var = TestIfParser(['not', False, 'and', 'not', False]).parse()
+ var = TestIfParser(["not", False, "and", "not", False]).parse()
assert var.resolve({})
- var = TestIfParser(['not', 'not', True]).parse()
+ var = TestIfParser(["not", "not", True]).parse()
assert var.resolve({})
- var = TestIfParser([1, '=', 1]).parse()
+ var = TestIfParser([1, "=", 1]).parse()
assert var.resolve({})
- var = TestIfParser([1, 'not', '=', 1]).parse()
+ var = TestIfParser([1, "not", "=", 1]).parse()
assert not var.resolve({})
- var = TestIfParser([1, 'not', 'not', '=', 1]).parse()
+ var = TestIfParser([1, "not", "not", "=", 1]).parse()
assert var.resolve({})
- var = TestIfParser([1, '!=', 1]).parse()
+ var = TestIfParser([1, "!=", 1]).parse()
assert not var.resolve({})
- var = TestIfParser([3, '>', 2]).parse()
+ var = TestIfParser([3, ">", 2]).parse()
assert var.resolve({})
- var = TestIfParser([1, '<', 2]).parse()
+ var = TestIfParser([1, "<", 2]).parse()
assert var.resolve({})
- var = TestIfParser([2, 'not', 'in', [2, 3]]).parse()
+ var = TestIfParser([2, "not", "in", [2, 3]]).parse()
assert not var.resolve({})
- var = TestIfParser([1, 'or', 1, '=', 2]).parse()
+ var = TestIfParser([1, "or", 1, "=", 2]).parse()
assert var.resolve({})
def test_boolean():
- var = TestIfParser([True, 'and', True, 'and', True]).parse()
+ var = TestIfParser([True, "and", True, "and", True]).parse()
assert var.resolve({})
- var = TestIfParser([False, 'or', False, 'or', True]).parse()
+ var = TestIfParser([False, "or", False, "or", True]).parse()
assert var.resolve({})
- var = TestIfParser([True, 'and', False, 'or', True]).parse()
+ var = TestIfParser([True, "and", False, "or", True]).parse()
assert var.resolve({})
- var = TestIfParser([False, 'or', True, 'and', True]).parse()
+ var = TestIfParser([False, "or", True, "and", True]).parse()
assert var.resolve({})
- var = TestIfParser([True, 'and', True, 'and', False]).parse()
+ var = TestIfParser([True, "and", True, "and", False]).parse()
assert not var.resolve({})
- var = TestIfParser([False, 'or', False, 'or', False]).parse()
+ var = TestIfParser([False, "or", False, "or", False]).parse()
assert not var.resolve({})
- var = TestIfParser([False, 'or', True, 'and', False]).parse()
+ var = TestIfParser([False, "or", True, "and", False]).parse()
assert not var.resolve({})
- var = TestIfParser([False, 'and', True, 'or', False]).parse()
+ var = TestIfParser([False, "and", True, "or", False]).parse()
assert not var.resolve({})
def test_invalid():
- pytest.raises(ValueError, TestIfParser(['not']).parse)
- pytest.raises(ValueError, TestIfParser(['==']).parse)
- pytest.raises(ValueError, TestIfParser([1, 'in']).parse)
- pytest.raises(ValueError, TestIfParser([1, '>', 'in']).parse)
- pytest.raises(ValueError, TestIfParser([1, '==', 'not', 'not']).parse)
+ pytest.raises(ValueError, TestIfParser(["not"]).parse)
+ pytest.raises(ValueError, TestIfParser(["=="]).parse)
+ pytest.raises(ValueError, TestIfParser([1, "in"]).parse)
+ pytest.raises(ValueError, TestIfParser([1, ">", "in"]).parse)
+ pytest.raises(ValueError, TestIfParser([1, "==", "not", "not"]).parse)
pytest.raises(ValueError, TestIfParser([1, 2]).parse)
diff --git a/sigi/apps/diagnosticos/urls.py b/sigi/apps/diagnosticos/urls.py
index 3e170d3..69b82e7 100644
--- a/sigi/apps/diagnosticos/urls.py
+++ b/sigi/apps/diagnosticos/urls.py
@@ -3,50 +3,71 @@ from django.conf.urls import patterns, url
from django.views.generic import TemplateView
-LOGIN_REDIRECT_URL = '/diagnosticos/mobile/login'
+LOGIN_REDIRECT_URL = "/diagnosticos/mobile/login"
urlpatterns = patterns(
- 'sigi.apps.diagnosticos.views',
-
+ "sigi.apps.diagnosticos.views",
# Lista de Diagnósticos
- url(r'^mobile/$', 'lista', name='lista_diagnosticos'),
-
+ url(r"^mobile/$", "lista", name="lista_diagnosticos"),
# Lista de Categorias
- url(r'^mobile/(?P\d+)/categorias/$',
- 'categorias', name='lista_categorias'),
-
+ url(
+ r"^mobile/(?P\d+)/categorias/$",
+ "categorias",
+ name="lista_categorias",
+ ),
# Detalhes da Categoria da Casa Legislativa
- url(r'^mobile/(?P\d+)/categorias/1/$',
- 'categoria_casa_legislativa', name='detalhes_categoria_casa_legislativa'),
-
+ url(
+ r"^mobile/(?P\d+)/categorias/1/$",
+ "categoria_casa_legislativa",
+ name="detalhes_categoria_casa_legislativa",
+ ),
# Detalhes da Categoria de Contatos
- url(r'^mobile/(?P\d+)/categorias/2/$',
- 'categoria_contatos', name='detalhes_categoria_contatos'),
-
+ url(
+ r"^mobile/(?P\d+)/categorias/2/$",
+ "categoria_contatos",
+ name="detalhes_categoria_contatos",
+ ),
# Detalhes de Categorias Dinamicas
- url(r'^mobile/(?P\d+)/categorias/(?P\d+)/$',
- 'categoria_detalhes', name='detalhes_categoria'),
-
- url(r'^mapa/$', TemplateView.as_view(template_name="diagnosticos/mapa.html"), name='template-mapa'),
- url(r'^mundiagjson/$', 'municipios_diagnosticados', name='municipios-diagnosticados'),
-
+ url(
+ r"^mobile/(?P\d+)/categorias/(?P\d+)/$",
+ "categoria_detalhes",
+ name="detalhes_categoria",
+ ),
+ url(
+ r"^mapa/$",
+ TemplateView.as_view(template_name="diagnosticos/mapa.html"),
+ name="template-mapa",
+ ),
+ url(
+ r"^mundiagjson/$",
+ "municipios_diagnosticados",
+ name="municipios-diagnosticados",
+ ),
# Reports diagnosticos
- url(r'^diagnostico/(?P\w+).pdf$', 'diagnostico_pdf', name='diagnostico-pdf'),
-
+ url(
+ r"^diagnostico/(?P\w+).pdf$",
+ "diagnostico_pdf",
+ name="diagnostico-pdf",
+ ),
# Graficos de perguntas
- url(r'^graficos/$', 'graficos', name="diagnosticos-graficos"), # tagerror
- url(r'^api/$', 'grafico_api', name="diagnosticos-grafico-api"), # tagerror
-
+ url(r"^graficos/$", "graficos", name="diagnosticos-graficos"), # tagerror
+ url(r"^api/$", "grafico_api", name="diagnosticos-grafico-api"), # tagerror
)
urlpatterns += patterns(
- 'django.contrib.auth.views',
-
+ "django.contrib.auth.views",
# Login do Diagnóstico
- url(r'^mobile/login/$', 'login', {'template_name':
- 'diagnosticos/diagnosticos_login.html'}, name='login'),
-
+ url(
+ r"^mobile/login/$",
+ "login",
+ {"template_name": "diagnosticos/diagnosticos_login.html"},
+ name="login",
+ ),
# Logout do Diagnóstico
- url(r'^mobile/logout/$', 'logout',
- {'next_page': LOGIN_REDIRECT_URL}, name='logout'),
+ url(
+ r"^mobile/logout/$",
+ "logout",
+ {"next_page": LOGIN_REDIRECT_URL},
+ name="logout",
+ ),
)
diff --git a/sigi/apps/diagnosticos/views.py b/sigi/apps/diagnosticos/views.py
index a3480b6..559dd7d 100644
--- a/sigi/apps/diagnosticos/views.py
+++ b/sigi/apps/diagnosticos/views.py
@@ -11,8 +11,11 @@ from django.views.decorators.cache import never_cache
from sigi.apps.casas.models import Funcionario
from sigi.apps.contatos.models import Telefone
from sigi.apps.diagnosticos.decorators import validate_diagnostico
-from sigi.apps.diagnosticos.forms import (DiagnosticoMobileForm,
- OrgaoMobileForm, FuncionariosMobileForm)
+from sigi.apps.diagnosticos.forms import (
+ DiagnosticoMobileForm,
+ OrgaoMobileForm,
+ FuncionariosMobileForm,
+)
from sigi.apps.diagnosticos.models import Diagnostico, Categoria, Pergunta
from sigi.apps.diagnosticos.urls import LOGIN_REDIRECT_URL
from sigi.apps.utils.decorators import login_required
@@ -27,8 +30,8 @@ def lista(request):
"""
servidor = request.user.servidor
diagnosticos = servidor.diagnosticos
- context = RequestContext(request, {'diagnosticos': diagnosticos})
- return render_to_response('diagnosticos/diagnosticos_list.html', context)
+ context = RequestContext(request, {"diagnosticos": diagnosticos})
+ return render_to_response("diagnosticos/diagnosticos_list.html", context)
@never_cache
@@ -44,12 +47,19 @@ def categorias(request, id_diagnostico):
# Estilizando a lista de categorias para que ajude a identificar
# qual categoria foi a ultima a ser usada, como também as outras
# que ainda não foram acessadas
- ultima_categoria = request.session.get('ultima_categoria', 0)
-
- context = RequestContext(request, {'categorias': categorias,
- 'diagnostico': diagnostico, 'ultima_categoria': ultima_categoria})
- return render_to_response('diagnosticos/diagnosticos_categorias_list.html',
- context)
+ ultima_categoria = request.session.get("ultima_categoria", 0)
+
+ context = RequestContext(
+ request,
+ {
+ "categorias": categorias,
+ "diagnostico": diagnostico,
+ "ultima_categoria": ultima_categoria,
+ },
+ )
+ return render_to_response(
+ "diagnosticos/diagnosticos_categorias_list.html", context
+ )
@never_cache
@@ -68,40 +78,42 @@ def categoria_detalhes(request, id_diagnostico, id_categoria):
# Grava na sessão a categoria atual, para destacar que
# era foi a última visitada.
- request.session['ultima_categoria'] = int(id_categoria)
+ request.session["ultima_categoria"] = int(id_categoria)
try:
categoria = Categoria.objects.get(pk=id_categoria)
except Categoria.DoesNotExist:
context = RequestContext(request)
- return render_to_response('mobile/404.html', context)
+ return render_to_response("mobile/404.html", context)
- diagnostico = Diagnostico.objects.filter(publicado=False).get(pk=id_diagnostico)
+ diagnostico = Diagnostico.objects.filter(publicado=False).get(
+ pk=id_diagnostico
+ )
if request.method == "POST":
- form = DiagnosticoMobileForm(request.POST,
- instance=diagnostico, category=id_categoria)
+ form = DiagnosticoMobileForm(
+ request.POST, instance=diagnostico, category=id_categoria
+ )
if form.is_valid():
form.save()
- resposta = {
- 'mensagem': 'sucesso'
- }
+ resposta = {"mensagem": "sucesso"}
else:
# Montando a estrutura das mensagens de erro no formato JSON
- resposta = {
- 'mensagem': 'erro',
- 'erros': form.errors
- }
+ resposta = {"mensagem": "erro", "erros": form.errors}
json = simplejson.dumps(resposta)
- return HttpResponse(json, content_type='application/json')
+ return HttpResponse(json, content_type="application/json")
else:
- form = DiagnosticoMobileForm(instance=diagnostico,
- category=id_categoria)
-
- context = RequestContext(request, {'form': form, 'categoria': categoria,
- 'diagnostico': diagnostico})
- return render_to_response('diagnosticos/diagnosticos_categorias_form.html',
- context)
+ form = DiagnosticoMobileForm(
+ instance=diagnostico, category=id_categoria
+ )
+
+ context = RequestContext(
+ request,
+ {"form": form, "categoria": categoria, "diagnostico": diagnostico},
+ )
+ return render_to_response(
+ "diagnosticos/diagnosticos_categorias_form.html", context
+ )
@never_cache
@@ -111,35 +123,36 @@ def categoria_casa_legislativa(request, id_diagnostico):
# Grava na sessão a categoria atual, para destacar que
# era foi a última visitada.
- request.session['ultima_categoria'] = 1
+ request.session["ultima_categoria"] = 1
diagnostico = Diagnostico.objects.get(pk=id_diagnostico)
casa_legislativa = diagnostico.casa_legislativa
if request.method == "POST":
- form = OrgaoMobileForm(request.POST,
- instance=casa_legislativa)
+ form = OrgaoMobileForm(request.POST, instance=casa_legislativa)
if form.is_valid():
form.save()
- resposta = {
- 'mensagem': 'sucesso'
- }
+ resposta = {"mensagem": "sucesso"}
else:
# Montando a estrutura das mensagens de erro no formato JSON
- resposta = {
- 'mensagem': 'erro',
- 'erros': form.errors
- }
+ resposta = {"mensagem": "erro", "erros": form.errors}
json = simplejson.dumps(resposta)
- return HttpResponse(json, content_type='application/json')
+ return HttpResponse(json, content_type="application/json")
else:
form = OrgaoMobileForm(instance=casa_legislativa)
- context = RequestContext(request, {'form': form,
- 'diagnostico': diagnostico, 'casa_legislativa': casa_legislativa})
+ context = RequestContext(
+ request,
+ {
+ "form": form,
+ "diagnostico": diagnostico,
+ "casa_legislativa": casa_legislativa,
+ },
+ )
return render_to_response(
- 'diagnosticos/diagnosticos_categoria_casa_legislativa_form.html',
- context)
+ "diagnosticos/diagnosticos_categoria_casa_legislativa_form.html",
+ context,
+ )
@never_cache
@@ -149,7 +162,7 @@ def categoria_contatos(request, id_diagnostico):
# Grava na sessão a categoria atual, para destacar que
# era foi a última visitada.
- request.session['ultima_categoria'] = 2
+ request.session["ultima_categoria"] = 2
diagnostico = Diagnostico.objects.get(pk=id_diagnostico)
casa_legislativa = diagnostico.casa_legislativa
@@ -158,7 +171,9 @@ def categoria_contatos(request, id_diagnostico):
for n, l in Funcionario.SETOR_CHOICES:
if casa_legislativa.funcionario_set.filter(setor=n).count() <= 1:
- funcionarios.append(casa_legislativa.funcionario_set.get_or_create(setor=n))
+ funcionarios.append(
+ casa_legislativa.funcionario_set.get_or_create(setor=n)
+ )
else:
for f in casa_legislativa.funcionario_set.filter(setor=n):
funcionarios.append((f, False))
@@ -167,64 +182,94 @@ def categoria_contatos(request, id_diagnostico):
forms = []
for f, c in funcionarios:
try:
- forms.append(FuncionariosMobileForm(request.POST, prefix=f.setor, instance=f))
+ forms.append(
+ FuncionariosMobileForm(
+ request.POST, prefix=f.setor, instance=f
+ )
+ )
except:
pass
resposta = {
- 'mensagem': 'sucesso',
- 'erros': {},
- 'fones': {},
- 'clean': (),
+ "mensagem": "sucesso",
+ "erros": {},
+ "fones": {},
+ "clean": (),
}
# valida e salva um formulario por vez
for form in forms:
if form.is_valid():
form.save()
- s = ''
+ s = ""
for form_telefones in form.telefones.forms:
tel = form_telefones.instance
- if tel._state.adding and tel.numero != '':
- s += _('Novo telefone %(type)s: %(number)s
') % dict(
+ if tel._state.adding and tel.numero != "":
+ s += _(
+ "Novo telefone %(type)s: %(number)s
"
+ ) % dict(
type=form_telefones.instance.get_tipo_display(),
- number=form_telefones.instance.numero)
- resposta['clean'] += ('id_' + form_telefones.prefix + '-numero',)
- if s != '':
- resposta['fones'][form.prefix] = s
+ number=form_telefones.instance.numero,
+ )
+ resposta["clean"] += (
+ "id_" + form_telefones.prefix + "-numero",
+ )
+ if s != "":
+ resposta["fones"][form.prefix] = s
else:
# Montando a estrutura das mensagens de erro no formato JSON
- resposta['mensagem'] = 'erro'
+ resposta["mensagem"] = "erro"
for key, value in form.errors.iteritems():
- resposta['erros'][form.prefix + '-' + key + '-errors'] = value
+ resposta["erros"][
+ form.prefix + "-" + key + "-errors"
+ ] = value
for form_telefones in form.telefones.forms:
if not form_telefones.is_valid():
- if (form_telefones.fields['id'].initial is not None
- and form_telefones.fields['tipo'].initial == 'I'
- and form_telefones.fields['numero'].initial is None):
- if Telefone.objects.filter(pk=form_telefones.fields['id'].initial).exists():
- Telefone.objects.get(pk=form_telefones.fields['id'].initial).delete()
- if form.prefix not in resposta['fones']:
- resposta['fones'][form.prefix] = ''
- resposta['fones'][form.prefix] += _('O telefone %(type)s %(number)s foi excluído da base de dados
') % dict(
+ if (
+ form_telefones.fields["id"].initial is not None
+ and form_telefones.fields["tipo"].initial == "I"
+ and form_telefones.fields["numero"].initial is None
+ ):
+ if Telefone.objects.filter(
+ pk=form_telefones.fields["id"].initial
+ ).exists():
+ Telefone.objects.get(
+ pk=form_telefones.fields["id"].initial
+ ).delete()
+ if form.prefix not in resposta["fones"]:
+ resposta["fones"][form.prefix] = ""
+ resposta["fones"][form.prefix] += _(
+ "O telefone %(type)s %(number)s foi excluído da base de dados
"
+ ) % dict(
type=form_telefones.instance.get_tipo_display(),
- number=form_telefones.instance.numero)
+ number=form_telefones.instance.numero,
+ )
else:
for key, value in form_telefones.errors.iteritems():
key = form_telefones.prefix + "-id-errors"
- resposta['erros'][key] = value
+ resposta["erros"][key] = value
json = simplejson.dumps(resposta)
- return HttpResponse(json, content_type='application/json')
+ return HttpResponse(json, content_type="application/json")
else:
- forms = [FuncionariosMobileForm(prefix=f.setor, instance=f)
- for f, c in funcionarios]
+ forms = [
+ FuncionariosMobileForm(prefix=f.setor, instance=f)
+ for f, c in funcionarios
+ ]
+
+ context = RequestContext(
+ request,
+ {
+ "forms": forms,
+ "diagnostico": diagnostico,
+ "casa_legislativa": casa_legislativa,
+ },
+ )
+ return render_to_response(
+ "diagnosticos/diagnosticos_categoria_contatos_form.html", context
+ )
- context = RequestContext(request, {'forms': forms,
- 'diagnostico': diagnostico, 'casa_legislativa': casa_legislativa})
- return render_to_response('diagnosticos/diagnosticos_categoria_contatos_form.html',
- context)
@login_required
def diagnostico_pdf(request, id_diagnostico):
@@ -235,7 +280,9 @@ def diagnostico_pdf(request, id_diagnostico):
funcionarios = []
for n, l in Funcionario.SETOR_CHOICES:
if casa_legislativa.funcionario_set.filter(setor=n).count() <= 1:
- funcionarios.append(casa_legislativa.funcionario_set.get_or_create(setor=n))
+ funcionarios.append(
+ casa_legislativa.funcionario_set.get_or_create(setor=n)
+ )
else:
for f in casa_legislativa.funcionario_set.filter(setor=n):
funcionarios.append(f)
@@ -249,24 +296,28 @@ def diagnostico_pdf(request, id_diagnostico):
if datatype == schema.TYPE_MANY:
schema.value = [x.pk for x in data]
elif datatype == schema.TYPE_ONE:
- schema.value = data.pk if data else None,
+ schema.value = (data.pk if data else None,)
else:
schema.value = data
schemas.append(schema)
schemas_by_categoria.append((categoria, schemas))
- context = RequestContext(request, {
- 'pagesize': 'A4',
- 'casa_legislativa': casa_legislativa,
- 'funcionarios': funcionarios,
- 'diagnostico': diagnostico,
- 'schemas_by_categoria': schemas_by_categoria,
- })
-
- return render_to_pdf('diagnosticos/diagnostico_pdf.html', context)
+ context = RequestContext(
+ request,
+ {
+ "pagesize": "A4",
+ "casa_legislativa": casa_legislativa,
+ "funcionarios": funcionarios,
+ "diagnostico": diagnostico,
+ "schemas_by_categoria": schemas_by_categoria,
+ },
+ )
+
+ return render_to_pdf("diagnosticos/diagnostico_pdf.html", context)
# return render_to_response('diagnosticos/diagnostico_pdf.html', context)
+
@login_required
def graficos(request):
categorias = Categoria.objects.all()
@@ -274,73 +325,101 @@ def graficos(request):
sel_categoria = int(request.REQUEST.get("categoria", "3"))
perguntas = Pergunta.objects.filter(categoria=sel_categoria).all()
- context = RequestContext(request, {
- 'categorias': categorias,
- 'sel_categoria': sel_categoria,
- 'perguntas': perguntas,
- })
- return render_to_response('diagnosticos/graficos.html',
- context)
+ context = RequestContext(
+ request,
+ {
+ "categorias": categorias,
+ "sel_categoria": sel_categoria,
+ "perguntas": perguntas,
+ },
+ )
+ return render_to_response("diagnosticos/graficos.html", context)
def percentage(fraction, population):
try:
return "%.0f%%" % ((float(fraction) / float(population)) * 100)
except ValueError:
- return ''
+ return ""
+
@login_required
def grafico_api(request):
- colors = cycle(['#7cb5ec',
- '#434348',
- '#90ed7d',
- '#f7a35c',
- '#8085e9',
- '#f15c80',
- '#e4d354',
- '#8085e8',
- '#8d4653',
- '#91e8e1', ])
-
- highlights = cycle(['#B0D3F4',
- '#8E8E91',
- '#BCF4B1',
- '#FAC89D',
- '#B3B6F2',
- '#F79DB3',
- '#EFE598',
- '#B3B6F1',
- '#BB9098',
- '#BDF1ED', ])
-
- pergunta_slug = request.REQUEST.get('id', None)
+ colors = cycle(
+ [
+ "#7cb5ec",
+ "#434348",
+ "#90ed7d",
+ "#f7a35c",
+ "#8085e9",
+ "#f15c80",
+ "#e4d354",
+ "#8085e8",
+ "#8d4653",
+ "#91e8e1",
+ ]
+ )
+
+ highlights = cycle(
+ [
+ "#B0D3F4",
+ "#8E8E91",
+ "#BCF4B1",
+ "#FAC89D",
+ "#B3B6F2",
+ "#F79DB3",
+ "#EFE598",
+ "#B3B6F1",
+ "#BB9098",
+ "#BDF1ED",
+ ]
+ )
+
+ pergunta_slug = request.REQUEST.get("id", None)
pergunta = get_object_or_404(Pergunta, name=pergunta_slug)
- if pergunta.datatype == 'one':
+ if pergunta.datatype == "one":
list_perguntas = pergunta.group_choices()
- list_perguntas = [{'label': k.title,
- 'value': v,
- 'color': colors.next(),
- 'highlight': highlights.next()}
- for k, v in list_perguntas]
+ list_perguntas = [
+ {
+ "label": k.title,
+ "value": v,
+ "color": colors.next(),
+ "highlight": highlights.next(),
+ }
+ for k, v in list_perguntas
+ ]
# list_perguntas = [[k.title, v, colors.next(), highlights.next()] for k, v in list_perguntas]
# elif pergunta.datatype == 'many':
- jsonn = simplejson.dumps(list_perguntas, sort_keys=True, indent=4, separators=(',', ': '))
+ jsonn = simplejson.dumps(
+ list_perguntas, sort_keys=True, indent=4, separators=(",", ": ")
+ )
return HttpResponse(jsonn, content_type="application/json")
+
@login_required
def municipios_diagnosticados(self):
municipios = []
for d in Diagnostico.objects.all():
m = d.casa_legislativa.municipio
- municipio = {'nome': d.casa_legislativa.nome + ', ' + m.uf.sigla, 'lat': str(m.latitude), 'lng': str(m.longitude), 'inicio': d.data_visita_inicio,
- 'fim': d.data_visita_fim, 'equipe': "" + " ".join([m.user.get_full_name() for m in d.membros]) + " ", }
+ municipio = {
+ "nome": d.casa_legislativa.nome + ", " + m.uf.sigla,
+ "lat": str(m.latitude),
+ "lng": str(m.longitude),
+ "inicio": d.data_visita_inicio,
+ "fim": d.data_visita_fim,
+ "equipe": ""
+ + " ".join([m.user.get_full_name() for m in d.membros])
+ + " ",
+ }
municipios.append(municipio)
- return HttpResponse(simplejson.dumps(municipios), content_type='application/json')
+ return HttpResponse(
+ simplejson.dumps(municipios), content_type="application/json"
+ )
diff --git a/sigi/apps/diagnosticos/widgets.py b/sigi/apps/diagnosticos/widgets.py
index 058ea27..bdbbf12 100644
--- a/sigi/apps/diagnosticos/widgets.py
+++ b/sigi/apps/diagnosticos/widgets.py
@@ -1,5 +1,11 @@
from itertools import chain
-from django.forms.widgets import CheckboxInput, CheckboxSelectMultiple, RadioSelect, RadioFieldRenderer, RadioInput
+from django.forms.widgets import (
+ CheckboxInput,
+ CheckboxSelectMultiple,
+ RadioSelect,
+ RadioFieldRenderer,
+ RadioInput,
+)
from django.utils.html import conditional_escape
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
@@ -7,34 +13,39 @@ from sigi.apps.diagnosticos.models import Escolha
class EavCheckboxSelectMultiple(CheckboxSelectMultiple):
-
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = []
final_attrs = self.build_attrs(attrs, name=name)
- output = ['']
+ output = [""]
str_values = set([force_unicode(v) for v in value])
- for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
- final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
- label_for = ' for="%s"' % final_attrs['id']
+ for i, (option_value, option_label) in enumerate(
+ chain(self.choices, choices)
+ ):
+ final_attrs = dict(final_attrs, id="%s_%s" % (attrs["id"], i))
+ label_for = ' for="%s"' % final_attrs["id"]
# Caso exista uma pergunta para abrir
# adiciona um atripbuto no checkbox
schema_to_open = Escolha.objects.get(pk=option_value).schema_to_open
if schema_to_open:
- final_attrs['schema_to_open'] = schema_to_open.name
+ final_attrs["schema_to_open"] = schema_to_open.name
- cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
+ cb = CheckboxInput(
+ final_attrs, check_test=lambda value: value in str_values
+ )
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
- output.append('%s %s ' % (label_for, rendered_cb, option_label))
- output.append(' ')
- return mark_safe('\n'.join(output))
+ output.append(
+ "%s %s "
+ % (label_for, rendered_cb, option_label)
+ )
+ output.append(" ")
+ return mark_safe("\n".join(output))
class EavRadioFieldRenderer(RadioFieldRenderer):
-
def __iter__(self):
for i, choice in enumerate(self.choices):
final_attrs = self.attrs.copy()
@@ -42,9 +53,11 @@ class EavRadioFieldRenderer(RadioFieldRenderer):
# Caso exista uma pergunta para abrir
# adiciona um atripbuto no checkbox
if choice[0]:
- schema_to_open = Escolha.objects.get(pk=choice[0]).schema_to_open
+ schema_to_open = Escolha.objects.get(
+ pk=choice[0]
+ ).schema_to_open
if schema_to_open:
- final_attrs['schema_to_open'] = schema_to_open.name
+ final_attrs["schema_to_open"] = schema_to_open.name
yield RadioInput(self.name, self.value, final_attrs, choice, i)
@@ -57,7 +70,7 @@ class EavRadioFieldRenderer(RadioFieldRenderer):
# adiciona um atripbuto no checkbox
schema_to_open = Escolha.objects.get(pk=self.value).schema_to_open
if schema_to_open:
- final_attrs['schema_to_open'] = schema_to_open.name
+ final_attrs["schema_to_open"] = schema_to_open.name
return RadioInput(self.name, self.value, final_attrs, choice, idx)
diff --git a/sigi/apps/eventos/admin.py b/sigi/apps/eventos/admin.py
index 2099770..4e96aec 100644
--- a/sigi/apps/eventos/admin.py
+++ b/sigi/apps/eventos/admin.py
@@ -4,94 +4,163 @@ from django.utils.translation import gettext as _
from import_export.fields import Field
from tinymce.models import HTMLField
from tinymce.widgets import AdminTinyMCE
-from sigi.apps.eventos.models import (ModeloDeclaracao, Modulo, TipoEvento,
- Funcao, Evento, Equipe, Convite, Anexo)
+from sigi.apps.eventos.models import (
+ ModeloDeclaracao,
+ Modulo,
+ TipoEvento,
+ Funcao,
+ Evento,
+ Equipe,
+ Convite,
+ Anexo,
+)
from sigi.apps.eventos.forms import EventoAdminForm
from sigi.apps.utils.filters import EmptyFilter
from sigi.apps.utils.mixins import CartExportMixin, ValueLabeledResource
+
class EventoResource(ValueLabeledResource):
# categoria_evento = Field(column_name="tipo_evento__categoria")
# status = Field(column_name="status")
class Meta:
model = Evento
fields = (
- 'id', 'tipo_evento__nome', 'tipo_evento__categoria', 'nome',
- 'descricao', 'virtual', 'solicitante', 'num_processo',
- 'data_pedido', 'data_inicio', 'data_termino', 'carga_horaria',
- 'casa_anfitria__nome', 'casa_anfitria__logradouro',
- 'casa_anfitria__bairro', 'casa_anfitria__municipio__nome',
- 'casa_anfitria__municipio__uf__sigla', 'casa_anfitria__cep',
- 'casa_anfitria__email', 'local', 'municipio__nome',
- 'municipio__uf__sigla', 'observacao', 'publico_alvo',
- 'total_participantes', 'status', 'data_cancelamento',
- 'motivo_cancelamento', 'equipe__membro__nome_completo',
- 'equipe__funcao__nome', 'convite__casa__nome',
- 'convite__casa__municipio__nome',
- 'convite__casa__municipio__uf__sigla', 'convite__casa__cep',
- 'convite__casa__email', 'convite__aceite', 'convite__data_convite',
- 'convite__participou', 'convite__qtde_participantes',
- 'convite__nomes_participantes',
+ "id",
+ "tipo_evento__nome",
+ "tipo_evento__categoria",
+ "nome",
+ "descricao",
+ "virtual",
+ "solicitante",
+ "num_processo",
+ "data_pedido",
+ "data_inicio",
+ "data_termino",
+ "carga_horaria",
+ "casa_anfitria__nome",
+ "casa_anfitria__logradouro",
+ "casa_anfitria__bairro",
+ "casa_anfitria__municipio__nome",
+ "casa_anfitria__municipio__uf__sigla",
+ "casa_anfitria__cep",
+ "casa_anfitria__email",
+ "local",
+ "municipio__nome",
+ "municipio__uf__sigla",
+ "observacao",
+ "publico_alvo",
+ "total_participantes",
+ "status",
+ "data_cancelamento",
+ "motivo_cancelamento",
+ "equipe__membro__nome_completo",
+ "equipe__funcao__nome",
+ "convite__casa__nome",
+ "convite__casa__municipio__nome",
+ "convite__casa__municipio__uf__sigla",
+ "convite__casa__cep",
+ "convite__casa__email",
+ "convite__aceite",
+ "convite__data_convite",
+ "convite__participou",
+ "convite__qtde_participantes",
+ "convite__nomes_participantes",
)
export_order = fields
def dehydrate_tipo_evento__categoria(self, obj):
- return dict(TipoEvento.CATEGORIA_CHOICES)[obj['tipo_evento__categoria']]
+ return dict(TipoEvento.CATEGORIA_CHOICES)[obj["tipo_evento__categoria"]]
def dehydrate_virtual(self, obj):
- return "Sim" if obj['virtual'] else "Não"
+ return "Sim" if obj["virtual"] else "Não"
def dehydrate_status(self, obj):
- return dict(Evento.STATUS_CHOICES)[obj['status']]
+ return dict(Evento.STATUS_CHOICES)[obj["status"]]
def dehydrate_convite__aceite(self, obj):
- return "Sim" if obj['convite__aceite'] else "Não"
+ return "Sim" if obj["convite__aceite"] else "Não"
def dehydrate_convite__participou(self, obj):
- return "Sim" if obj['convite__participou'] else "Não"
+ return "Sim" if obj["convite__participou"] else "Não"
+
@admin.register(TipoEvento)
class TipoEventAdmin(admin.ModelAdmin):
- search_fields = ('nome',)
+ search_fields = ("nome",)
+
@admin.register(Funcao)
class FuncaoAdmin(admin.ModelAdmin):
- list_display = ('nome', 'descricao',)
- search_fields = ('nome', 'descricao',)
+ list_display = (
+ "nome",
+ "descricao",
+ )
+ search_fields = (
+ "nome",
+ "descricao",
+ )
+
@admin.register(ModeloDeclaracao)
class ModeloDeclaracaoAdmin(admin.ModelAdmin):
- list_display = ('nome', 'formato')
- formfield_overrides = {HTMLField: {'widget': AdminTinyMCE}}
+ list_display = ("nome", "formato")
+ formfield_overrides = {HTMLField: {"widget": AdminTinyMCE}}
+
class EquipeInline(admin.StackedInline):
model = Equipe
+
class ConviteInline(admin.StackedInline):
model = Convite
- raw_id_fields = ('casa',)
+ raw_id_fields = ("casa",)
+
class ModuloInline(admin.StackedInline):
model = Modulo
+
class AnexoInline(admin.StackedInline):
model = Anexo
- exclude = ('data_pub',)
+ exclude = ("data_pub",)
+
@admin.register(Evento)
class EventoAdmin(CartExportMixin, admin.ModelAdmin):
form = EventoAdminForm
resource_class = EventoResource
- date_hierarchy = 'data_inicio'
- list_display = ('nome', 'tipo_evento', 'status', 'link_sigad',
- 'data_inicio', 'data_termino', 'municipio', 'solicitante',
- 'total_participantes',)
- list_filter = ('status', ('num_processo', EmptyFilter), 'tipo_evento',
- 'tipo_evento__categoria', 'virtual', 'municipio__uf',
- 'solicitante')
- raw_id_fields = ('casa_anfitria', 'municipio',)
- search_fields = ('nome', 'tipo_evento__nome', 'casa_anfitria__search_text',
- 'municipio__search_text', 'solicitante')
+ date_hierarchy = "data_inicio"
+ list_display = (
+ "nome",
+ "tipo_evento",
+ "status",
+ "link_sigad",
+ "data_inicio",
+ "data_termino",
+ "municipio",
+ "solicitante",
+ "total_participantes",
+ )
+ list_filter = (
+ "status",
+ ("num_processo", EmptyFilter),
+ "tipo_evento",
+ "tipo_evento__categoria",
+ "virtual",
+ "municipio__uf",
+ "solicitante",
+ )
+ raw_id_fields = (
+ "casa_anfitria",
+ "municipio",
+ )
+ search_fields = (
+ "nome",
+ "tipo_evento__nome",
+ "casa_anfitria__search_text",
+ "municipio__search_text",
+ "solicitante",
+ )
inlines = (EquipeInline, ConviteInline, ModuloInline, AnexoInline)
save_as = True
@@ -99,10 +168,14 @@ class EventoAdmin(CartExportMixin, admin.ModelAdmin):
if obj.pk is None:
return ""
return obj.get_sigad_url()
- link_sigad.short_description = _(u"número do processo SIGAD")
+
+ link_sigad.short_description = _("número do processo SIGAD")
link_sigad.allow_tags = True
def lookup_allowed(self, lookup, value):
- return (super(EventoAdmin, self).lookup_allowed(lookup, value) or
- lookup in ['tipo_evento__nome__exact',
- 'tipo_evento__nome__contains'])
+ return super(EventoAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in [
+ "tipo_evento__nome__exact",
+ "tipo_evento__nome__contains",
+ ]
diff --git a/sigi/apps/eventos/apps.py b/sigi/apps/eventos/apps.py
index 8ce1c87..db65204 100644
--- a/sigi/apps/eventos/apps.py
+++ b/sigi/apps/eventos/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class EventosConfig(AppConfig):
- name = 'sigi.apps.eventos'
- verbose_name = _('Eventos Interlegis')
+ name = "sigi.apps.eventos"
+ verbose_name = _("Eventos Interlegis")
diff --git a/sigi/apps/eventos/forms.py b/sigi/apps/eventos/forms.py
index e100412..0d99e7c 100644
--- a/sigi/apps/eventos/forms.py
+++ b/sigi/apps/eventos/forms.py
@@ -2,14 +2,31 @@ from django import forms
from django.utils.translation import gettext as _
from sigi.apps.eventos.models import ModeloDeclaracao, Evento
+
class EventoAdminForm(forms.ModelForm):
class Meta:
model = Evento
- fields = ('tipo_evento', 'nome', 'descricao', 'virtual', 'solicitante',
- 'num_processo', 'data_pedido', 'data_inicio', 'data_termino',
- 'carga_horaria', 'casa_anfitria', 'municipio', 'observacao',
- 'local', 'publico_alvo', 'total_participantes', 'status',
- 'data_cancelamento', 'motivo_cancelamento', )
+ fields = (
+ "tipo_evento",
+ "nome",
+ "descricao",
+ "virtual",
+ "solicitante",
+ "num_processo",
+ "data_pedido",
+ "data_inicio",
+ "data_termino",
+ "carga_horaria",
+ "casa_anfitria",
+ "municipio",
+ "observacao",
+ "local",
+ "publico_alvo",
+ "total_participantes",
+ "status",
+ "data_cancelamento",
+ "motivo_cancelamento",
+ )
def clean(self):
cleaned_data = super(EventoAdminForm, self).clean()
@@ -19,12 +36,13 @@ class EventoAdminForm(forms.ModelForm):
if data_inicio > data_termino:
raise forms.ValidationError(
_("Data término deve ser posterior à data inicio"),
- code="invalid_period"
+ code="invalid_period",
)
+
class SelecionaModeloForm(forms.Form):
modelo = forms.ModelChoiceField(
queryset=ModeloDeclaracao.objects.all(),
required=True,
label=_("Modelo de declaração"),
- )
\ No newline at end of file
+ )
diff --git a/sigi/apps/eventos/migrations/0001_initial.py b/sigi/apps/eventos/migrations/0001_initial.py
index 0e07be4..2b72638 100644
--- a/sigi/apps/eventos/migrations/0001_initial.py
+++ b/sigi/apps/eventos/migrations/0001_initial.py
@@ -7,130 +7,292 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
- ('contatos', '0001_initial'),
- ('casas', '0002_auto_20150710_1247'),
+ ("servidores", "0001_initial"),
+ ("contatos", "0001_initial"),
+ ("casas", "0002_auto_20150710_1247"),
]
operations = [
migrations.CreateModel(
- name='Convite',
+ name="Convite",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('data_convite', models.DateField(verbose_name='Data do convite')),
- ('aceite', models.BooleanField(default=False, verbose_name='Aceitou o convite')),
- ('participou', models.BooleanField(default=False, verbose_name='Participou do evento')),
- ('casa', models.ForeignKey(verbose_name='Casa convidada', to='casas.CasaLegislativa', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "data_convite",
+ models.DateField(verbose_name="Data do convite"),
+ ),
+ (
+ "aceite",
+ models.BooleanField(
+ default=False, verbose_name="Aceitou o convite"
+ ),
+ ),
+ (
+ "participou",
+ models.BooleanField(
+ default=False, verbose_name="Participou do evento"
+ ),
+ ),
+ (
+ "casa",
+ models.ForeignKey(
+ verbose_name="Casa convidada",
+ to="casas.CasaLegislativa",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('evento', 'casa', '-data_convite'),
- 'verbose_name': 'Casa convidada',
- 'verbose_name_plural': 'Casas convidadas',
+ "ordering": ("evento", "casa", "-data_convite"),
+ "verbose_name": "Casa convidada",
+ "verbose_name_plural": "Casas convidadas",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Equipe',
+ name="Equipe",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('observacoes', models.TextField(verbose_name='Observa\xe7\xf5es', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "observacoes",
+ models.TextField(
+ verbose_name="Observa\xe7\xf5es", blank=True
+ ),
+ ),
],
options={
- 'ordering': ('evento', 'funcao', 'membro'),
- 'verbose_name': 'Membro da equipe',
- 'verbose_name_plural': 'Membros da equipe',
+ "ordering": ("evento", "funcao", "membro"),
+ "verbose_name": "Membro da equipe",
+ "verbose_name_plural": "Membros da equipe",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Evento',
+ name="Evento",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome do evento')),
- ('descricao', models.TextField(verbose_name='Descri\xe7\xe3o do evento')),
- ('solicitante', models.CharField(max_length=100, verbose_name='Solicitante')),
- ('data_inicio', models.DateField(verbose_name='Data de in\xedcio')),
- ('data_termino', models.DateField(verbose_name='Data de t\xe9rmino')),
- ('local', models.TextField(verbose_name='Local do evento', blank=True)),
- ('publico_alvo', models.TextField(verbose_name='P\xfablico alvo', blank=True)),
- ('status', models.CharField(max_length=1, verbose_name='Status', choices=[('P', 'Previs\xe3o'), ('A', 'A confirmar'), ('O', 'Confirmado'), ('R', 'Realizado'), ('C', 'Cancelado')])),
- ('data_cancelamento', models.DateField(null=True, verbose_name='Data de cancelamento', blank=True)),
- ('motivo_cancelamento', models.TextField(verbose_name='Motivo do cancelamento', blank=True)),
- ('casa_anfitria', models.ForeignKey(verbose_name='Casa anfitri\xe3', blank=True, to='casas.CasaLegislativa', null=True, on_delete=models.CASCADE)),
- ('municipio', models.ForeignKey(to='contatos.Municipio', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=100, verbose_name="Nome do evento"
+ ),
+ ),
+ (
+ "descricao",
+ models.TextField(verbose_name="Descri\xe7\xe3o do evento"),
+ ),
+ (
+ "solicitante",
+ models.CharField(
+ max_length=100, verbose_name="Solicitante"
+ ),
+ ),
+ (
+ "data_inicio",
+ models.DateField(verbose_name="Data de in\xedcio"),
+ ),
+ (
+ "data_termino",
+ models.DateField(verbose_name="Data de t\xe9rmino"),
+ ),
+ (
+ "local",
+ models.TextField(
+ verbose_name="Local do evento", blank=True
+ ),
+ ),
+ (
+ "publico_alvo",
+ models.TextField(
+ verbose_name="P\xfablico alvo", blank=True
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ max_length=1,
+ verbose_name="Status",
+ choices=[
+ ("P", "Previs\xe3o"),
+ ("A", "A confirmar"),
+ ("O", "Confirmado"),
+ ("R", "Realizado"),
+ ("C", "Cancelado"),
+ ],
+ ),
+ ),
+ (
+ "data_cancelamento",
+ models.DateField(
+ null=True,
+ verbose_name="Data de cancelamento",
+ blank=True,
+ ),
+ ),
+ (
+ "motivo_cancelamento",
+ models.TextField(
+ verbose_name="Motivo do cancelamento", blank=True
+ ),
+ ),
+ (
+ "casa_anfitria",
+ models.ForeignKey(
+ verbose_name="Casa anfitri\xe3",
+ blank=True,
+ to="casas.CasaLegislativa",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "municipio",
+ models.ForeignKey(
+ to="contatos.Municipio", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'ordering': ('-data_inicio',),
- 'verbose_name': 'Evento',
- 'verbose_name_plural': 'Eventos',
+ "ordering": ("-data_inicio",),
+ "verbose_name": "Evento",
+ "verbose_name_plural": "Eventos",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Funcao',
+ name="Funcao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Fun\xe7\xe3o na equipe de evento')),
- ('descricao', models.TextField(verbose_name='Descri\xe7\xe3o da fun\xe7\xe3o')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=100,
+ verbose_name="Fun\xe7\xe3o na equipe de evento",
+ ),
+ ),
+ (
+ "descricao",
+ models.TextField(
+ verbose_name="Descri\xe7\xe3o da fun\xe7\xe3o"
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'Fun\xe7\xe3o',
- 'verbose_name_plural': 'Fun\xe7\xf5es',
+ "ordering": ("nome",),
+ "verbose_name": "Fun\xe7\xe3o",
+ "verbose_name_plural": "Fun\xe7\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='TipoEvento',
+ name="TipoEvento",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=100, verbose_name="Nome")),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'Tipo de evento',
- 'verbose_name_plural': 'Tipos de evento',
+ "ordering": ("nome",),
+ "verbose_name": "Tipo de evento",
+ "verbose_name_plural": "Tipos de evento",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='evento',
- name='tipo_evento',
- field=models.ForeignKey(to='eventos.TipoEvento', on_delete=models.CASCADE),
+ model_name="evento",
+ name="tipo_evento",
+ field=models.ForeignKey(
+ to="eventos.TipoEvento", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='equipe',
- name='evento',
- field=models.ForeignKey(to='eventos.Evento', on_delete=models.CASCADE),
+ model_name="equipe",
+ name="evento",
+ field=models.ForeignKey(
+ to="eventos.Evento", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='equipe',
- name='funcao',
- field=models.ForeignKey(verbose_name='Fun\xe7\xe3o na equipe', to='eventos.Funcao', on_delete=models.CASCADE),
+ model_name="equipe",
+ name="funcao",
+ field=models.ForeignKey(
+ verbose_name="Fun\xe7\xe3o na equipe",
+ to="eventos.Funcao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='equipe',
- name='membro',
- field=models.ForeignKey(related_name='equipe_evento', to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="equipe",
+ name="membro",
+ field=models.ForeignKey(
+ related_name="equipe_evento",
+ to="servidores.Servidor",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convite',
- name='evento',
- field=models.ForeignKey(to='eventos.Evento', on_delete=models.CASCADE),
+ model_name="convite",
+ name="evento",
+ field=models.ForeignKey(
+ to="eventos.Evento", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convite',
- name='servidor',
- field=models.ForeignKey(verbose_name='Servidor que convido', to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="convite",
+ name="servidor",
+ field=models.ForeignKey(
+ verbose_name="Servidor que convido",
+ to="servidores.Servidor",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='convite',
- unique_together=set([('evento', 'casa')]),
+ name="convite",
+ unique_together=set([("evento", "casa")]),
),
]
diff --git a/sigi/apps/eventos/migrations/0002_auto_20151016_1449.py b/sigi/apps/eventos/migrations/0002_auto_20151016_1449.py
index 08aad72..3edb1c8 100644
--- a/sigi/apps/eventos/migrations/0002_auto_20151016_1449.py
+++ b/sigi/apps/eventos/migrations/0002_auto_20151016_1449.py
@@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0001_initial'),
+ ("eventos", "0001_initial"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/eventos/migrations/0003_auto_20151104_0810.py b/sigi/apps/eventos/migrations/0003_auto_20151104_0810.py
index 01fcd86..d1565c0 100644
--- a/sigi/apps/eventos/migrations/0003_auto_20151104_0810.py
+++ b/sigi/apps/eventos/migrations/0003_auto_20151104_0810.py
@@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0002_auto_20151016_1449'),
+ ("eventos", "0002_auto_20151016_1449"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/eventos/migrations/0004_auto_20160719_0920.py b/sigi/apps/eventos/migrations/0004_auto_20160719_0920.py
index 6e70d8b..936c35e 100644
--- a/sigi/apps/eventos/migrations/0004_auto_20160719_0920.py
+++ b/sigi/apps/eventos/migrations/0004_auto_20160719_0920.py
@@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0003_auto_20151104_0810'),
+ ("eventos", "0003_auto_20151104_0810"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/eventos/migrations/0004_remove_evento_curso_moodle_id.py b/sigi/apps/eventos/migrations/0004_remove_evento_curso_moodle_id.py
index 6e70d8b..936c35e 100644
--- a/sigi/apps/eventos/migrations/0004_remove_evento_curso_moodle_id.py
+++ b/sigi/apps/eventos/migrations/0004_remove_evento_curso_moodle_id.py
@@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0003_auto_20151104_0810'),
+ ("eventos", "0003_auto_20151104_0810"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py b/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py
index 2c440ae..e996a4f 100644
--- a/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py
+++ b/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py
@@ -7,21 +7,31 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0004_remove_evento_curso_moodle_id'),
- ('casas', '0014_auto_20210406_1945'),
+ ("eventos", "0004_remove_evento_curso_moodle_id"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='convite',
- name='casa',
- field=models.ForeignKey(verbose_name='Casa convidada', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="convite",
+ name="casa",
+ field=models.ForeignKey(
+ verbose_name="Casa convidada",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='evento',
- name='casa_anfitria',
- field=models.ForeignKey(verbose_name='Casa anfitri\xe3', blank=True, to='casas.Orgao', null=True, on_delete=models.CASCADE),
+ model_name="evento",
+ name="casa_anfitria",
+ field=models.ForeignKey(
+ verbose_name="Casa anfitri\xe3",
+ blank=True,
+ to="casas.Orgao",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0006_auto_20210416_0841.py b/sigi/apps/eventos/migrations/0006_auto_20210416_0841.py
index addbdbb..8eca59b 100644
--- a/sigi/apps/eventos/migrations/0006_auto_20210416_0841.py
+++ b/sigi/apps/eventos/migrations/0006_auto_20210416_0841.py
@@ -8,50 +8,78 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0005_auto_20210406_1945'),
+ ("eventos", "0005_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='convite',
- name='casa',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa convidada', to='casas.Orgao'),
+ model_name="convite",
+ name="casa",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Casa convidada",
+ to="casas.Orgao",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='convite',
- name='servidor',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Servidor que convido', to='servidores.Servidor'),
+ model_name="convite",
+ name="servidor",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Servidor que convido",
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='equipe',
- name='funcao',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Fun\xe7\xe3o na equipe', to='eventos.Funcao'),
+ model_name="equipe",
+ name="funcao",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Fun\xe7\xe3o na equipe",
+ to="eventos.Funcao",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='equipe',
- name='membro',
- field=models.ForeignKey(related_name='equipe_evento', on_delete=django.db.models.deletion.PROTECT, to='servidores.Servidor'),
+ model_name="equipe",
+ name="membro",
+ field=models.ForeignKey(
+ related_name="equipe_evento",
+ on_delete=django.db.models.deletion.PROTECT,
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='evento',
- name='casa_anfitria',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa anfitri\xe3', blank=True, to='casas.Orgao', null=True),
+ model_name="evento",
+ name="casa_anfitria",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Casa anfitri\xe3",
+ blank=True,
+ to="casas.Orgao",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='evento',
- name='municipio',
- field=models.ForeignKey(to='contatos.Municipio', on_delete=django.db.models.deletion.PROTECT),
+ model_name="evento",
+ name="municipio",
+ field=models.ForeignKey(
+ to="contatos.Municipio",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='evento',
- name='tipo_evento',
- field=models.ForeignKey(to='eventos.TipoEvento', on_delete=django.db.models.deletion.PROTECT),
+ model_name="evento",
+ name="tipo_evento",
+ field=models.ForeignKey(
+ to="eventos.TipoEvento",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0007_auto_20210417_0744.py b/sigi/apps/eventos/migrations/0007_auto_20210417_0744.py
index e00c563..2256ac3 100644
--- a/sigi/apps/eventos/migrations/0007_auto_20210417_0744.py
+++ b/sigi/apps/eventos/migrations/0007_auto_20210417_0744.py
@@ -7,32 +7,40 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0006_auto_20210416_0841'),
+ ("eventos", "0006_auto_20210416_0841"),
]
operations = [
migrations.AddField(
- model_name='convite',
- name='nomes_participantes',
- field=models.TextField(help_text='Favor colocar um participante por linha', verbose_name='nome dos participantes', blank=True),
+ model_name="convite",
+ name="nomes_participantes",
+ field=models.TextField(
+ help_text="Favor colocar um participante por linha",
+ verbose_name="nome dos participantes",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='convite',
- name='qtde_participantes',
- field=models.PositiveIntegerField(default=0, verbose_name='n\xfamero de participantes'),
+ model_name="convite",
+ name="qtde_participantes",
+ field=models.PositiveIntegerField(
+ default=0, verbose_name="n\xfamero de participantes"
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='evento',
- name='carga_horaria',
- field=models.PositiveIntegerField(default=0, verbose_name='carga hor\xe1ria'),
+ model_name="evento",
+ name="carga_horaria",
+ field=models.PositiveIntegerField(
+ default=0, verbose_name="carga hor\xe1ria"
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='evento',
- name='virtual',
- field=models.BooleanField(default=False, verbose_name='Virtual'),
+ model_name="evento",
+ name="virtual",
+ field=models.BooleanField(default=False, verbose_name="Virtual"),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0008_auto_20211104_1253.py b/sigi/apps/eventos/migrations/0008_auto_20211104_1253.py
index 2231f84..e691516 100644
--- a/sigi/apps/eventos/migrations/0008_auto_20211104_1253.py
+++ b/sigi/apps/eventos/migrations/0008_auto_20211104_1253.py
@@ -7,20 +7,24 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0007_auto_20210417_0744'),
+ ("eventos", "0007_auto_20210417_0744"),
]
operations = [
migrations.AlterField(
- model_name='evento',
- name='data_inicio',
- field=models.DateTimeField(null=True, verbose_name='Data/hora do In\xedcio', blank=True),
+ model_name="evento",
+ name="data_inicio",
+ field=models.DateTimeField(
+ null=True, verbose_name="Data/hora do In\xedcio", blank=True
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='evento',
- name='data_termino',
- field=models.DateTimeField(null=True, verbose_name='Data/hora do Termino', blank=True),
+ model_name="evento",
+ name="data_termino",
+ field=models.DateTimeField(
+ null=True, verbose_name="Data/hora do Termino", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0009_tipoevento_categoria.py b/sigi/apps/eventos/migrations/0009_tipoevento_categoria.py
index 89198bc..303a829 100644
--- a/sigi/apps/eventos/migrations/0009_tipoevento_categoria.py
+++ b/sigi/apps/eventos/migrations/0009_tipoevento_categoria.py
@@ -7,14 +7,25 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0008_auto_20211104_1253'),
+ ("eventos", "0008_auto_20211104_1253"),
]
operations = [
migrations.AddField(
- model_name='tipoevento',
- name='categoria',
- field=models.CharField(default='E', max_length=1, verbose_name='Categoaria', choices=[('C', 'Curso'), ('E', 'Encontro'), ('O', 'Oficina'), ('S', 'Semin\xe1rio'), ('V', 'Visita')]),
+ model_name="tipoevento",
+ name="categoria",
+ field=models.CharField(
+ default="E",
+ max_length=1,
+ verbose_name="Categoaria",
+ choices=[
+ ("C", "Curso"),
+ ("E", "Encontro"),
+ ("O", "Oficina"),
+ ("S", "Semin\xe1rio"),
+ ("V", "Visita"),
+ ],
+ ),
preserve_default=False,
),
]
diff --git a/sigi/apps/eventos/migrations/0010_modulo.py b/sigi/apps/eventos/migrations/0010_modulo.py
index 7190464..29a446a 100644
--- a/sigi/apps/eventos/migrations/0010_modulo.py
+++ b/sigi/apps/eventos/migrations/0010_modulo.py
@@ -8,29 +8,107 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0007_auto_20210430_0735'),
- ('eventos', '0009_tipoevento_categoria'),
+ ("servidores", "0007_auto_20210430_0735"),
+ ("eventos", "0009_tipoevento_categoria"),
]
operations = [
migrations.CreateModel(
- name='Modulo',
+ name="Modulo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome')),
- ('descricao', models.TextField(verbose_name='Descri\xe7\xe3o do m\xf3dulo')),
- ('tipo', models.CharField(max_length=1, verbose_name='Tipo', choices=[('A', 'Aula'), ('P', 'Palestra'), ('R', 'Apresenta\xe7\xe3o')])),
- ('inicio', models.DateTimeField(null=True, verbose_name='Data/hora de in\xedcio', blank=True)),
- ('termino', models.DateTimeField(null=True, verbose_name='Data/hora de t\xe9rmino', blank=True)),
- ('carga_horaria', models.PositiveIntegerField(default=0, verbose_name='carga hor\xe1ria')),
- ('qtde_participantes', models.PositiveIntegerField(default=0, help_text='Deixar Zero significa que todos os participantes do evento participaram do m\xf3dulo', verbose_name='n\xfamero de participantes')),
- ('apresentador', models.ForeignKey(related_name='modulo_apresentador', on_delete=django.db.models.deletion.PROTECT, verbose_name='Apresentador', blank=True, to='servidores.Servidor', null=True)),
- ('evento', models.ForeignKey(verbose_name='Evento', to='eventos.Evento', on_delete=models.CASCADE)),
- ('monitor', models.ForeignKey(related_name='modulo_monitor', on_delete=django.db.models.deletion.PROTECT, blank=True, to='servidores.Servidor', help_text='Monitor, mediador, auxiliar, etc.', null=True, verbose_name='Monitor')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=100, verbose_name="Nome")),
+ (
+ "descricao",
+ models.TextField(
+ verbose_name="Descri\xe7\xe3o do m\xf3dulo"
+ ),
+ ),
+ (
+ "tipo",
+ models.CharField(
+ max_length=1,
+ verbose_name="Tipo",
+ choices=[
+ ("A", "Aula"),
+ ("P", "Palestra"),
+ ("R", "Apresenta\xe7\xe3o"),
+ ],
+ ),
+ ),
+ (
+ "inicio",
+ models.DateTimeField(
+ null=True,
+ verbose_name="Data/hora de in\xedcio",
+ blank=True,
+ ),
+ ),
+ (
+ "termino",
+ models.DateTimeField(
+ null=True,
+ verbose_name="Data/hora de t\xe9rmino",
+ blank=True,
+ ),
+ ),
+ (
+ "carga_horaria",
+ models.PositiveIntegerField(
+ default=0, verbose_name="carga hor\xe1ria"
+ ),
+ ),
+ (
+ "qtde_participantes",
+ models.PositiveIntegerField(
+ default=0,
+ help_text="Deixar Zero significa que todos os participantes do evento participaram do m\xf3dulo",
+ verbose_name="n\xfamero de participantes",
+ ),
+ ),
+ (
+ "apresentador",
+ models.ForeignKey(
+ related_name="modulo_apresentador",
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Apresentador",
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
+ ),
+ (
+ "evento",
+ models.ForeignKey(
+ verbose_name="Evento",
+ to="eventos.Evento",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "monitor",
+ models.ForeignKey(
+ related_name="modulo_monitor",
+ on_delete=django.db.models.deletion.PROTECT,
+ blank=True,
+ to="servidores.Servidor",
+ help_text="Monitor, mediador, auxiliar, etc.",
+ null=True,
+ verbose_name="Monitor",
+ ),
+ ),
],
options={
- 'verbose_name': 'M\xf3dulo do evento',
- 'verbose_name_plural': 'M\xf3dulos do evento',
+ "verbose_name": "M\xf3dulo do evento",
+ "verbose_name_plural": "M\xf3dulos do evento",
},
bases=(models.Model,),
),
diff --git a/sigi/apps/eventos/migrations/0011_auto_20211117_0633.py b/sigi/apps/eventos/migrations/0011_auto_20211117_0633.py
index 4b09869..d9295bd 100644
--- a/sigi/apps/eventos/migrations/0011_auto_20211117_0633.py
+++ b/sigi/apps/eventos/migrations/0011_auto_20211117_0633.py
@@ -7,18 +7,26 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0010_modulo'),
+ ("eventos", "0010_modulo"),
]
operations = [
migrations.AlterModelOptions(
- name='modulo',
- options={'ordering': ('inicio',), 'verbose_name': 'M\xf3dulo do evento', 'verbose_name_plural': 'M\xf3dulos do evento'},
+ name="modulo",
+ options={
+ "ordering": ("inicio",),
+ "verbose_name": "M\xf3dulo do evento",
+ "verbose_name_plural": "M\xf3dulos do evento",
+ },
),
migrations.AddField(
- model_name='evento',
- name='total_participantes',
- field=models.PositiveIntegerField(default=0, help_text='Se informar quantidade de participantes na aba de convites, este campo ser\xe1 ajustado com a somat\xf3ria dos participantes naquela aba.', verbose_name='Total de participantes'),
+ model_name="evento",
+ name="total_participantes",
+ field=models.PositiveIntegerField(
+ default=0,
+ help_text="Se informar quantidade de participantes na aba de convites, este campo ser\xe1 ajustado com a somat\xf3ria dos participantes naquela aba.",
+ verbose_name="Total de participantes",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0012_auto_20211117_0657.py b/sigi/apps/eventos/migrations/0012_auto_20211117_0657.py
index 662c4d1..a52f1d8 100644
--- a/sigi/apps/eventos/migrations/0012_auto_20211117_0657.py
+++ b/sigi/apps/eventos/migrations/0012_auto_20211117_0657.py
@@ -4,23 +4,25 @@ from __future__ import unicode_literals
from django.db import models, migrations
from django.db.models import Sum
+
def atualiza_participantes(apps, schema_editor):
- if schema_editor.connection.alias != 'default':
+ if schema_editor.connection.alias != "default":
return
- Evento = apps.get_model('eventos', 'Evento')
+ Evento = apps.get_model("eventos", "Evento")
for e in Evento.objects.all():
- total = e.convite_set.aggregate(total=Sum('qtde_participantes'))
- total = total['total']
+ total = e.convite_set.aggregate(total=Sum("qtde_participantes"))
+ total = total["total"]
if (total is not None) or (total > 0):
e.total_participantes = total
e.save()
+
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0011_auto_20211117_0633'),
+ ("eventos", "0011_auto_20211117_0633"),
]
operations = [
diff --git a/sigi/apps/eventos/migrations/0013_modelodeclaracao.py b/sigi/apps/eventos/migrations/0013_modelodeclaracao.py
index b3d11d6..8099703 100644
--- a/sigi/apps/eventos/migrations/0013_modelodeclaracao.py
+++ b/sigi/apps/eventos/migrations/0013_modelodeclaracao.py
@@ -8,22 +8,61 @@ import tinymce.models
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0012_auto_20211117_0657'),
+ ("eventos", "0012_auto_20211117_0657"),
]
operations = [
migrations.CreateModel(
- name='ModeloDeclaracao',
+ name="ModeloDeclaracao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=100, verbose_name='Nome do modelo')),
- ('formato', models.CharField(default='A4 portrait', max_length=30, verbose_name='Formato da p\xe1gina', choices=[('A4 portrait', 'A4 retrato'), ('A4 landscape', 'A4 paisagem'), ('letter portrait', 'Carta retrato'), ('letter landscape', 'Carta paisagem')])),
- ('margem', models.PositiveIntegerField(default=4, help_text='Margem da p\xe1gina em cent\xedmetros', verbose_name='Margem')),
- ('texto', tinymce.models.HTMLField(help_text='Use as seguintes marca\xe7\xf5es:{{ casa }} para o nome da Casa Legislativa / \xf3rg\xe3o {{ nome }} para o nome do visitante {{ data }} para a data de emiss\xe3o da declara\xe7\xe3o {{ evento.data_inicio }} para a data/hora do in\xedcio da visita {{ evento.data_termino }} para a data/hora do t\xe9rmino da visita {{ evento.nome }} para o nome do evento {{ evento.descricao }} para a descri\xe7\xe3o do evento ', verbose_name='Texto da declara\xe7\xe3o')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=100, verbose_name="Nome do modelo"
+ ),
+ ),
+ (
+ "formato",
+ models.CharField(
+ default="A4 portrait",
+ max_length=30,
+ verbose_name="Formato da p\xe1gina",
+ choices=[
+ ("A4 portrait", "A4 retrato"),
+ ("A4 landscape", "A4 paisagem"),
+ ("letter portrait", "Carta retrato"),
+ ("letter landscape", "Carta paisagem"),
+ ],
+ ),
+ ),
+ (
+ "margem",
+ models.PositiveIntegerField(
+ default=4,
+ help_text="Margem da p\xe1gina em cent\xedmetros",
+ verbose_name="Margem",
+ ),
+ ),
+ (
+ "texto",
+ tinymce.models.HTMLField(
+ help_text="Use as seguintes marca\xe7\xf5es:{{ casa }} para o nome da Casa Legislativa / \xf3rg\xe3o {{ nome }} para o nome do visitante {{ data }} para a data de emiss\xe3o da declara\xe7\xe3o {{ evento.data_inicio }} para a data/hora do in\xedcio da visita {{ evento.data_termino }} para a data/hora do t\xe9rmino da visita {{ evento.nome }} para o nome do evento {{ evento.descricao }} para a descri\xe7\xe3o do evento ",
+ verbose_name="Texto da declara\xe7\xe3o",
+ ),
+ ),
],
options={
- 'verbose_name': 'modelo de declara\xe7\xe3o',
- 'verbose_name_plural': 'modelos de declara\xe7\xe3o',
+ "verbose_name": "modelo de declara\xe7\xe3o",
+ "verbose_name_plural": "modelos de declara\xe7\xe3o",
},
bases=(models.Model,),
),
diff --git a/sigi/apps/eventos/migrations/0014_auto_20211124_0736.py b/sigi/apps/eventos/migrations/0014_auto_20211124_0736.py
index 8c5619d..6e73b87 100644
--- a/sigi/apps/eventos/migrations/0014_auto_20211124_0736.py
+++ b/sigi/apps/eventos/migrations/0014_auto_20211124_0736.py
@@ -8,14 +8,17 @@ import tinymce.models
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0013_modelodeclaracao'),
+ ("eventos", "0013_modelodeclaracao"),
]
operations = [
migrations.AlterField(
- model_name='modelodeclaracao',
- name='texto',
- field=tinymce.models.HTMLField(help_text='Use as seguintes marca\xe7\xf5es:{{ casa.nome }} para o nome da Casa Legislativa / \xf3rg\xe3o {{ casa.municipio.uf.sigla }} para a sigla da UF da Casa legislativa {{ nome }} para o nome do visitante {{ data }} para a data de emiss\xe3o da declara\xe7\xe3o {{ evento.data_inicio }} para a data/hora do in\xedcio da visita {{ evento.data_termino }} para a data/hora do t\xe9rmino da visita {{ evento.nome }} para o nome do evento {{ evento.descricao }} para a descri\xe7\xe3o do evento ', verbose_name='Texto da declara\xe7\xe3o'),
+ model_name="modelodeclaracao",
+ name="texto",
+ field=tinymce.models.HTMLField(
+ help_text="Use as seguintes marca\xe7\xf5es:{{ casa.nome }} para o nome da Casa Legislativa / \xf3rg\xe3o {{ casa.municipio.uf.sigla }} para a sigla da UF da Casa legislativa {{ nome }} para o nome do visitante {{ data }} para a data de emiss\xe3o da declara\xe7\xe3o {{ evento.data_inicio }} para a data/hora do in\xedcio da visita {{ evento.data_termino }} para a data/hora do t\xe9rmino da visita {{ evento.nome }} para o nome do evento {{ evento.descricao }} para a descri\xe7\xe3o do evento ",
+ verbose_name="Texto da declara\xe7\xe3o",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/eventos/migrations/0015_anexo.py b/sigi/apps/eventos/migrations/0015_anexo.py
index 50b66b3..19a4418 100644
--- a/sigi/apps/eventos/migrations/0015_anexo.py
+++ b/sigi/apps/eventos/migrations/0015_anexo.py
@@ -8,21 +8,52 @@ import datetime
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0014_auto_20211124_0736'),
+ ("eventos", "0014_auto_20211124_0736"),
]
operations = [
migrations.CreateModel(
- name='Anexo',
+ name="Anexo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('arquivo', models.FileField(max_length=500, upload_to='apps/eventos/anexo/arquivo')),
- ('descricao', models.CharField(max_length='70', verbose_name='descri\xe7\xe3o')),
- ('data_pub', models.DateTimeField(default=datetime.datetime.now, verbose_name='data da publica\xe7\xe3o do anexo')),
- ('evento', models.ForeignKey(verbose_name='evento', to='eventos.Evento', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "arquivo",
+ models.FileField(
+ max_length=500, upload_to="apps/eventos/anexo/arquivo"
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length="70", verbose_name="descri\xe7\xe3o"
+ ),
+ ),
+ (
+ "data_pub",
+ models.DateTimeField(
+ default=datetime.datetime.now,
+ verbose_name="data da publica\xe7\xe3o do anexo",
+ ),
+ ),
+ (
+ "evento",
+ models.ForeignKey(
+ verbose_name="evento",
+ to="eventos.Evento",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('-data_pub',),
+ "ordering": ("-data_pub",),
},
bases=(models.Model,),
),
diff --git a/sigi/apps/eventos/migrations/0016_merge.py b/sigi/apps/eventos/migrations/0016_merge.py
index 9c4907c..3e3a37b 100644
--- a/sigi/apps/eventos/migrations/0016_merge.py
+++ b/sigi/apps/eventos/migrations/0016_merge.py
@@ -7,9 +7,8 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0004_auto_20160719_0920'),
- ('eventos', '0015_anexo'),
+ ("eventos", "0004_auto_20160719_0920"),
+ ("eventos", "0015_anexo"),
]
- operations = [
- ]
+ operations = []
diff --git a/sigi/apps/eventos/migrations/0017_alter_anexo_arquivo_alter_anexo_descricao_and_more.py b/sigi/apps/eventos/migrations/0017_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
index 19cd7d7..1c9c6eb 100644
--- a/sigi/apps/eventos/migrations/0017_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
+++ b/sigi/apps/eventos/migrations/0017_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
@@ -7,84 +7,168 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0008_alter_servico_id_alter_servidor_foto_and_more'),
- ('eventos', '0016_merge'),
+ ("servidores", "0008_alter_servico_id_alter_servidor_foto_and_more"),
+ ("eventos", "0016_merge"),
]
operations = [
migrations.AlterField(
- model_name='anexo',
- name='arquivo',
- field=models.FileField(max_length=500, upload_to='apps/eventos/anexo/arquivo'),
+ model_name="anexo",
+ name="arquivo",
+ field=models.FileField(
+ max_length=500, upload_to="apps/eventos/anexo/arquivo"
+ ),
),
migrations.AlterField(
- model_name='anexo',
- name='descricao',
- field=models.CharField(max_length=70, verbose_name='descrição'),
+ model_name="anexo",
+ name="descricao",
+ field=models.CharField(max_length=70, verbose_name="descrição"),
),
migrations.AlterField(
- model_name='anexo',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="anexo",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='convite',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="convite",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='convite',
- name='servidor',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='servidores.servidor', verbose_name='Servidor que convidou'),
+ model_name="convite",
+ name="servidor",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ to="servidores.servidor",
+ verbose_name="Servidor que convidou",
+ ),
),
migrations.AlterField(
- model_name='equipe',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="equipe",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='evento',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="evento",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='evento',
- name='status',
- field=models.CharField(choices=[('P', 'Previsão'), ('A', 'A confirmar'), ('O', 'Confirmado'), ('R', 'Realizado'), ('C', 'Cancelado')], max_length=1, verbose_name='Status'),
+ model_name="evento",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("P", "Previsão"),
+ ("A", "A confirmar"),
+ ("O", "Confirmado"),
+ ("R", "Realizado"),
+ ("C", "Cancelado"),
+ ],
+ max_length=1,
+ verbose_name="Status",
+ ),
),
migrations.AlterField(
- model_name='funcao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="funcao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='modelodeclaracao',
- name='formato',
- field=models.CharField(choices=[('A4 portrait', 'A4 retrato'), ('A4 landscape', 'A4 paisagem'), ('letter portrait', 'Carta retrato'), ('letter landscape', 'Carta paisagem')], default='A4 portrait', max_length=30, verbose_name='Formato da página'),
+ model_name="modelodeclaracao",
+ name="formato",
+ field=models.CharField(
+ choices=[
+ ("A4 portrait", "A4 retrato"),
+ ("A4 landscape", "A4 paisagem"),
+ ("letter portrait", "Carta retrato"),
+ ("letter landscape", "Carta paisagem"),
+ ],
+ default="A4 portrait",
+ max_length=30,
+ verbose_name="Formato da página",
+ ),
),
migrations.AlterField(
- model_name='modelodeclaracao',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="modelodeclaracao",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='modulo',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="modulo",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='modulo',
- name='tipo',
- field=models.CharField(choices=[('A', 'Aula'), ('P', 'Palestra'), ('R', 'Apresentação')], max_length=1, verbose_name='Tipo'),
+ model_name="modulo",
+ name="tipo",
+ field=models.CharField(
+ choices=[
+ ("A", "Aula"),
+ ("P", "Palestra"),
+ ("R", "Apresentação"),
+ ],
+ max_length=1,
+ verbose_name="Tipo",
+ ),
),
migrations.AlterField(
- model_name='tipoevento',
- name='categoria',
- field=models.CharField(choices=[('C', 'Curso'), ('E', 'Encontro'), ('O', 'Oficina'), ('S', 'Seminário'), ('V', 'Visita')], max_length=1, verbose_name='Categoaria'),
+ model_name="tipoevento",
+ name="categoria",
+ field=models.CharField(
+ choices=[
+ ("C", "Curso"),
+ ("E", "Encontro"),
+ ("O", "Oficina"),
+ ("S", "Seminário"),
+ ("V", "Visita"),
+ ],
+ max_length=1,
+ verbose_name="Categoaria",
+ ),
),
migrations.AlterField(
- model_name='tipoevento',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="tipoevento",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
]
diff --git a/sigi/apps/eventos/migrations/0018_evento_data_pedido_evento_num_processo_and_more.py b/sigi/apps/eventos/migrations/0018_evento_data_pedido_evento_num_processo_and_more.py
index 8a5751b..da5f690 100644
--- a/sigi/apps/eventos/migrations/0018_evento_data_pedido_evento_num_processo_and_more.py
+++ b/sigi/apps/eventos/migrations/0018_evento_data_pedido_evento_num_processo_and_more.py
@@ -6,28 +6,52 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0017_alter_anexo_arquivo_alter_anexo_descricao_and_more'),
+ ("eventos", "0017_alter_anexo_arquivo_alter_anexo_descricao_and_more"),
]
operations = [
migrations.AddField(
- model_name='evento',
- name='data_pedido',
- field=models.DateField(blank=True, help_text='Data em que o pedido do Gabinete chegou à COPERI', null=True, verbose_name='Data do pedido'),
+ model_name="evento",
+ name="data_pedido",
+ field=models.DateField(
+ blank=True,
+ help_text="Data em que o pedido do Gabinete chegou à COPERI",
+ null=True,
+ verbose_name="Data do pedido",
+ ),
),
migrations.AddField(
- model_name='evento',
- name='num_processo',
- field=models.CharField(blank=True, help_text='Formato:XXXXX.XXXXXX/XXXX-XX ', max_length=20, verbose_name='número do processo SIGAD'),
+ model_name="evento",
+ name="num_processo",
+ field=models.CharField(
+ blank=True,
+ help_text="Formato:XXXXX.XXXXXX/XXXX-XX ",
+ max_length=20,
+ verbose_name="número do processo SIGAD",
+ ),
),
migrations.AddField(
- model_name='evento',
- name='observacao',
- field=models.TextField(blank=True, verbose_name='Observações e anotações'),
+ model_name="evento",
+ name="observacao",
+ field=models.TextField(
+ blank=True, verbose_name="Observações e anotações"
+ ),
),
migrations.AlterField(
- model_name='evento',
- name='status',
- field=models.CharField(choices=[('E', 'Em planejamento'), ('G', 'Aguardando abertura SIGAD'), ('P', 'Previsão'), ('A', 'A confirmar'), ('O', 'Confirmado'), ('R', 'Realizado'), ('C', 'Cancelado')], max_length=1, verbose_name='Status'),
+ model_name="evento",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("E", "Em planejamento"),
+ ("G", "Aguardando abertura SIGAD"),
+ ("P", "Previsão"),
+ ("A", "A confirmar"),
+ ("O", "Confirmado"),
+ ("R", "Realizado"),
+ ("C", "Cancelado"),
+ ],
+ max_length=1,
+ verbose_name="Status",
+ ),
),
]
diff --git a/sigi/apps/eventos/migrations/0019_alter_evento_status.py b/sigi/apps/eventos/migrations/0019_alter_evento_status.py
index dd870eb..9eb20ab 100644
--- a/sigi/apps/eventos/migrations/0019_alter_evento_status.py
+++ b/sigi/apps/eventos/migrations/0019_alter_evento_status.py
@@ -6,13 +6,26 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('eventos', '0018_evento_data_pedido_evento_num_processo_and_more'),
+ ("eventos", "0018_evento_data_pedido_evento_num_processo_and_more"),
]
operations = [
migrations.AlterField(
- model_name='evento',
- name='status',
- field=models.CharField(choices=[('E', 'Em planejamento'), ('G', 'Aguardando abertura SIGAD'), ('P', 'Previsão'), ('A', 'A confirmar'), ('O', 'Confirmado'), ('R', 'Realizado'), ('C', 'Cancelado'), ('Q', 'Arquivado')], max_length=1, verbose_name='Status'),
+ model_name="evento",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("E", "Em planejamento"),
+ ("G", "Aguardando abertura SIGAD"),
+ ("P", "Previsão"),
+ ("A", "A confirmar"),
+ ("O", "Confirmado"),
+ ("R", "Realizado"),
+ ("C", "Cancelado"),
+ ("Q", "Arquivado"),
+ ],
+ max_length=1,
+ verbose_name="Status",
+ ),
),
]
diff --git a/sigi/apps/eventos/models.py b/sigi/apps/eventos/models.py
index 85902d1..2962f82 100644
--- a/sigi/apps/eventos/models.py
+++ b/sigi/apps/eventos/models.py
@@ -12,36 +12,37 @@ from tinymce.models import HTMLField
class TipoEvento(models.Model):
CATEGORIA_CHOICES = (
- ('C', _('Curso')),
- ('E', _('Encontro')),
- ('O', _('Oficina')),
- ('S', _('Seminário')),
- ('V', _('Visita')),
-
+ ("C", _("Curso")),
+ ("E", _("Encontro")),
+ ("O", _("Oficina")),
+ ("S", _("Seminário")),
+ ("V", _("Visita")),
)
nome = models.CharField(_("Nome"), max_length=100)
categoria = models.CharField(
- _('Categoaria'),
- max_length=1,
- choices=CATEGORIA_CHOICES
+ _("Categoaria"), max_length=1, choices=CATEGORIA_CHOICES
)
+
class Meta:
ordering = ("nome",)
- verbose_name, verbose_name_plural = _("Tipo de evento"), _("Tipos de evento")
+ verbose_name, verbose_name_plural = _("Tipo de evento"), _(
+ "Tipos de evento"
+ )
def __str__(self):
return self.nome
+
class Evento(models.Model):
STATUS_CHOICES = (
- ('E', _(u"Em planejamento")),
- ('G', _(u"Aguardando abertura SIGAD")),
- ('P', _("Previsão")),
- ('A', _("A confirmar")),
- ('O', _("Confirmado")),
- ('R', _("Realizado")),
- ('C', _("Cancelado")),
- ('Q', _("Arquivado")),
+ ("E", _("Em planejamento")),
+ ("G", _("Aguardando abertura SIGAD")),
+ ("P", _("Previsão")),
+ ("A", _("A confirmar")),
+ ("O", _("Confirmado")),
+ ("R", _("Realizado")),
+ ("C", _("Cancelado")),
+ ("Q", _("Arquivado")),
)
tipo_evento = models.ForeignKey(
@@ -53,55 +54,51 @@ class Evento(models.Model):
virtual = models.BooleanField(_("Virtual"), default=False)
solicitante = models.CharField(_("Solicitante"), max_length=100)
num_processo = models.CharField(
- _(u'número do processo SIGAD'),
+ _("número do processo SIGAD"),
max_length=20,
blank=True,
- help_text=_(u'Formato:XXXXX.XXXXXX/XXXX-XX ')
+ help_text=_("Formato:XXXXX.XXXXXX/XXXX-XX "),
)
data_pedido = models.DateField(
- _(u"Data do pedido"),
+ _("Data do pedido"),
null=True,
blank=True,
- help_text=_(u"Data em que o pedido do Gabinete chegou à COPERI")
+ help_text=_("Data em que o pedido do Gabinete chegou à COPERI"),
)
data_inicio = models.DateTimeField(
- _("Data/hora do Início"),
- null=True,
- blank=True
+ _("Data/hora do Início"), null=True, blank=True
)
data_termino = models.DateTimeField(
- _("Data/hora do Termino"),
- null=True,
- blank=True
- )
- carga_horaria = models.PositiveIntegerField(
- _("carga horária"),
- default=0
+ _("Data/hora do Termino"), null=True, blank=True
)
+ carga_horaria = models.PositiveIntegerField(_("carga horária"), default=0)
casa_anfitria = models.ForeignKey(
Orgao,
on_delete=models.PROTECT,
verbose_name=_("Casa anfitriã"),
blank=True,
- null=True
- )
- municipio = models.ForeignKey(
- Municipio,
- on_delete=models.PROTECT
+ null=True,
)
+ municipio = models.ForeignKey(Municipio, on_delete=models.PROTECT)
local = models.TextField(_("Local do evento"), blank=True)
- observacao = models.TextField(_(u"Observações e anotações"), blank=True)
+ observacao = models.TextField(_("Observações e anotações"), blank=True)
publico_alvo = models.TextField(_("Público alvo"), blank=True)
total_participantes = models.PositiveIntegerField(
_("Total de participantes"),
default=0,
- help_text=_("Se informar quantidade de participantes na aba de "
- "convites, este campo será ajustado com a somatória "
- "dos participantes naquela aba.")
+ help_text=_(
+ "Se informar quantidade de participantes na aba de "
+ "convites, este campo será ajustado com a somatória "
+ "dos participantes naquela aba."
+ ),
)
status = models.CharField(_("Status"), max_length=1, choices=STATUS_CHOICES)
- data_cancelamento = models.DateField(_("Data de cancelamento"), blank=True, null=True)
- motivo_cancelamento = models.TextField(_("Motivo do cancelamento"), blank=True)
+ data_cancelamento = models.DateField(
+ _("Data de cancelamento"), blank=True, null=True
+ )
+ motivo_cancelamento = models.TextField(
+ _("Motivo do cancelamento"), blank=True
+ )
class Meta:
ordering = ("-data_inicio",)
@@ -114,32 +111,37 @@ class Evento(models.Model):
)
def get_sigad_url(self):
- m = re.match('(?P00100|00200)\.(?P\d{6})/(?P'
- '\d{4})-\d{2}', self.num_processo)
+ m = re.match(
+ "(?P00100|00200)\.(?P\d{6})/(?P"
+ "\d{4})-\d{2}",
+ self.num_processo,
+ )
if m:
- return ('{processo} ').format(
- processo=self.num_processo,**m.groupdict()
- )
+ return (
+ '{processo} '
+ ).format(processo=self.num_processo, **m.groupdict())
return self.num_processo
def save(self, *args, **kwargs):
- if self.status != 'C':
+ if self.status != "C":
self.data_cancelamento = None
self.motivo_cancelamento = ""
if self.data_inicio > self.data_termino:
- raise ValidationError(_("Data de término deve ser posterior à "
- "data de início"))
- total = self.convite_set.aggregate(total=Sum('qtde_participantes'))
- total = total['total']
+ raise ValidationError(
+ _("Data de término deve ser posterior à " "data de início")
+ )
+ total = self.convite_set.aggregate(total=Sum("qtde_participantes"))
+ total = total["total"]
if total and total > 0:
self.total_participantes = total
return super(Evento, self).save(*args, **kwargs)
+
class Funcao(models.Model):
nome = models.CharField(_("Função na equipe de evento"), max_length=100)
descricao = models.TextField(_("Descrição da função"))
@@ -151,88 +153,79 @@ class Funcao(models.Model):
def __str__(self):
return self.nome
+
class Equipe(models.Model):
- evento = models.ForeignKey(
- Evento,
- on_delete=models.CASCADE
- )
+ evento = models.ForeignKey(Evento, on_delete=models.CASCADE)
membro = models.ForeignKey(
- Servidor,
- on_delete=models.PROTECT,
- related_name="equipe_evento"
+ Servidor, on_delete=models.PROTECT, related_name="equipe_evento"
)
funcao = models.ForeignKey(
- Funcao,
- on_delete=models.PROTECT,
- verbose_name=_("Função na equipe")
+ Funcao, on_delete=models.PROTECT, verbose_name=_("Função na equipe")
)
observacoes = models.TextField(_("Observações"), blank=True)
class Meta:
- ordering = ('evento', 'funcao', 'membro',)
- verbose_name, verbose_name_plural = _("Membro da equipe"), _("Membros da equipe")
+ ordering = (
+ "evento",
+ "funcao",
+ "membro",
+ )
+ verbose_name, verbose_name_plural = _("Membro da equipe"), _(
+ "Membros da equipe"
+ )
def __str__(self):
return _(f"{self.membro} ({self.funcao})")
+
class Convite(models.Model):
- evento = models.ForeignKey(
- Evento,
- on_delete=models.CASCADE
- )
+ evento = models.ForeignKey(Evento, on_delete=models.CASCADE)
casa = models.ForeignKey(
- Orgao,
- on_delete=models.PROTECT,
- verbose_name=_("Casa convidada")
+ Orgao, on_delete=models.PROTECT, verbose_name=_("Casa convidada")
)
servidor = models.ForeignKey(
Servidor,
on_delete=models.PROTECT,
- verbose_name=_("Servidor que convidou")
+ verbose_name=_("Servidor que convidou"),
)
data_convite = models.DateField(_("Data do convite"))
aceite = models.BooleanField(_("Aceitou o convite"), default=False)
participou = models.BooleanField(_("Participou do evento"), default=False)
qtde_participantes = models.PositiveIntegerField(
- _("número de participantes"),
- default=0
+ _("número de participantes"), default=0
)
nomes_participantes = models.TextField(
_("nome dos participantes"),
blank=True,
- help_text=_("Favor colocar um participante por linha")
+ help_text=_("Favor colocar um participante por linha"),
)
class Meta:
- ordering = ('evento', 'casa', '-data_convite')
- unique_together = ('evento', 'casa')
+ ordering = ("evento", "casa", "-data_convite")
+ unique_together = ("evento", "casa")
verbose_name = _("Casa convidada")
verbose_name_plural = _("Casas convidadas")
+
class Modulo(models.Model):
TIPO_CHOICES = (
- ('A', _('Aula')),
- ('P', _('Palestra')),
- ('R', _('Apresentação')),
+ ("A", _("Aula")),
+ ("P", _("Palestra")),
+ ("R", _("Apresentação")),
+ )
+ evento = models.ForeignKey(
+ Evento, verbose_name=_("Evento"), on_delete=models.CASCADE
)
- evento = models.ForeignKey(Evento, verbose_name=_("Evento"), on_delete=models.CASCADE)
nome = models.CharField(_("Nome"), max_length=100)
descricao = models.TextField(_("Descrição do módulo"))
- tipo = models.CharField(_('Tipo'), max_length=1, choices=TIPO_CHOICES)
+ tipo = models.CharField(_("Tipo"), max_length=1, choices=TIPO_CHOICES)
inicio = models.DateTimeField(
- _("Data/hora de início"),
- null=True,
- blank=True
+ _("Data/hora de início"), null=True, blank=True
)
termino = models.DateTimeField(
- _("Data/hora de término"),
- null=True,
- blank=True
- )
- carga_horaria = models.PositiveIntegerField(
- _("carga horária"),
- default=0
+ _("Data/hora de término"), null=True, blank=True
)
+ carga_horaria = models.PositiveIntegerField(_("carga horária"), default=0)
apresentador = models.ForeignKey(
Servidor,
on_delete=models.PROTECT,
@@ -248,55 +241,58 @@ class Modulo(models.Model):
null=True,
blank=True,
verbose_name=_("Monitor"),
- help_text=_("Monitor, mediador, auxiliar, etc.")
+ help_text=_("Monitor, mediador, auxiliar, etc."),
)
qtde_participantes = models.PositiveIntegerField(
_("número de participantes"),
default=0,
- help_text=_("Deixar Zero significa que todos os participantes "
- "do evento participaram do módulo"),
+ help_text=_(
+ "Deixar Zero significa que todos os participantes "
+ "do evento participaram do módulo"
+ ),
)
class Meta:
- ordering = ('inicio',)
+ ordering = ("inicio",)
verbose_name = _("Módulo do evento")
verbose_name_plural = _("Módulos do evento")
def __str__(self):
return _(f"{self.nome} ({self.get_tipo_display()})")
+
class ModeloDeclaracao(models.Model):
FORMATO_CHOICES = (
- ('A4 portrait', _("A4 retrato")),
- ('A4 landscape', _("A4 paisagem")),
- ('letter portrait', _("Carta retrato")),
- ('letter landscape', _("Carta paisagem"))
+ ("A4 portrait", _("A4 retrato")),
+ ("A4 landscape", _("A4 paisagem")),
+ ("letter portrait", _("Carta retrato")),
+ ("letter landscape", _("Carta paisagem")),
)
nome = models.CharField(_("Nome do modelo"), max_length=100)
formato = models.CharField(
_("Formato da página"),
max_length=30,
choices=FORMATO_CHOICES,
- default=FORMATO_CHOICES[0][0]
+ default=FORMATO_CHOICES[0][0],
)
margem = models.PositiveIntegerField(
- _("Margem"),
- help_text=_("Margem da página em centímetros"),
- default=4
+ _("Margem"), help_text=_("Margem da página em centímetros"), default=4
)
texto = HTMLField(
_("Texto da declaração"),
- help_text=_("Use as seguintes marcações:{{ casa.nome }} para o"
- " nome da Casa Legislativa / órgão "
- "{{ casa.municipio.uf.sigla }} para a sigla da UF da "
- "Casa legislativa {{ nome }} "
- "para o nome do visitante {{ data }} para a data "
- "de emissão da declaração {{ evento.data_inicio }}"
- " para a data/hora do início da visita "
- "{{ evento.data_termino }} para a data/hora do "
- "término da visita {{ evento.nome }} para o nome "
- "do evento {{ evento.descricao }} para a descrição"
- " do evento ")
+ help_text=_(
+ "Use as seguintes marcações:{{ casa.nome }} para o"
+ " nome da Casa Legislativa / órgão "
+ "{{ casa.municipio.uf.sigla }} para a sigla da UF da "
+ "Casa legislativa {{ nome }} "
+ "para o nome do visitante {{ data }} para a data "
+ "de emissão da declaração {{ evento.data_inicio }}"
+ " para a data/hora do início da visita "
+ "{{ evento.data_termino }} para a data/hora do "
+ "término da visita {{ evento.nome }} para o nome "
+ "do evento {{ evento.descricao }} para a descrição"
+ " do evento "
+ ),
)
class Meta:
@@ -306,22 +302,22 @@ class ModeloDeclaracao(models.Model):
def __str__(self):
return _(f"{self.nome} ({self.get_formato_display()})")
+
class Anexo(models.Model):
evento = models.ForeignKey(
- Evento,
- on_delete=models.CASCADE,
- verbose_name=_('evento')
+ Evento, on_delete=models.CASCADE, verbose_name=_("evento")
)
# caminho no sistema para o documento anexo
- arquivo = models.FileField(upload_to='apps/eventos/anexo/arquivo', max_length=500)
- descricao = models.CharField(_('descrição'), max_length=70)
+ arquivo = models.FileField(
+ upload_to="apps/eventos/anexo/arquivo", max_length=500
+ )
+ descricao = models.CharField(_("descrição"), max_length=70)
data_pub = models.DateTimeField(
- _('data da publicação do anexo'),
- default=datetime.now
+ _("data da publicação do anexo"), default=datetime.now
)
class Meta:
- ordering = ('-data_pub',)
+ ordering = ("-data_pub",)
def __str__(self):
return _(f"{self.descricao} publicado em {self.data_pub}")
diff --git a/sigi/apps/eventos/urls.py b/sigi/apps/eventos/urls.py
index 433daa5..65054ee 100644
--- a/sigi/apps/eventos/urls.py
+++ b/sigi/apps/eventos/urls.py
@@ -2,9 +2,12 @@ from django.urls import path, include
from sigi.apps.eventos import views
urlpatterns = [
- path('calendario/', views.calendario, name='eventos-calendario'),
- path('evento//declaracao/', views.declaracao,
- name='evento-declaracao'),
+ path("calendario/", views.calendario, name="eventos-calendario"),
+ path(
+ "evento//declaracao/",
+ views.declaracao,
+ name="evento-declaracao",
+ ),
]
# from django.conf.urls import patterns, url
diff --git a/sigi/apps/eventos/views.py b/sigi/apps/eventos/views.py
index d31e2b9..5bc7a38 100644
--- a/sigi/apps/eventos/views.py
+++ b/sigi/apps/eventos/views.py
@@ -13,38 +13,37 @@ from sigi.apps.eventos.models import Evento, Equipe, Convite, Modulo
from sigi.apps.eventos.forms import SelecionaModeloForm
from sigi.apps.servidores.models import Servidor
+
@login_required
def calendario(request):
- mes_pesquisa = int(request.GET.get('mes', datetime.date.today().month))
- ano_pesquisa = int(request.GET.get('ano', datetime.date.today().year))
- formato = request.GET.get('fmt', 'html')
+ mes_pesquisa = int(request.GET.get("mes", datetime.date.today().month))
+ ano_pesquisa = int(request.GET.get("ano", datetime.date.today().year))
+ formato = request.GET.get("fmt", "html")
meses = {}
- lang = to_locale(get_language())+'.UTF-8'
+ lang = to_locale(get_language()) + ".UTF-8"
locale.setlocale(locale.LC_ALL, lang)
- for ano, mes in Evento.objects.values_list(
- 'data_inicio__year', 'data_inicio__month').order_by(
- 'data_inicio__year', 'data_inicio__month').distinct(
- 'data_inicio__year', 'data_inicio__month'):
+ for ano, mes in (
+ Evento.objects.values_list("data_inicio__year", "data_inicio__month")
+ .order_by("data_inicio__year", "data_inicio__month")
+ .distinct("data_inicio__year", "data_inicio__month")
+ ):
if ano in meses:
meses[ano][mes] = calendar.month_name[mes]
else:
meses[ano] = {mes: calendar.month_name[mes]}
context = {
- 'ano_pesquisa': ano_pesquisa,
- 'mes_pesquisa': mes_pesquisa,
- 'meses': meses,
- 'eventos': Evento.objects.filter(
- data_inicio__year=ano_pesquisa,
- data_inicio__month=mes_pesquisa
- )
+ "ano_pesquisa": ano_pesquisa,
+ "mes_pesquisa": mes_pesquisa,
+ "meses": meses,
+ "eventos": Evento.objects.filter(
+ data_inicio__year=ano_pesquisa, data_inicio__month=mes_pesquisa
+ ),
}
- return render(request, 'eventos/calendario.html', context)
-
-
+ return render(request, "eventos/calendario.html", context)
# @login_required
@@ -405,42 +404,52 @@ def calendario(request):
# return response
+
@login_required
def declaracao(request, id):
- if request.method == 'POST':
+ if request.method == "POST":
form = SelecionaModeloForm(request.POST)
if form.is_valid():
evento = get_object_or_404(Evento, id=id)
- modelo = form.cleaned_data['modelo']
+ modelo = form.cleaned_data["modelo"]
template_string = (
"""
{% extends "eventos/declaracao_pdf.html" %}
- {% block text_body %}""" +
- modelo.texto + """
+ {% block text_body %}"""
+ + modelo.texto
+ + """
{% endblock %}
"""
)
- context = Context({
- 'pagesize': modelo.formato,
- 'pagemargin': modelo.margem,
- 'evento': evento,
- 'data': datetime.date.today(),
- })
+ context = Context(
+ {
+ "pagesize": modelo.formato,
+ "pagemargin": modelo.margem,
+ "evento": evento,
+ "data": datetime.date.today(),
+ }
+ )
string = Template(template_string).render(context)
# return HttpResponse(string)
- response = HttpResponse(headers={
- 'Content-Type': "application/pdf",
- 'Content-Disposition': 'attachment; filename="declaração.pdf"'
- })
- pdf = HTML(string=string, url_fetcher=django_url_fetcher,
- encoding="utf-8", base_url=request.build_absolute_uri('/'))
+ response = HttpResponse(
+ headers={
+ "Content-Type": "application/pdf",
+ "Content-Disposition": 'attachment; filename="declaração.pdf"',
+ }
+ )
+ pdf = HTML(
+ string=string,
+ url_fetcher=django_url_fetcher,
+ encoding="utf-8",
+ base_url=request.build_absolute_uri("/"),
+ )
pdf.write_pdf(target=response)
return response
else:
form = SelecionaModeloForm()
context = site.each_context(request)
- context['form'] = form
- context['evento_id'] = id
+ context["form"] = form
+ context["evento_id"] = id
- return render(request, 'eventos/seleciona_modelo.html', context)
\ No newline at end of file
+ return render(request, "eventos/seleciona_modelo.html", context)
diff --git a/sigi/apps/financeiro/admin.py b/sigi/apps/financeiro/admin.py
index a090c66..7ab09f8 100644
--- a/sigi/apps/financeiro/admin.py
+++ b/sigi/apps/financeiro/admin.py
@@ -6,9 +6,22 @@ from sigi.apps.utils.base_admin import BaseModelAdmin
class DesembolsoAdmin(BaseModelAdmin):
- list_display = ('projeto', 'descricao', 'data', 'valor_reais', 'valor_dolar',)
- fields = ('projeto', 'descricao', 'data', 'valor_reais', 'valor_dolar', )
- list_filter = ('projeto',)
- date_hierarchy = 'data'
+ list_display = (
+ "projeto",
+ "descricao",
+ "data",
+ "valor_reais",
+ "valor_dolar",
+ )
+ fields = (
+ "projeto",
+ "descricao",
+ "data",
+ "valor_reais",
+ "valor_dolar",
+ )
+ list_filter = ("projeto",)
+ date_hierarchy = "data"
+
admin.site.register(Desembolso, DesembolsoAdmin)
diff --git a/sigi/apps/financeiro/migrations/0001_initial.py b/sigi/apps/financeiro/migrations/0001_initial.py
index a79e5d2..4c77017 100644
--- a/sigi/apps/financeiro/migrations/0001_initial.py
+++ b/sigi/apps/financeiro/migrations/0001_initial.py
@@ -7,23 +7,56 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('convenios', '0001_initial'),
+ ("convenios", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Desembolso',
+ name="Desembolso",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('descricao', models.CharField(max_length=100, verbose_name='Descri\xe7\xe3o da despesa')),
- ('data', models.DateField(verbose_name='Data do desembolso')),
- ('valor_reais', models.DecimalField(verbose_name='Valor em R$', max_digits=18, decimal_places=2)),
- ('valor_dolar', models.DecimalField(verbose_name='Valor em US$', max_digits=18, decimal_places=2)),
- ('projeto', models.ForeignKey(verbose_name='Projeto', to='convenios.Projeto')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length=100,
+ verbose_name="Descri\xe7\xe3o da despesa",
+ ),
+ ),
+ ("data", models.DateField(verbose_name="Data do desembolso")),
+ (
+ "valor_reais",
+ models.DecimalField(
+ verbose_name="Valor em R$",
+ max_digits=18,
+ decimal_places=2,
+ ),
+ ),
+ (
+ "valor_dolar",
+ models.DecimalField(
+ verbose_name="Valor em US$",
+ max_digits=18,
+ decimal_places=2,
+ ),
+ ),
+ (
+ "projeto",
+ models.ForeignKey(
+ verbose_name="Projeto", to="convenios.Projeto"
+ ),
+ ),
],
options={
- 'verbose_name': 'Desembolso',
- 'verbose_name_plural': 'Desembolsos',
+ "verbose_name": "Desembolso",
+ "verbose_name_plural": "Desembolsos",
},
bases=(models.Model,),
),
diff --git a/sigi/apps/financeiro/models.py b/sigi/apps/financeiro/models.py
index bf73b9c..884bd59 100644
--- a/sigi/apps/financeiro/models.py
+++ b/sigi/apps/financeiro/models.py
@@ -7,18 +7,20 @@ from sigi.apps.convenios.models import Projeto
class Desembolso(models.Model):
projeto = models.ForeignKey(
- Projeto,
- on_delete=models.CASCADE,
- verbose_name=_('Projeto')
+ Projeto, on_delete=models.CASCADE, verbose_name=_("Projeto")
+ )
+ descricao = models.CharField(_("Descrição da despesa"), max_length=100)
+ data = models.DateField(_("Data do desembolso"))
+ valor_reais = models.DecimalField(
+ _("Valor em R$"), max_digits=18, decimal_places=2
+ )
+ valor_dolar = models.DecimalField(
+ _("Valor em US$"), max_digits=18, decimal_places=2
)
- descricao = models.CharField(_('Descrição da despesa'), max_length=100)
- data = models.DateField(_('Data do desembolso'))
- valor_reais = models.DecimalField(_('Valor em R$'), max_digits=18, decimal_places=2)
- valor_dolar = models.DecimalField(_('Valor em US$'), max_digits=18, decimal_places=2)
class Meta:
- verbose_name = _('Desembolso')
- verbose_name_plural = _('Desembolsos')
+ verbose_name = _("Desembolso")
+ verbose_name_plural = _("Desembolsos")
def __unicode__(self):
return "%s (US$ %s)" % (self.descricao, self.valor_dolar)
diff --git a/sigi/apps/home/templatetags/menus.py b/sigi/apps/home/templatetags/menus.py
index e418c59..0667247 100644
--- a/sigi/apps/home/templatetags/menus.py
+++ b/sigi/apps/home/templatetags/menus.py
@@ -4,9 +4,10 @@ from django.conf import settings
register = template.Library()
-with open(settings.MENU_FILE, 'r') as menu_file:
+with open(settings.MENU_FILE, "r") as menu_file:
menus = yaml.load(menu_file, yaml.FullLoader)
-@register.inclusion_tag('menus/menu.html', takes_context=True)
+
+@register.inclusion_tag("menus/menu.html", takes_context=True)
def show_menu(context, menu_id):
- return {'menu_items': menus[menu_id], 'request': context.request}
+ return {"menu_items": menus[menu_id], "request": context.request}
diff --git a/sigi/apps/home/templatetags/smart_pagination.py b/sigi/apps/home/templatetags/smart_pagination.py
index e4d5142..d6e0487 100644
--- a/sigi/apps/home/templatetags/smart_pagination.py
+++ b/sigi/apps/home/templatetags/smart_pagination.py
@@ -2,34 +2,42 @@ from django import template
register = template.Library()
-@register.inclusion_tag('pagination/paginator.html')
+
+@register.inclusion_tag("pagination/paginator.html")
def smart_paginator(page_obj, querystring=None):
if querystring:
- querystring = '?' + querystring + '&'
+ querystring = "?" + querystring + "&"
else:
- querystring = '?'
+ querystring = "?"
page_range = page_obj.paginator.page_range
mid = len(page_range) // 2
- range = list(set(page_range[:3]) | set(page_range[mid-2:mid+1]) | set(page_range[-3:]) |
- set(page_range[page_obj.number-2:page_obj.number+1]))
+ range = list(
+ set(page_range[:3])
+ | set(page_range[mid - 2 : mid + 1])
+ | set(page_range[-3:])
+ | set(page_range[page_obj.number - 2 : page_obj.number + 1])
+ )
range.sort()
- last = range[0]-1
+ last = range[0] - 1
page_range = []
for p in range:
- if p-1 != last:
- if p-2 == last:
- page_range.append(p-1)
+ if p - 1 != last:
+ if p - 2 == last:
+ page_range.append(p - 1)
else:
page_range.append(None)
page_range.append(p)
last = p
- return dict(page_obj=page_obj, querystring=querystring, page_range=page_range)
+ return dict(
+ page_obj=page_obj, querystring=querystring, page_range=page_range
+ )
+
-@register.inclusion_tag('menus/menu_item.html')
+@register.inclusion_tag("menus/menu_item.html")
def show_menu_item(menu_item, base_url):
return dict(menu_item=menu_item, base_url=base_url)
diff --git a/sigi/apps/home/urls.py b/sigi/apps/home/urls.py
index 234371a..c1fb0c3 100644
--- a/sigi/apps/home/urls.py
+++ b/sigi/apps/home/urls.py
@@ -2,16 +2,32 @@ from django.urls import path
from sigi.apps.home import views
urlpatterns = [
- path('',views.openmap, name='openmap'),
- path('openmapdata/', views.openmapdata, name='openmapdata'),
- path('openmapdetail//', views.openmapdetail, name='openmapdetail'),
- path('openmapsearch/', views.openmapsearch, name='openmapsearch'),
- path('home/resumoseit/', views.resumo_seit, name="home_resumoseit"),
- path('home/chartseit/', views.chart_seit, name="home_chartseit"),
- path('home/chartperformance/', views.chart_performance, name="home_chartperformance"),
- path('home/chartcarteira/', views.chart_carteira, name="home_chartcarteira"),
- path('home/resumoconvenios/', views.resumo_convenios, name="home_resumoconvenios"),
- path('home/report/semconvenio/', views.report_sem_convenio, name="home_reportsemconvenio"),
+ path("", views.openmap, name="openmap"),
+ path("openmapdata/", views.openmapdata, name="openmapdata"),
+ path(
+ "openmapdetail//", views.openmapdetail, name="openmapdetail"
+ ),
+ path("openmapsearch/", views.openmapsearch, name="openmapsearch"),
+ path("home/resumoseit/", views.resumo_seit, name="home_resumoseit"),
+ path("home/chartseit/", views.chart_seit, name="home_chartseit"),
+ path(
+ "home/chartperformance/",
+ views.chart_performance,
+ name="home_chartperformance",
+ ),
+ path(
+ "home/chartcarteira/", views.chart_carteira, name="home_chartcarteira"
+ ),
+ path(
+ "home/resumoconvenios/",
+ views.resumo_convenios,
+ name="home_resumoconvenios",
+ ),
+ path(
+ "home/report/semconvenio/",
+ views.report_sem_convenio,
+ name="home_reportsemconvenio",
+ ),
]
# from django.conf.urls import patterns, url
diff --git a/sigi/apps/home/views.py b/sigi/apps/home/views.py
index 67fd6f4..c5d8265 100644
--- a/sigi/apps/home/views.py
+++ b/sigi/apps/home/views.py
@@ -26,89 +26,118 @@ from sigi.apps.utils import to_ascii
# from sigi.apps.servidores.models import Servidor
# from django.http.response import JsonResponse, HttpResponse
from django.urls import reverse
+
# from sigi.shortcuts import render_to_pdf
# import csv
+
def openmap(request):
- reptype = request.GET.get('reptype', None)
+ reptype = request.GET.get("reptype", None)
context = site.each_context(request)
if reptype is None:
- context['tipos_orgao'] = TipoOrgao.objects.filter(legislativo=True)
- context['tipos_servico'] = TipoServico.objects.all()
- context['tipos_convenio'] = Projeto.objects.all()
- context['gerentes'] = Servidor.objects.exclude(casas_que_gerencia=None)
- context['regioes'] = [(s, n, UnidadeFederativa.objects.filter(regiao=s))
- for s, n in UnidadeFederativa.REGIAO_CHOICES]
- return render(request, 'home/openmap.html', context)
+ context["tipos_orgao"] = TipoOrgao.objects.filter(legislativo=True)
+ context["tipos_servico"] = TipoServico.objects.all()
+ context["tipos_convenio"] = Projeto.objects.all()
+ context["gerentes"] = Servidor.objects.exclude(casas_que_gerencia=None)
+ context["regioes"] = [
+ (s, n, UnidadeFederativa.objects.filter(regiao=s))
+ for s, n in UnidadeFederativa.REGIAO_CHOICES
+ ]
+ return render(request, "home/openmap.html", context)
else:
if request.user.is_anonymous():
return HttpResponseForbidden()
- tipos_orgao = request.GET.getlist('tipo_orgao', [])
- tipos_servico = request.GET.getlist('tipo_servico', [])
- tipos_convenio = request.GET.getlist('tipo_convenio', [])
- gerentes = request.GET.getlist('gerente', [])
- ufs = request.GET.getlist('uf', [])
+ tipos_orgao = request.GET.getlist("tipo_orgao", [])
+ tipos_servico = request.GET.getlist("tipo_servico", [])
+ tipos_convenio = request.GET.getlist("tipo_convenio", [])
+ gerentes = request.GET.getlist("gerente", [])
+ ufs = request.GET.getlist("uf", [])
casas = openmapdata(request)
- context['tipos_orgao'] = TipoOrgao.objects.filter(legislativo=True,
- sigla__in=tipos_orgao)
- context['tipos_servico'] = TipoServico.objects.filter(
- sigla__in=tipos_servico
- )
- context['tipos_convenio'] = Projeto.objects.filter(
- sigla__in=tipos_convenio)
- context['gerentes'] = Servidor.objects.exclude(
- casas_que_gerencia=None).filter(id__in=gerentes)
- context['ufs'] = UnidadeFederativa.objects.filter(sigla__in=ufs)
- context['casas'] = casas
+ context["tipos_orgao"] = TipoOrgao.objects.filter(
+ legislativo=True, sigla__in=tipos_orgao
+ )
+ context["tipos_servico"] = TipoServico.objects.filter(
+ sigla__in=tipos_servico
+ )
+ context["tipos_convenio"] = Projeto.objects.filter(
+ sigla__in=tipos_convenio
+ )
+ context["gerentes"] = Servidor.objects.exclude(
+ casas_que_gerencia=None
+ ).filter(id__in=gerentes)
+ context["ufs"] = UnidadeFederativa.objects.filter(sigla__in=ufs)
+ context["casas"] = casas
if reptype == "lista":
return WeasyTemplateResponse(
- filename='Lista de Casas atendidas.pdf',
+ filename="Lista de Casas atendidas.pdf",
request=request,
- template='home/lista_casas.html',
+ template="home/lista_casas.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
else:
- fields = ['cnpj', 'nome', 'municipio__uf__nome',
- 'municipio__uf__regiao', 'logradouro', 'bairro',
- 'cep', 'ult_alt_endereco', 'email']
- if reptype in ('exporta_servico', 'exporta'):
- fields.extend(['servico__tipo_servico__nome', 'servico__url',
- 'servico__data_ativacao',
- 'servico__data_desativacao'])
- if reptype in ('exporta_convenio', 'exporta'):
- fields.extend([
- 'convenio__num_convenio',
- 'convenio__num_processo_sf',
- 'convenio__projeto__sigla',
- 'convenio__data_adesao',
- 'convenio__data_termino_vigencia',
- 'convenio__data_retorno_assinatura'
- ])
- if reptype in ('exporta_contato', 'exporta'):
- fields.extend(['funcionario__nome', 'funcionario__setor',
- 'funcionario__email', 'funcionario__nota',
- 'funcionario__redes_sociais',
- 'funcionario__desativado',
- 'funcionario__ult_alteracao'])
+ fields = [
+ "cnpj",
+ "nome",
+ "municipio__uf__nome",
+ "municipio__uf__regiao",
+ "logradouro",
+ "bairro",
+ "cep",
+ "ult_alt_endereco",
+ "email",
+ ]
+ if reptype in ("exporta_servico", "exporta"):
+ fields.extend(
+ [
+ "servico__tipo_servico__nome",
+ "servico__url",
+ "servico__data_ativacao",
+ "servico__data_desativacao",
+ ]
+ )
+ if reptype in ("exporta_convenio", "exporta"):
+ fields.extend(
+ [
+ "convenio__num_convenio",
+ "convenio__num_processo_sf",
+ "convenio__projeto__sigla",
+ "convenio__data_adesao",
+ "convenio__data_termino_vigencia",
+ "convenio__data_retorno_assinatura",
+ ]
+ )
+ if reptype in ("exporta_contato", "exporta"):
+ fields.extend(
+ [
+ "funcionario__nome",
+ "funcionario__setor",
+ "funcionario__email",
+ "funcionario__nota",
+ "funcionario__redes_sociais",
+ "funcionario__desativado",
+ "funcionario__ult_alteracao",
+ ]
+ )
dados = casas.distinct().values(*fields)
- response = HttpResponse(content_type='text/csv')
+ response = HttpResponse(content_type="text/csv")
writer = csv.DictWriter(response, fieldnames=fields)
writer.writeheader()
writer.writerows(dados)
return response
+
def openmapdata(request):
- tipos_orgao = request.GET.getlist('tipo_orgao', None)
- tipos_servico = request.GET.getlist('tipo_servico', None)
- tipos_convenio = request.GET.getlist('tipo_convenio', None)
- ufs = request.GET.getlist('uf', None)
- gerentes = request.GET.getlist('gerente', None)
- reptype = request.GET.get('reptype', None)
+ tipos_orgao = request.GET.getlist("tipo_orgao", None)
+ tipos_servico = request.GET.getlist("tipo_servico", None)
+ tipos_convenio = request.GET.getlist("tipo_convenio", None)
+ ufs = request.GET.getlist("uf", None)
+ gerentes = request.GET.getlist("gerente", None)
+ reptype = request.GET.get("reptype", None)
dados = Orgao.objects.all()
@@ -121,8 +150,10 @@ def openmapdata(request):
if "none" in tipos_servico:
dados = dados.filter(servico=None)
else:
- dados = dados.filter(servico__tipo_servico__sigla__in=tipos_servico,
- servico__data_desativacao=None)
+ dados = dados.filter(
+ servico__tipo_servico__sigla__in=tipos_servico,
+ servico__data_desativacao=None,
+ )
if tipos_convenio:
if "none" in tipos_convenio:
@@ -139,72 +170,77 @@ def openmapdata(request):
else:
dados = dados.filter(gerentes_interlegis__id__in=gerentes)
-
if not reptype:
- dados = dados.order_by('nome', 'id').distinct('nome', 'id')
- dados = dados.values_list("id", "nome", "municipio__latitude",
- "municipio__longitude")
+ dados = dados.order_by("nome", "id").distinct("nome", "id")
+ dados = dados.values_list(
+ "id", "nome", "municipio__latitude", "municipio__longitude"
+ )
return JsonResponse(list(dados), safe=False)
else:
- dados = dados.order_by(
- 'municipio__uf__regiao',
- 'municipio__uf__nome',
- 'nome',
- 'id'
- ).distinct(
- 'municipio__uf__regiao',
- 'municipio__uf__nome',
- 'nome',
- 'id'
- ).prefetch_related(
- 'servico_set',
- 'convenio_set',
- 'municipio__uf',
- 'gerentes_interlegis'
+ dados = (
+ dados.order_by(
+ "municipio__uf__regiao", "municipio__uf__nome", "nome", "id"
+ )
+ .distinct(
+ "municipio__uf__regiao", "municipio__uf__nome", "nome", "id"
+ )
+ .prefetch_related(
+ "servico_set",
+ "convenio_set",
+ "municipio__uf",
+ "gerentes_interlegis",
+ )
)
return dados
+
def openmapdetail(request, orgao_id):
orgao = get_object_or_404(Orgao, id=orgao_id)
- return render(request, "home/openmapdetail.html", {'orgao': orgao})
+ return render(request, "home/openmapdetail.html", {"orgao": orgao})
+
def openmapsearch(request):
- q = request.GET.get('q', '')
+ q = request.GET.get("q", "")
if len(q) < 3:
- return JsonResponse({'result': 'unsearchable'})
+ return JsonResponse({"result": "unsearchable"})
dados = Orgao.objects.filter(
- tipo__legislativo=True,
- search_text__icontains=to_ascii(q)
+ tipo__legislativo=True, search_text__icontains=to_ascii(q)
)[:10]
- dados = dados.values("id", "nome", "municipio__latitude",
- "municipio__longitude")
- dados = [{'id': d['id'],
- 'label': d['nome'],
- 'lat': d['municipio__latitude'],
- 'lng': d['municipio__longitude']} for d in dados]
+ dados = dados.values(
+ "id", "nome", "municipio__latitude", "municipio__longitude"
+ )
+ dados = [
+ {
+ "id": d["id"],
+ "label": d["nome"],
+ "lat": d["municipio__latitude"],
+ "lng": d["municipio__longitude"],
+ }
+ for d in dados
+ ]
return JsonResponse(list(dados), safe=False)
-
-
# @never_cache
# @login_required
# def index(request):
# context = {'gerentes': Servidor.objects.exclude(casas_que_gerencia=None)}
# return render(request, 'index.html', context)
+
@never_cache
@login_required
def resumo_convenios(request):
- context = {'tabela_resumo_camara': busca_informacoes_camara() }
- return render(request, 'home/dashboard/resumo_convenios.html', context)
+ context = {"tabela_resumo_camara": busca_informacoes_camara()}
+ return render(request, "home/dashboard/resumo_convenios.html", context)
+
@never_cache
@login_required
def resumo_seit(request):
- mes = request.GET.get('mes', None)
- ano = request.GET.get('ano', None)
+ mes = request.GET.get("mes", None)
+ ano = request.GET.get("ano", None)
try:
mes = datetime.date(year=int(ano), month=int(mes), day=1)
@@ -212,48 +248,60 @@ def resumo_seit(request):
except:
tabela_resumo_seit = busca_informacoes_seit()
- context = {'tabela_resumo_seit': tabela_resumo_seit}
- return render(request, 'home/dashboard/resumo_seit.html', context)
+ context = {"tabela_resumo_seit": tabela_resumo_seit}
+ return render(request, "home/dashboard/resumo_seit.html", context)
+
@never_cache
@login_required
def chart_seit(request):
hoje = datetime.date.today()
- mes = request.GET.get('mes', hoje.month)
- ano = request.GET.get('ano', hoje.year)
+ mes = request.GET.get("mes", hoje.month)
+ ano = request.GET.get("ano", hoje.year)
mes = datetime.date(year=int(ano), month=int(mes), day=1)
tabela_resumo_seit = busca_informacoes_seit(mes)
data = {
- 'type': 'line',
- 'prevlink': reverse('home_chartseit') + (
+ "type": "line",
+ "prevlink": reverse("home_chartseit")
+ + (
f"?ano={tabela_resumo_seit['mes_anterior'].year}"
f"&mes={tabela_resumo_seit['mes_anterior'].month}"
),
- 'nextlink': reverse('home_chartseit') + (
+ "nextlink": reverse("home_chartseit")
+ + (
f"?ano={tabela_resumo_seit['proximo_mes'].year}"
f"&mes={tabela_resumo_seit['proximo_mes'].month}"
),
- 'options': {'bezierCurve': False, 'datasetFill': False,
- 'pointDot': False, 'responsive': True},
- 'data': {
- 'labels': [f'{mes: %m/%Y}'
- for mes in reversed(tabela_resumo_seit['meses'])],
- 'datasets': [
+ "options": {
+ "bezierCurve": False,
+ "datasetFill": False,
+ "pointDot": False,
+ "responsive": True,
+ },
+ "data": {
+ "labels": [
+ f"{mes: %m/%Y}" for mes in reversed(tabela_resumo_seit["meses"])
+ ],
+ "datasets": [
{
- 'label': servico['nome'],
- 'borderColor': servico['cor'],
- 'backgroundColor': servico['cor'],
- 'data': [mes['total']
- for mes in reversed(servico['novos_por_mes'])]
+ "label": servico["nome"],
+ "borderColor": servico["cor"],
+ "backgroundColor": servico["cor"],
+ "data": [
+ mes["total"]
+ for mes in reversed(servico["novos_por_mes"])
+ ],
}
- for servico in tabela_resumo_seit['servicos']],
- }
+ for servico in tabela_resumo_seit["servicos"]
+ ],
+ },
}
return JsonResponse(data)
+
# @never_cache
# @login_required
# def chart_convenios(request):
@@ -268,21 +316,23 @@ def chart_seit(request):
# }
# return JsonResponse(data)
+
@never_cache
@login_required
def chart_carteira(request):
colors, highlights = color_palete()
gerentes = Servidor.objects.exclude(casas_que_gerencia=None).annotate(
- total_casas=Count('casas_que_gerencia'))
+ total_casas=Count("casas_que_gerencia")
+ )
data = {
- 'type': 'doughnut',
- 'data': {
- 'labels': [g.get_apelido() for g in gerentes],
- 'datasets': [
+ "type": "doughnut",
+ "data": {
+ "labels": [g.get_apelido() for g in gerentes],
+ "datasets": [
{
- 'data': [g.total_casas for g in gerentes],
- 'backgroundColor': [next(highlights) for g in gerentes]
+ "data": [g.total_casas for g in gerentes],
+ "backgroundColor": [next(highlights) for g in gerentes],
}
],
},
@@ -290,21 +340,24 @@ def chart_carteira(request):
return JsonResponse(data)
+
@never_cache
@login_required
def chart_performance(request):
- servidor = request.GET.get('servidor', None)
+ servidor = request.GET.get("servidor", None)
gerentes = Servidor.objects.exclude(casas_que_gerencia=None)
gerente = None
if servidor is None:
- if (request.user.servidor and
- request.user.servidor.casas_que_gerencia.exists()):
+ if (
+ request.user.servidor
+ and request.user.servidor.casas_que_gerencia.exists()
+ ):
gerente = request.user.servidor
else:
- servidor = '_all'
+ servidor = "_all"
- if servidor is not None and servidor != '_all':
+ if servidor is not None and servidor != "_all":
gerente = get_object_or_404(Servidor, pk=servidor)
if gerente is None:
@@ -313,94 +366,114 @@ def chart_performance(request):
casas = gerente.casas_que_gerencia
data = {
- 'type': 'doughnut',
- 'data': {
- 'labels': [_("Utilizam serviços"), _("Não utilizam serviços")],
- 'datasets': [
+ "type": "doughnut",
+ "data": {
+ "labels": [_("Utilizam serviços"), _("Não utilizam serviços")],
+ "datasets": [
{
- 'label': 'SeiLaQueIsso',
- 'data': [casas.exclude(servico=None).count(),
- casas.filter(servico=None).count()],
- 'backgroundColor': ['#91e8e1', '#f7a35c']
+ "label": "SeiLaQueIsso",
+ "data": [
+ casas.exclude(servico=None).count(),
+ casas.filter(servico=None).count(),
+ ],
+ "backgroundColor": ["#91e8e1", "#f7a35c"],
}
- ]
+ ],
},
- 'actionblock': render_to_string(
- 'home/dashboard/gerentes_snippet.html',
- context={'gerentes': gerentes, 'gerente': gerente},
- request=request
- )
+ "actionblock": render_to_string(
+ "home/dashboard/gerentes_snippet.html",
+ context={"gerentes": gerentes, "gerente": gerente},
+ request=request,
+ ),
}
return JsonResponse(data)
+
@never_cache
@login_required
def report_sem_convenio(request):
- modo = request.GET.get('modo', None)
- fmt = request.GET.get('f', 'pdf')
+ modo = request.GET.get("modo", None)
+ fmt = request.GET.get("f", "pdf")
sc = sem_convenio()
- if modo == 'H':
- casas = sc['hospedagem']
- titulo = _("Casas sem convenio que utilizam algum serviço de "
- "hospedagem")
- elif modo == 'R':
- casas = sc['registro']
- titulo = _("Casas sem convenio que utilizam somente serviço de "
- "registro")
+ if modo == "H":
+ casas = sc["hospedagem"]
+ titulo = _(
+ "Casas sem convenio que utilizam algum serviço de " "hospedagem"
+ )
+ elif modo == "R":
+ casas = sc["registro"]
+ titulo = _(
+ "Casas sem convenio que utilizam somente serviço de " "registro"
+ )
else:
- casas = sc['total']
- titulo = _("Casas sem convenio que utilizam algum serviço de registro "
- "e/ou hospedagem")
+ casas = sc["total"]
+ titulo = _(
+ "Casas sem convenio que utilizam algum serviço de registro "
+ "e/ou hospedagem"
+ )
- if fmt == 'csv':
- response = HttpResponse(content_type='text/csv')
- response['Content-Disposition'] = f'attachment; filename={ titulo }.csv'
+ if fmt == "csv":
+ response = HttpResponse(content_type="text/csv")
+ response["Content-Disposition"] = f"attachment; filename={ titulo }.csv"
writer = csv.writer(response)
writer.writerow([titulo])
- writer.writerow([''])
- writer.writerow(['casa', 'uf', 'gerentes', 'serviços'])
+ writer.writerow([""])
+ writer.writerow(["casa", "uf", "gerentes", "serviços"])
for casa in casas:
- writer.writerow([
- casa.nome,
- casa.municipio.uf.sigla,
- casa.lista_gerentes(fmt='lista'),
- (', '.join(casa.servico_set.filter(
- data_desativacao__isnull=True).values_list(
- 'tipo_servico__nome', flat=True))),
- ])
+ writer.writerow(
+ [
+ casa.nome,
+ casa.municipio.uf.sigla,
+ casa.lista_gerentes(fmt="lista"),
+ (
+ ", ".join(
+ casa.servico_set.filter(
+ data_desativacao__isnull=True
+ ).values_list("tipo_servico__nome", flat=True)
+ )
+ ),
+ ]
+ )
return response
- elif fmt == 'json':
+ elif fmt == "json":
data = {
- 'titulo': titulo,
- 'casas': [
- {'nome': casa.nome,
- 'uf': casa.municipio.uf.sigla,
- 'gerentes': list(casa.gerentes_interlegis.all().values_list(
- 'nome_completo', flat=True)),
- 'servicos': list(casa.servico_set.filter(
- data_desativacao__isnull=True).values_list(
- 'tipo_servico__nome', flat=True))}
+ "titulo": titulo,
+ "casas": [
+ {
+ "nome": casa.nome,
+ "uf": casa.municipio.uf.sigla,
+ "gerentes": list(
+ casa.gerentes_interlegis.all().values_list(
+ "nome_completo", flat=True
+ )
+ ),
+ "servicos": list(
+ casa.servico_set.filter(
+ data_desativacao__isnull=True
+ ).values_list("tipo_servico__nome", flat=True)
+ ),
+ }
for casa in casas
- ]
+ ],
}
return JsonResponse(data, safe=False)
else:
- context = {'casas': casas, 'title': titulo}
+ context = {"casas": casas, "title": titulo}
return WeasyTemplateResponse(
- filename=f'{ titulo }.pdf',
+ filename=f"{ titulo }.pdf",
request=request,
- template='home/sem_convenio.html',
+ template="home/sem_convenio.html",
context=context,
- content_type='application/pdf',
+ content_type="application/pdf",
)
def busca_informacoes_camara():
- camaras = Orgao.objects.filter(tipo__sigla='CM')
- convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM')
+ camaras = Orgao.objects.filter(tipo__sigla="CM")
+ convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla="CM")
projetos = Projeto.objects.all()
convenios_assinados = convenios.exclude(data_retorno_assinatura=None)
@@ -415,7 +488,9 @@ def busca_informacoes_camara():
# Criacao das listas para o resumo de camaras por projeto
- cabecalho_topo = ['', ] # Cabecalho superior da tabela
+ cabecalho_topo = [
+ "",
+ ] # Cabecalho superior da tabela
lista_total = []
lista_nao_aderidas = []
@@ -450,12 +525,12 @@ def busca_informacoes_camara():
# Cabecalho da esquerda na tabela
cabecalho_esquerda = (
- _('Câmaras municipais'),
- _('Câmaras municipais não aderidas'),
- _('Câmaras municipais aderidas'),
- _('Câmaras municipais com convênios assinados'),
- _('Câmaras municipais convênios em andamento'),
- _('Câmaras municipais equipadas'),
+ _("Câmaras municipais"),
+ _("Câmaras municipais não aderidas"),
+ _("Câmaras municipais aderidas"),
+ _("Câmaras municipais com convênios assinados"),
+ _("Câmaras municipais convênios em andamento"),
+ _("Câmaras municipais equipadas"),
)
linhas = (
@@ -473,45 +548,44 @@ def busca_informacoes_camara():
# Retornando listas em forma de dicionario
return {
- 'cabecalho_topo': cabecalho_topo,
- 'lista_zip': lista_zip,
- 'total_camaras': camaras.count(),
- 'camaras_sem_processo': camaras_sem_processo.count(),
- 'sem_convenio': sem_convenio(),
+ "cabecalho_topo": cabecalho_topo,
+ "lista_zip": lista_zip,
+ "total_camaras": camaras.count(),
+ "camaras_sem_processo": camaras_sem_processo.count(),
+ "sem_convenio": sem_convenio(),
}
+
def sem_convenio():
- total = Orgao.objects.exclude(
- servico=None
- ).filter(
- servico__data_desativacao=None, convenio=None
- ).order_by(
- 'municipio__uf__sigla', 'nome'
- ).distinct(
- 'municipio__uf__sigla', 'nome'
+ total = (
+ Orgao.objects.exclude(servico=None)
+ .filter(servico__data_desativacao=None, convenio=None)
+ .order_by("municipio__uf__sigla", "nome")
+ .distinct("municipio__uf__sigla", "nome")
)
- hospedagem = Orgao.objects.exclude(
- servico=None
- ).filter(
- servico__data_desativacao=None, servico__tipo_servico__modo='H',
- convenio=None
- ).order_by(
- 'municipio__uf__sigla', 'nome'
- ).distinct(
- 'municipio__uf__sigla', 'nome'
+ hospedagem = (
+ Orgao.objects.exclude(servico=None)
+ .filter(
+ servico__data_desativacao=None,
+ servico__tipo_servico__modo="H",
+ convenio=None,
+ )
+ .order_by("municipio__uf__sigla", "nome")
+ .distinct("municipio__uf__sigla", "nome")
)
- reg_keys = set(total.values_list('pk', flat=True)).difference(
- set(hospedagem.values_list('pk', flat=True))
+ reg_keys = set(total.values_list("pk", flat=True)).difference(
+ set(hospedagem.values_list("pk", flat=True))
)
registro = Orgao.objects.filter(pk__in=reg_keys).order_by(
- 'municipio__uf__sigla', 'nome'
+ "municipio__uf__sigla", "nome"
)
return {
- 'total': total,
- 'hospedagem': hospedagem,
- 'registro': registro,
+ "total": total,
+ "hospedagem": hospedagem,
+ "registro": registro,
}
+
# def grafico_convenio_projeto(convenios):
# colors, highlights = color_palete()
# projetos = Projeto.objects.all()
@@ -534,8 +608,9 @@ def busca_informacoes_seit(mes_atual=None):
if mes_atual is None:
mes_atual = datetime.date.today().replace(day=1)
mes_anterior = mes_atual - datetime.timedelta(days=1)
- proximo_mes = mes_atual + datetime.timedelta(days=calendar.monthrange(
- mes_atual.year, mes_atual.month)[1])
+ proximo_mes = mes_atual + datetime.timedelta(
+ days=calendar.monthrange(mes_atual.year, mes_atual.month)[1]
+ )
meses = []
mes = mes_atual
@@ -544,32 +619,53 @@ def busca_informacoes_seit(mes_atual=None):
mes = (mes - datetime.timedelta(days=1)).replace(day=1)
result = {
- 'mes_atual': mes_atual,
- 'mes_anterior': mes_anterior,
- 'proximo_mes': proximo_mes,
- 'meses': meses,
- 'titulos': [ '',
- 'Total de casas atendidas',
- 'Novas casas em %s/%s' % (mes_anterior.month, mes_anterior.year),
- 'Novas casas em %s/%s' % (mes_atual.month, mes_atual.year)
+ "mes_atual": mes_atual,
+ "mes_anterior": mes_anterior,
+ "proximo_mes": proximo_mes,
+ "meses": meses,
+ "titulos": [
+ "",
+ "Total de casas atendidas",
+ "Novas casas em %s/%s" % (mes_anterior.month, mes_anterior.year),
+ "Novas casas em %s/%s" % (mes_atual.month, mes_atual.year),
],
- 'servicos': [],
+ "servicos": [],
}
for tipo_servico in TipoServico.objects.all():
por_mes = []
for mes in meses:
- por_mes.append({'mes': '%02d/%s' % (mes.month, mes.year),
- 'total': tipo_servico.servico_set.filter(data_ativacao__year=mes.year, data_ativacao__month=mes.month).count()})
-
- result['servicos'].append(
- {'nome': tipo_servico.nome,
- 'total': tipo_servico.servico_set.filter(Q(data_ativacao__lt=proximo_mes)&(Q(data_desativacao=None)|Q(data_desativacao__gt=proximo_mes))).count(),
- 'novos_mes_anterior': tipo_servico.servico_set.filter(data_ativacao__year=mes_anterior.year, data_ativacao__month=mes_anterior.month).count(),
- 'novos_mes_atual': tipo_servico.servico_set.filter(data_ativacao__year=mes_atual.year, data_ativacao__month=mes_atual.month).count(),
- 'novos_por_mes': por_mes,
- 'cor': next(colors),
- }
+ por_mes.append(
+ {
+ "mes": "%02d/%s" % (mes.month, mes.year),
+ "total": tipo_servico.servico_set.filter(
+ data_ativacao__year=mes.year,
+ data_ativacao__month=mes.month,
+ ).count(),
+ }
+ )
+
+ result["servicos"].append(
+ {
+ "nome": tipo_servico.nome,
+ "total": tipo_servico.servico_set.filter(
+ Q(data_ativacao__lt=proximo_mes)
+ & (
+ Q(data_desativacao=None)
+ | Q(data_desativacao__gt=proximo_mes)
+ )
+ ).count(),
+ "novos_mes_anterior": tipo_servico.servico_set.filter(
+ data_ativacao__year=mes_anterior.year,
+ data_ativacao__month=mes_anterior.month,
+ ).count(),
+ "novos_mes_atual": tipo_servico.servico_set.filter(
+ data_ativacao__year=mes_atual.year,
+ data_ativacao__month=mes_atual.month,
+ ).count(),
+ "novos_por_mes": por_mes,
+ "cor": next(colors),
+ }
)
return result
@@ -583,26 +679,34 @@ def busca_informacoes_seit(mes_atual=None):
def color_palete():
- colors = cycle(['#7cb5ec',
- '#434348',
- '#90ed7d',
- '#f7a35c',
- '#8085e9',
- '#f15c80',
- '#e4d354',
- '#8085e8',
- '#8d4653',
- '#91e8e1', ])
-
- highlights = cycle(['#B0D3F4',
- '#8E8E91',
- '#BCF4B1',
- '#FAC89D',
- '#B3B6F2',
- '#F79DB3',
- '#EFE598',
- '#B3B6F1',
- '#BB9098',
- '#BDF1ED', ])
+ colors = cycle(
+ [
+ "#7cb5ec",
+ "#434348",
+ "#90ed7d",
+ "#f7a35c",
+ "#8085e9",
+ "#f15c80",
+ "#e4d354",
+ "#8085e8",
+ "#8d4653",
+ "#91e8e1",
+ ]
+ )
+
+ highlights = cycle(
+ [
+ "#B0D3F4",
+ "#8E8E91",
+ "#BCF4B1",
+ "#FAC89D",
+ "#B3B6F2",
+ "#F79DB3",
+ "#EFE598",
+ "#B3B6F1",
+ "#BB9098",
+ "#BDF1ED",
+ ]
+ )
return (colors, highlights)
diff --git a/sigi/apps/inventario/admin.py b/sigi/apps/inventario/admin.py
index c2d8406..4590602 100644
--- a/sigi/apps/inventario/admin.py
+++ b/sigi/apps/inventario/admin.py
@@ -2,70 +2,92 @@ from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from sigi.apps.contatos.models import Contato, Telefone
-from sigi.apps.inventario.models import (Fornecedor, Fabricante, Equipamento,
- TipoEquipamento, ModeloEquipamento,
- Bem)
+from sigi.apps.inventario.models import (
+ Fornecedor,
+ Fabricante,
+ Equipamento,
+ TipoEquipamento,
+ ModeloEquipamento,
+ Bem,
+)
class ContatosInline(GenericTabularInline):
model = Contato
extra = 2
- raw_id_fields = ('municipio',)
+ raw_id_fields = ("municipio",)
+
class TelefonesInline(GenericTabularInline):
model = Telefone
extra = 2
+
@admin.register(Fornecedor)
class FornecedorAdmin(admin.ModelAdmin):
inlines = (TelefonesInline, ContatosInline)
- list_display = ('id', 'nome', 'email', 'pagina_web')
- list_display_links = ('id', 'nome')
- list_filter = ('nome',)
- search_fields = ('id', 'nome', 'email', 'pagina_web')
+ list_display = ("id", "nome", "email", "pagina_web")
+ list_display_links = ("id", "nome")
+ list_filter = ("nome",)
+ search_fields = ("id", "nome", "email", "pagina_web")
+
@admin.register(Fabricante)
class FabricanteAdmin(admin.ModelAdmin):
- list_display = ('id', 'nome')
+ list_display = ("id", "nome")
list_display_links = list_display
- list_filter = ('nome',)
- search_fields = ('id', 'nome')
+ list_filter = ("nome",)
+ search_fields = ("id", "nome")
+
@admin.register(TipoEquipamento)
class TipoEquipamentoAdmin(admin.ModelAdmin):
- list_display = ('id', 'tipo')
+ list_display = ("id", "tipo")
list_display_links = list_display
- list_filter = ('tipo',)
- search_fields = ('id', 'tipo')
+ list_filter = ("tipo",)
+ search_fields = ("id", "tipo")
+
@admin.register(ModeloEquipamento)
class ModeloEquipamentoAdmin(admin.ModelAdmin):
- list_display = ('id', 'tipo', 'modelo')
- list_filter = ('tipo', 'modelo')
- ordering = ('tipo', 'modelo')
- search_fields = ('id', 'tipo', 'modelo')
- raw_id_fields = ('tipo',)
+ list_display = ("id", "tipo", "modelo")
+ list_filter = ("tipo", "modelo")
+ ordering = ("tipo", "modelo")
+ search_fields = ("id", "tipo", "modelo")
+ raw_id_fields = ("tipo",)
+
@admin.register(Equipamento)
class EquipamentoAdmin(admin.ModelAdmin):
- list_display = ('id', 'fabricante', 'modelo', 'get_tipo')
- list_display_links = ('id',)
- list_filter = ('fabricante',)
- ordering = ('fabricante', 'modelo')
- raw_id_fields = ('fabricante', 'modelo')
- search_fields = ('id', 'modelo', 'fabricante')
+ list_display = ("id", "fabricante", "modelo", "get_tipo")
+ list_display_links = ("id",)
+ list_filter = ("fabricante",)
+ ordering = ("fabricante", "modelo")
+ raw_id_fields = ("fabricante", "modelo")
+ search_fields = ("id", "modelo", "fabricante")
def get_tipo(self, obj):
return obj.modelo.tipo.tipo
- get_tipo.short_description = 'tipo'
+
+ get_tipo.short_description = "tipo"
+
@admin.register(Bem)
class BemAdmin(admin.ModelAdmin):
- list_display = ('equipamento', 'fornecedor', 'num_serie',
- 'casa_legislativa')
- list_filter = ('fornecedor',)
- ordering = ('casa_legislativa', 'fornecedor', 'equipamento')
- raw_id_fields = ('casa_legislativa', 'equipamento', 'fornecedor')
- search_fields = ('fornecedor__nome', 'equipamento__fabricante__nome',
- 'equipamento__modelo__modelo', 'num_serie',
- 'num_tombamento', 'casa_legislativa__nome')
+ list_display = (
+ "equipamento",
+ "fornecedor",
+ "num_serie",
+ "casa_legislativa",
+ )
+ list_filter = ("fornecedor",)
+ ordering = ("casa_legislativa", "fornecedor", "equipamento")
+ raw_id_fields = ("casa_legislativa", "equipamento", "fornecedor")
+ search_fields = (
+ "fornecedor__nome",
+ "equipamento__fabricante__nome",
+ "equipamento__modelo__modelo",
+ "num_serie",
+ "num_tombamento",
+ "casa_legislativa__nome",
+ )
diff --git a/sigi/apps/inventario/apps.py b/sigi/apps/inventario/apps.py
index 40ed946..5675a84 100644
--- a/sigi/apps/inventario/apps.py
+++ b/sigi/apps/inventario/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class InventarioConfig(AppConfig):
- name = 'sigi.apps.inventario'
- verbose_name = _('inventário')
+ name = "sigi.apps.inventario"
+ verbose_name = _("inventário")
diff --git a/sigi/apps/inventario/migrations/0001_initial.py b/sigi/apps/inventario/migrations/0001_initial.py
index 23b6bdb..8e1486b 100644
--- a/sigi/apps/inventario/migrations/0001_initial.py
+++ b/sigi/apps/inventario/migrations/0001_initial.py
@@ -7,116 +7,208 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0001_initial'),
+ ("casas", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Bem',
+ name="Bem",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('num_serie', models.CharField(help_text='N\xfamero fornecido pelo fabricante.', unique=True, max_length=64, verbose_name='n\xfamero de s\xe9rie')),
- ('recebido_por', models.CharField(help_text='Nome de quem recebeu o equipamento.', max_length=64, blank=True)),
- ('observacoes', models.TextField(verbose_name='observa\xe7\xf5es', blank=True)),
- ('casa_legislativa', models.ForeignKey(to='casas.CasaLegislativa', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "num_serie",
+ models.CharField(
+ help_text="N\xfamero fornecido pelo fabricante.",
+ unique=True,
+ max_length=64,
+ verbose_name="n\xfamero de s\xe9rie",
+ ),
+ ),
+ (
+ "recebido_por",
+ models.CharField(
+ help_text="Nome de quem recebeu o equipamento.",
+ max_length=64,
+ blank=True,
+ ),
+ ),
+ (
+ "observacoes",
+ models.TextField(
+ verbose_name="observa\xe7\xf5es", blank=True
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ to="casas.CasaLegislativa", on_delete=models.CASCADE
+ ),
+ ),
],
options={
- 'verbose_name_plural': 'bens',
+ "verbose_name_plural": "bens",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Equipamento',
+ name="Equipamento",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Fabricante',
+ name="Fabricante",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(unique=True, max_length=40)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(unique=True, max_length=40)),
],
options={
- 'ordering': ('nome',),
+ "ordering": ("nome",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Fornecedor',
+ name="Fornecedor",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=40)),
- ('email', models.EmailField(max_length=75, verbose_name='e-mail', blank=True)),
- ('pagina_web', models.URLField(verbose_name='p\xe1gina web', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=40)),
+ (
+ "email",
+ models.EmailField(
+ max_length=75, verbose_name="e-mail", blank=True
+ ),
+ ),
+ (
+ "pagina_web",
+ models.URLField(verbose_name="p\xe1gina web", blank=True),
+ ),
],
options={
- 'ordering': ('nome',),
- 'verbose_name_plural': 'fornecedores',
+ "ordering": ("nome",),
+ "verbose_name_plural": "fornecedores",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='ModeloEquipamento',
+ name="ModeloEquipamento",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('modelo', models.CharField(max_length=30)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("modelo", models.CharField(max_length=30)),
],
options={
- 'ordering': ('modelo',),
- 'verbose_name': 'modelo de equipamento',
- 'verbose_name_plural': 'modelos de equipamentos',
+ "ordering": ("modelo",),
+ "verbose_name": "modelo de equipamento",
+ "verbose_name_plural": "modelos de equipamentos",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='TipoEquipamento',
+ name="TipoEquipamento",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('tipo', models.CharField(max_length=40)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("tipo", models.CharField(max_length=40)),
],
options={
- 'ordering': ('tipo',),
- 'verbose_name': 'tipo de equipamento',
- 'verbose_name_plural': 'tipos de equipamentos',
+ "ordering": ("tipo",),
+ "verbose_name": "tipo de equipamento",
+ "verbose_name_plural": "tipos de equipamentos",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='modeloequipamento',
- name='tipo',
- field=models.ForeignKey(verbose_name='tipo de equipamento', to='inventario.TipoEquipamento', on_delete=models.CASCADE),
+ model_name="modeloequipamento",
+ name="tipo",
+ field=models.ForeignKey(
+ verbose_name="tipo de equipamento",
+ to="inventario.TipoEquipamento",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='equipamento',
- name='fabricante',
- field=models.ForeignKey(to='inventario.Fabricante', on_delete=models.CASCADE),
+ model_name="equipamento",
+ name="fabricante",
+ field=models.ForeignKey(
+ to="inventario.Fabricante", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='equipamento',
- name='modelo',
- field=models.ForeignKey(to='inventario.ModeloEquipamento', on_delete=models.CASCADE),
+ model_name="equipamento",
+ name="modelo",
+ field=models.ForeignKey(
+ to="inventario.ModeloEquipamento", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='equipamento',
- unique_together=set([('fabricante', 'modelo')]),
+ name="equipamento",
+ unique_together=set([("fabricante", "modelo")]),
),
migrations.AddField(
- model_name='bem',
- name='equipamento',
- field=models.ForeignKey(to='inventario.Equipamento', on_delete=models.CASCADE),
+ model_name="bem",
+ name="equipamento",
+ field=models.ForeignKey(
+ to="inventario.Equipamento", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='bem',
- name='fornecedor',
- field=models.ForeignKey(to='inventario.Fornecedor', on_delete=models.CASCADE),
+ model_name="bem",
+ name="fornecedor",
+ field=models.ForeignKey(
+ to="inventario.Fornecedor", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py b/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py
index e165c11..4c3e709 100644
--- a/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py
+++ b/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py
@@ -7,15 +7,15 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('inventario', '0001_initial'),
- ('casas', '0014_auto_20210406_1945'),
+ ("inventario", "0001_initial"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='bem',
- name='casa_legislativa',
- field=models.ForeignKey(to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="bem",
+ name="casa_legislativa",
+ field=models.ForeignKey(to="casas.Orgao", on_delete=models.CASCADE),
preserve_default=True,
),
]
diff --git a/sigi/apps/inventario/migrations/0003_auto_20210416_0841.py b/sigi/apps/inventario/migrations/0003_auto_20210416_0841.py
index 07c7ee7..216c664 100644
--- a/sigi/apps/inventario/migrations/0003_auto_20210416_0841.py
+++ b/sigi/apps/inventario/migrations/0003_auto_20210416_0841.py
@@ -8,32 +8,45 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('inventario', '0002_auto_20210406_1945'),
+ ("inventario", "0002_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='bem',
- name='fornecedor',
- field=models.ForeignKey(to='inventario.Fornecedor', on_delete=django.db.models.deletion.PROTECT),
+ model_name="bem",
+ name="fornecedor",
+ field=models.ForeignKey(
+ to="inventario.Fornecedor",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='equipamento',
- name='fabricante',
- field=models.ForeignKey(to='inventario.Fabricante', on_delete=django.db.models.deletion.PROTECT),
+ model_name="equipamento",
+ name="fabricante",
+ field=models.ForeignKey(
+ to="inventario.Fabricante",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='equipamento',
- name='modelo',
- field=models.ForeignKey(to='inventario.ModeloEquipamento', on_delete=django.db.models.deletion.PROTECT),
+ model_name="equipamento",
+ name="modelo",
+ field=models.ForeignKey(
+ to="inventario.ModeloEquipamento",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='modeloequipamento',
- name='tipo',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='tipo de equipamento', to='inventario.TipoEquipamento'),
+ model_name="modeloequipamento",
+ name="tipo",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="tipo de equipamento",
+ to="inventario.TipoEquipamento",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/inventario/migrations/0004_alter_bem_id_alter_equipamento_id_and_more.py b/sigi/apps/inventario/migrations/0004_alter_bem_id_alter_equipamento_id_and_more.py
index eb89482..ae1ad5d 100644
--- a/sigi/apps/inventario/migrations/0004_alter_bem_id_alter_equipamento_id_and_more.py
+++ b/sigi/apps/inventario/migrations/0004_alter_bem_id_alter_equipamento_id_and_more.py
@@ -6,43 +6,75 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('inventario', '0003_auto_20210416_0841'),
+ ("inventario", "0003_auto_20210416_0841"),
]
operations = [
migrations.AlterField(
- model_name='bem',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="bem",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='equipamento',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="equipamento",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='fabricante',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="fabricante",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='fornecedor',
- name='email',
- field=models.EmailField(blank=True, max_length=254, verbose_name='e-mail'),
+ model_name="fornecedor",
+ name="email",
+ field=models.EmailField(
+ blank=True, max_length=254, verbose_name="e-mail"
+ ),
),
migrations.AlterField(
- model_name='fornecedor',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="fornecedor",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='modeloequipamento',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="modeloequipamento",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='tipoequipamento',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="tipoequipamento",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
]
diff --git a/sigi/apps/inventario/models.py b/sigi/apps/inventario/models.py
index c4c8076..0c3e562 100644
--- a/sigi/apps/inventario/models.py
+++ b/sigi/apps/inventario/models.py
@@ -5,94 +5,92 @@ from django.utils.translation import gettext as _
class Fornecedor(models.Model):
nome = models.CharField(max_length=40)
- email = models.EmailField(_('e-mail'), blank=True)
- pagina_web = models.URLField(_('página web'), blank=True)
- telefones = GenericRelation('contatos.Telefone')
- contatos = GenericRelation('contatos.Contato')
+ email = models.EmailField(_("e-mail"), blank=True)
+ pagina_web = models.URLField(_("página web"), blank=True)
+ telefones = GenericRelation("contatos.Telefone")
+ contatos = GenericRelation("contatos.Contato")
class Meta:
- ordering = ('nome',)
- verbose_name_plural = _('fornecedores')
+ ordering = ("nome",)
+ verbose_name_plural = _("fornecedores")
def __str__(self):
return self.nome
+
class Fabricante(models.Model):
nome = models.CharField(max_length=40, unique=True)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
def __str__(self):
return self.nome
+
class TipoEquipamento(models.Model):
tipo = models.CharField(max_length=40)
class Meta:
- ordering = ('tipo',)
- verbose_name = _('tipo de equipamento')
- verbose_name_plural = _('tipos de equipamentos')
+ ordering = ("tipo",)
+ verbose_name = _("tipo de equipamento")
+ verbose_name_plural = _("tipos de equipamentos")
def __str__(self):
return self.tipo
+
class ModeloEquipamento(models.Model):
tipo = models.ForeignKey(
TipoEquipamento,
on_delete=models.PROTECT,
- verbose_name=_('tipo de equipamento')
+ verbose_name=_("tipo de equipamento"),
)
modelo = models.CharField(max_length=30)
class Meta:
- ordering = ('modelo',)
- verbose_name = _('modelo de equipamento')
- verbose_name_plural = _('modelos de equipamentos')
+ ordering = ("modelo",)
+ verbose_name = _("modelo de equipamento")
+ verbose_name_plural = _("modelos de equipamentos")
def __str__(self):
return self.modelo
+
class Equipamento(models.Model):
- fabricante = models.ForeignKey(
- Fabricante,
- on_delete=models.PROTECT
- )
- modelo = models.ForeignKey(
- ModeloEquipamento,
- on_delete=models.PROTECT
- )
+ fabricante = models.ForeignKey(Fabricante, on_delete=models.PROTECT)
+ modelo = models.ForeignKey(ModeloEquipamento, on_delete=models.PROTECT)
class Meta:
- unique_together = (('fabricante', 'modelo'),)
+ unique_together = (("fabricante", "modelo"),)
def __str__(self):
return _(
f"{self.modelo.tipo} {self.fabricante.nome} {self.modelo.modelo}"
)
+
class Bem(models.Model):
casa_legislativa = models.ForeignKey(
- 'casas.Orgao',
- on_delete=models.CASCADE
+ "casas.Orgao", on_delete=models.CASCADE
)
equipamento = models.ForeignKey(Equipamento, on_delete=models.CASCADE)
fornecedor = models.ForeignKey(Fornecedor, on_delete=models.PROTECT)
num_serie = models.CharField(
- _('número de série'),
+ _("número de série"),
max_length=64,
- help_text=_('Número fornecido pelo fabricante.'),
- unique=True
+ help_text=_("Número fornecido pelo fabricante."),
+ unique=True,
)
recebido_por = models.CharField(
max_length=64,
blank=True,
- help_text=_('Nome de quem recebeu o equipamento.')
+ help_text=_("Nome de quem recebeu o equipamento."),
)
- observacoes = models.TextField(_('observações'), blank=True)
+ observacoes = models.TextField(_("observações"), blank=True)
class Meta:
- verbose_name_plural = _('bens')
+ verbose_name_plural = _("bens")
def __str__(self):
return _(f"{self.equipamento} ({self.casa_legislativa})")
diff --git a/sigi/apps/metas/admin.py b/sigi/apps/metas/admin.py
index 259af79..9536dd3 100644
--- a/sigi/apps/metas/admin.py
+++ b/sigi/apps/metas/admin.py
@@ -7,47 +7,95 @@ from sigi.apps.utils.base_admin import BaseModelAdmin
class MetaAdmin(BaseModelAdmin):
- list_display = ('projeto', 'titulo', 'data_inicio', 'data_fim', 'valor_meta', 'valor_executado', 'percentual_concluido',)
- fields = ('projeto', 'titulo', 'descricao', 'data_inicio', 'data_fim', 'algoritmo', 'valor_meta',)
- list_filter = ('projeto',)
+ list_display = (
+ "projeto",
+ "titulo",
+ "data_inicio",
+ "data_fim",
+ "valor_meta",
+ "valor_executado",
+ "percentual_concluido",
+ )
+ fields = (
+ "projeto",
+ "titulo",
+ "descricao",
+ "data_inicio",
+ "data_fim",
+ "algoritmo",
+ "valor_meta",
+ )
+ list_filter = ("projeto",)
class PlanoDiretorAdmin(BaseModelAdmin):
- list_display = ('projeto', 'casa_legislativa', 'get_uf', 'status', 'data_entrega', 'data_implantacao',)
- fields = ('projeto', 'casa_legislativa', 'status', 'data_entrega', 'data_implantacao',)
- raw_id_fields = ('casa_legislativa',)
- list_filter = ('projeto', 'status', 'casa_legislativa', 'casa_legislativa__municipio__uf__nome')
+ list_display = (
+ "projeto",
+ "casa_legislativa",
+ "get_uf",
+ "status",
+ "data_entrega",
+ "data_implantacao",
+ )
+ fields = (
+ "projeto",
+ "casa_legislativa",
+ "status",
+ "data_entrega",
+ "data_implantacao",
+ )
+ raw_id_fields = ("casa_legislativa",)
+ list_filter = (
+ "projeto",
+ "status",
+ "casa_legislativa",
+ "casa_legislativa__municipio__uf__nome",
+ )
def get_uf(self, obj):
return obj.casa_legislativa.municipio.uf.nome
+
get_uf.short_description = _("UF")
- get_uf.admin_order_field = 'casa_legislativa__municipio__uf__nome'
+ get_uf.admin_order_field = "casa_legislativa__municipio__uf__nome"
def lookup_allowed(self, lookup, value):
- return super(PlanoDiretorAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact']
+ return super(PlanoDiretorAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in ["casa_legislativa__municipio__uf__codigo_ibge__exact"]
def changelist_view(self, request, extra_context=None):
import re
+
request.GET._mutable = True
- if 'data_entrega__gte' in request.GET:
- value = request.GET.get('data_entrega__gte', '')
- if value == '':
- del request.GET['data_entrega__gte']
- elif re.match('^\d*$', value): # Year only
- request.GET['data_entrega__gte'] = "%s-01-01" % value # Complete with january 1st
- elif re.match('^\d*\D\d*$', value): # Year and month
- request.GET['data_entrega__gte'] = '%s-01' % value # Complete with 1st day of month
- if 'data_entrega__lte' in request.GET:
- value = request.GET.get('data_entrega__lte', '')
- if value == '':
- del request.GET['data_entrega__lte']
- elif re.match('^\d*$', value): # Year only
- request.GET['data_entrega__lte'] = "%s-01-01" % value # Complete with january 1st
- elif re.match('^\d*\D\d*$', value): # Year and month
- request.GET['data_entrega__lte'] = '%s-01' % value # Complete with 1st day of month
+ if "data_entrega__gte" in request.GET:
+ value = request.GET.get("data_entrega__gte", "")
+ if value == "":
+ del request.GET["data_entrega__gte"]
+ elif re.match("^\d*$", value): # Year only
+ request.GET["data_entrega__gte"] = (
+ "%s-01-01" % value
+ ) # Complete with january 1st
+ elif re.match("^\d*\D\d*$", value): # Year and month
+ request.GET["data_entrega__gte"] = (
+ "%s-01" % value
+ ) # Complete with 1st day of month
+ if "data_entrega__lte" in request.GET:
+ value = request.GET.get("data_entrega__lte", "")
+ if value == "":
+ del request.GET["data_entrega__lte"]
+ elif re.match("^\d*$", value): # Year only
+ request.GET["data_entrega__lte"] = (
+ "%s-01-01" % value
+ ) # Complete with january 1st
+ elif re.match("^\d*\D\d*$", value): # Year and month
+ request.GET["data_entrega__lte"] = (
+ "%s-01" % value
+ ) # Complete with 1st day of month
request.GET._mutable = False
- return super(PlanoDiretorAdmin, self).changelist_view(request, extra_context)
+ return super(PlanoDiretorAdmin, self).changelist_view(
+ request, extra_context
+ )
+
admin.site.register(PlanoDiretor, PlanoDiretorAdmin)
diff --git a/sigi/apps/metas/migrations/0001_initial.py b/sigi/apps/metas/migrations/0001_initial.py
index a7e4740..ed628c0 100644
--- a/sigi/apps/metas/migrations/0001_initial.py
+++ b/sigi/apps/metas/migrations/0001_initial.py
@@ -7,42 +7,138 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0001_initial'),
- ('convenios', '0001_initial'),
+ ("casas", "0001_initial"),
+ ("convenios", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Meta',
+ name="Meta",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('titulo', models.CharField(help_text='T\xedtulo da meta que aparecer\xe1 no dashboard', max_length=40, verbose_name='T\xedtulo')),
- ('descricao', models.TextField(verbose_name='Descri\xe7\xe3o')),
- ('data_inicio', models.DateField(help_text='In\xedcio do per\xedodo de c\xf4mputo da meta', verbose_name='Data inicial')),
- ('data_fim', models.DateField(help_text='Prazo final para cumprimento da meta', verbose_name='Data final')),
- ('algoritmo', models.CharField(max_length=10, verbose_name='Algoritmo de c\xe1lculo', choices=[(b'SUM_GASTOS', 'Soma dos desembolsos'), (b'COUNT_EQUI', 'Quantidade de casas equipadas'), (b'COUNT_ADER', 'Quantidade de casas aderidas'), (b'COUNT_DIAG', 'Quantidade de casas diagnosticadas'), (b'COUNT_PDIR', 'Quantidade de planos diretores'), (b'COUNT_CONV', 'Quantidade de casas conveniadas')])),
- ('valor_meta', models.FloatField(help_text='Valor que deve ser atingido at\xe9 o prazo final da meta', verbose_name='Valor da meta')),
- ('projeto', models.ForeignKey(verbose_name='Projeto', to='convenios.Projeto', help_text='Projeto ao qual a meta se refere')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "titulo",
+ models.CharField(
+ help_text="T\xedtulo da meta que aparecer\xe1 no dashboard",
+ max_length=40,
+ verbose_name="T\xedtulo",
+ ),
+ ),
+ ("descricao", models.TextField(verbose_name="Descri\xe7\xe3o")),
+ (
+ "data_inicio",
+ models.DateField(
+ help_text="In\xedcio do per\xedodo de c\xf4mputo da meta",
+ verbose_name="Data inicial",
+ ),
+ ),
+ (
+ "data_fim",
+ models.DateField(
+ help_text="Prazo final para cumprimento da meta",
+ verbose_name="Data final",
+ ),
+ ),
+ (
+ "algoritmo",
+ models.CharField(
+ max_length=10,
+ verbose_name="Algoritmo de c\xe1lculo",
+ choices=[
+ (b"SUM_GASTOS", "Soma dos desembolsos"),
+ (b"COUNT_EQUI", "Quantidade de casas equipadas"),
+ (b"COUNT_ADER", "Quantidade de casas aderidas"),
+ (
+ b"COUNT_DIAG",
+ "Quantidade de casas diagnosticadas",
+ ),
+ (b"COUNT_PDIR", "Quantidade de planos diretores"),
+ (b"COUNT_CONV", "Quantidade de casas conveniadas"),
+ ],
+ ),
+ ),
+ (
+ "valor_meta",
+ models.FloatField(
+ help_text="Valor que deve ser atingido at\xe9 o prazo final da meta",
+ verbose_name="Valor da meta",
+ ),
+ ),
+ (
+ "projeto",
+ models.ForeignKey(
+ verbose_name="Projeto",
+ to="convenios.Projeto",
+ help_text="Projeto ao qual a meta se refere",
+ ),
+ ),
],
options={
- 'verbose_name': 'Meta BID',
- 'verbose_name_plural': 'Metas BID',
+ "verbose_name": "Meta BID",
+ "verbose_name_plural": "Metas BID",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='PlanoDiretor',
+ name="PlanoDiretor",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('status', models.CharField(default=b'E', max_length=1, verbose_name='Status', choices=[(b'E', 'Entregue'), (b'I', 'Implantado')])),
- ('data_entrega', models.DateField(null=True, verbose_name='Data de entrega', blank=True)),
- ('data_implantacao', models.DateField(null=True, verbose_name='Data de implanta\xe7\xe3o', blank=True)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa')),
- ('projeto', models.ForeignKey(verbose_name='Projeto', to='convenios.Projeto')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ default=b"E",
+ max_length=1,
+ verbose_name="Status",
+ choices=[(b"E", "Entregue"), (b"I", "Implantado")],
+ ),
+ ),
+ (
+ "data_entrega",
+ models.DateField(
+ null=True, verbose_name="Data de entrega", blank=True
+ ),
+ ),
+ (
+ "data_implantacao",
+ models.DateField(
+ null=True,
+ verbose_name="Data de implanta\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ ),
+ ),
+ (
+ "projeto",
+ models.ForeignKey(
+ verbose_name="Projeto", to="convenios.Projeto"
+ ),
+ ),
],
options={
- 'verbose_name': 'Plano Diretor',
- 'verbose_name_plural': 'Planos Diretores',
+ "verbose_name": "Plano Diretor",
+ "verbose_name_plural": "Planos Diretores",
},
bases=(models.Model,),
),
diff --git a/sigi/apps/metas/migrations/0002_auto_20210406_1945.py b/sigi/apps/metas/migrations/0002_auto_20210406_1945.py
index c590ad0..35d6cbd 100644
--- a/sigi/apps/metas/migrations/0002_auto_20210406_1945.py
+++ b/sigi/apps/metas/migrations/0002_auto_20210406_1945.py
@@ -7,15 +7,17 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('metas', '0001_initial'),
- ('casas', '0014_auto_20210406_1945'),
+ ("metas", "0001_initial"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='planodiretor',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
+ model_name="planodiretor",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa", to="casas.Orgao"
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/metas/models.py b/sigi/apps/metas/models.py
index 27610b6..3e46027 100644
--- a/sigi/apps/metas/models.py
+++ b/sigi/apps/metas/models.py
@@ -11,29 +11,42 @@ from sigi.apps.financeiro.models import Desembolso
class Meta(models.Model):
ALGORITMO_CHOICES = (
- ('SUM_GASTOS', _('Soma dos desembolsos')),
- ('COUNT_EQUI', _('Quantidade de casas equipadas')),
- ('COUNT_ADER', _('Quantidade de casas aderidas')),
- ('COUNT_DIAG', _('Quantidade de casas diagnosticadas')),
- ('COUNT_PDIR', _('Quantidade de planos diretores')),
- ('COUNT_CONV', _('Quantidade de casas conveniadas')),
+ ("SUM_GASTOS", _("Soma dos desembolsos")),
+ ("COUNT_EQUI", _("Quantidade de casas equipadas")),
+ ("COUNT_ADER", _("Quantidade de casas aderidas")),
+ ("COUNT_DIAG", _("Quantidade de casas diagnosticadas")),
+ ("COUNT_PDIR", _("Quantidade de planos diretores")),
+ ("COUNT_CONV", _("Quantidade de casas conveniadas")),
)
projeto = models.ForeignKey(
Projeto,
on_delete=models.CASCADE,
- verbose_name=_('Projeto'),
- help_text=_('Projeto ao qual a meta se refere')
+ verbose_name=_("Projeto"),
+ help_text=_("Projeto ao qual a meta se refere"),
+ )
+ titulo = models.CharField(
+ _("Título"),
+ max_length=40,
+ help_text=_("Título da meta que aparecerá no dashboard"),
+ )
+ descricao = models.TextField(_("Descrição"))
+ data_inicio = models.DateField(
+ _("Data inicial"), help_text=_("Início do período de cômputo da meta")
+ )
+ data_fim = models.DateField(
+ _("Data final"), help_text=_("Prazo final para cumprimento da meta")
+ )
+ algoritmo = models.CharField(
+ _("Algoritmo de cálculo"), max_length=10, choices=ALGORITMO_CHOICES
+ )
+ valor_meta = models.FloatField(
+ _("Valor da meta"),
+ help_text=_("Valor que deve ser atingido até o prazo final da meta"),
)
- titulo = models.CharField(_('Título'), max_length=40, help_text=_('Título da meta que aparecerá no dashboard'))
- descricao = models.TextField(_('Descrição'))
- data_inicio = models.DateField(_('Data inicial'), help_text=_('Início do período de cômputo da meta'))
- data_fim = models.DateField(_('Data final'), help_text=_('Prazo final para cumprimento da meta'))
- algoritmo = models.CharField(_('Algoritmo de cálculo'), max_length=10, choices=ALGORITMO_CHOICES)
- valor_meta = models.FloatField(_('Valor da meta'), help_text=_('Valor que deve ser atingido até o prazo final da meta'))
class Meta:
- verbose_name = _('Meta BID')
- verbose_name_plural = _('Metas BID')
+ verbose_name = _("Meta BID")
+ verbose_name_plural = _("Metas BID")
def __unicode__(self):
return self.titulo
@@ -53,7 +66,9 @@ class Meta(models.Model):
@property
def percentual_concluido(self):
- return round(float(self.valor_executado) / float(self.valor_meta) * 100.0, 2)
+ return round(
+ float(self.valor_executado) / float(self.valor_meta) * 100.0, 2
+ )
@property
def valor_desejado(self):
@@ -64,79 +79,119 @@ class Meta(models.Model):
@property
def percentual_desejado_low(self):
- return (self.valor_desejado / self.valor_meta) - 0.05 # 5% abaixo do desejado
+ return (
+ self.valor_desejado / self.valor_meta
+ ) - 0.05 # 5% abaixo do desejado
@property
def percentual_desejado_high(self):
- return (self.valor_desejado / self.valor_meta) + 0.05 # 5% acima do desejado
+ return (
+ self.valor_desejado / self.valor_meta
+ ) + 0.05 # 5% acima do desejado
@property
def saude(self):
percentual_concluido = self.percentual_concluido / 100.0
if percentual_concluido >= 1:
- return 'A2BBED' # Blue
+ return "A2BBED" # Blue
if percentual_concluido > self.percentual_desejado_high:
- return '89D7AF' # Green
+ return "89D7AF" # Green
if percentual_concluido > self.percentual_desejado_low:
- return 'FFDB6E' # Orange
+ return "FFDB6E" # Orange
- return 'E74A69' # Red
+ return "E74A69" # Red
def sum_gastos(self):
- valor = Desembolso.objects.filter(projeto=self.projeto, data__gte=self.data_inicio, data__lte=self.data_fim) \
- .aggregate(total_dolar=models.Sum('valor_dolar'))
- valor = valor['total_dolar']
+ valor = Desembolso.objects.filter(
+ projeto=self.projeto,
+ data__gte=self.data_inicio,
+ data__lte=self.data_fim,
+ ).aggregate(total_dolar=models.Sum("valor_dolar"))
+ valor = valor["total_dolar"]
return valor
def count_equi(self):
- valor = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM', equipada=True, projeto__pk=3, data_termo_aceite__gte=self.data_inicio, data_termo_aceite__lte=self.data_fim).exclude(data_termo_aceite=None).count()
+ valor = (
+ Convenio.objects.filter(
+ casa_legislativa__tipo__sigla="CM",
+ equipada=True,
+ projeto__pk=3,
+ data_termo_aceite__gte=self.data_inicio,
+ data_termo_aceite__lte=self.data_fim,
+ )
+ .exclude(data_termo_aceite=None)
+ .count()
+ )
return valor
def count_ader(self):
- valor = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM', projeto=self.projeto, data_adesao__gte=self.data_inicio,
- data_adesao__lte=self.data_fim).exclude(data_adesao=None).count()
+ valor = (
+ Convenio.objects.filter(
+ casa_legislativa__tipo__sigla="CM",
+ projeto=self.projeto,
+ data_adesao__gte=self.data_inicio,
+ data_adesao__lte=self.data_fim,
+ )
+ .exclude(data_adesao=None)
+ .count()
+ )
return valor
def count_diag(self):
- valor = Diagnostico.objects.filter(data_visita_inicio__gte=self.data_inicio, data_visita_inicio__lte=self.data_fim,
- publicado=True).count()
+ valor = Diagnostico.objects.filter(
+ data_visita_inicio__gte=self.data_inicio,
+ data_visita_inicio__lte=self.data_fim,
+ publicado=True,
+ ).count()
return valor
def count_pdir(self):
- valor = PlanoDiretor.objects.filter(projeto=self.projeto, data_entrega__gte=self.data_inicio,
- data_entrega__lte=self.data_fim).count()
+ valor = PlanoDiretor.objects.filter(
+ projeto=self.projeto,
+ data_entrega__gte=self.data_inicio,
+ data_entrega__lte=self.data_fim,
+ ).count()
return valor
def count_conv(self):
- valor = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM', projeto=self.projeto, data_retorno_assinatura__gte=self.data_inicio, data_retorno_assinatura__lte=self.data_fim).exclude(data_retorno_assinatura=None).count()
+ valor = (
+ Convenio.objects.filter(
+ casa_legislativa__tipo__sigla="CM",
+ projeto=self.projeto,
+ data_retorno_assinatura__gte=self.data_inicio,
+ data_retorno_assinatura__lte=self.data_fim,
+ )
+ .exclude(data_retorno_assinatura=None)
+ .count()
+ )
return valor
class PlanoDiretor(models.Model):
STATUS_CHOICE = (
- ('E', _('Entregue')),
- ('I', _('Implantado')),
+ ("E", _("Entregue")),
+ ("I", _("Implantado")),
)
projeto = models.ForeignKey(
- Projeto,
- on_delete=models.CASCADE,
- verbose_name=_('Projeto')
+ Projeto, on_delete=models.CASCADE, verbose_name=_("Projeto")
)
casa_legislativa = models.ForeignKey(
- Orgao,
- on_delete=models.CASCADE,
- verbose_name=_('Casa Legislativa')
+ Orgao, on_delete=models.CASCADE, verbose_name=_("Casa Legislativa")
)
casa_legislativa.casa_uf_filter = True
- status = models.CharField(_('Status'), max_length=1, choices=STATUS_CHOICE, default='E')
- data_entrega = models.DateField(_('Data de entrega'), blank=True, null=True)
- data_implantacao = models.DateField(_('Data de implantação'), blank=True, null=True)
+ status = models.CharField(
+ _("Status"), max_length=1, choices=STATUS_CHOICE, default="E"
+ )
+ data_entrega = models.DateField(_("Data de entrega"), blank=True, null=True)
+ data_implantacao = models.DateField(
+ _("Data de implantação"), blank=True, null=True
+ )
class Meta:
- verbose_name = _('Plano Diretor')
- verbose_name_plural = _('Planos Diretores')
+ verbose_name = _("Plano Diretor")
+ verbose_name_plural = _("Planos Diretores")
def __unicode__(self):
return self.casa_legislativa.nome
diff --git a/sigi/apps/metas/templatetags/mapa_tags.py b/sigi/apps/metas/templatetags/mapa_tags.py
index bd71770..7493afc 100644
--- a/sigi/apps/metas/templatetags/mapa_tags.py
+++ b/sigi/apps/metas/templatetags/mapa_tags.py
@@ -9,12 +9,14 @@ from sigi.apps.metas.views import openmap
register = template.Library()
-@register.filter(name='map_desc_serv')
+@register.filter(name="map_desc_serv")
def descricao_servicos(casa):
if not isinstance(casa, Orgao):
return ""
summary = openmap(casa)
- result = ''.join('%s ' % info for info in summary['info'])
+ result = "".join("%s " % info for info in summary["info"])
return mark_safe(result)
+
+
descricao_servicos.is_safe = True
diff --git a/sigi/apps/metas/urls.py b/sigi/apps/metas/urls.py
index 52e73a4..e3a21a9 100644
--- a/sigi/apps/metas/urls.py
+++ b/sigi/apps/metas/urls.py
@@ -3,11 +3,14 @@ from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns(
- 'sigi.apps.metas.views',
-
- url(r'^$', 'dashboard', name='metas-dashboardsss'), # tagerror
- url(r'^openmap/$', 'openmap', name='openmap'),
- url(r'^openmapdata/$', 'openmapdata', name='openmapdata'),
- url(r'^openmapdetail/(?P\w+)/$', 'openmapdetail', name='openmapdetail'),
- url(r'^openmapsearch/$', 'openmapsearch', name='openmapsearch'),
+ "sigi.apps.metas.views",
+ url(r"^$", "dashboard", name="metas-dashboardsss"), # tagerror
+ url(r"^openmap/$", "openmap", name="openmap"),
+ url(r"^openmapdata/$", "openmapdata", name="openmapdata"),
+ url(
+ r"^openmapdetail/(?P\w+)/$",
+ "openmapdetail",
+ name="openmapdetail",
+ ),
+ url(r"^openmapsearch/$", "openmapsearch", name="openmapsearch"),
)
diff --git a/sigi/apps/metas/views.py b/sigi/apps/metas/views.py
index d7a7269..ef4f861 100644
--- a/sigi/apps/metas/views.py
+++ b/sigi/apps/metas/views.py
@@ -30,134 +30,206 @@ from sigi.shortcuts import render_to_pdf
from sigi.apps.servidores.models import Servidor
-JSON_FILE_NAME = os.path.join(MEDIA_ROOT, 'apps/metas/map_data.json')
+JSON_FILE_NAME = os.path.join(MEDIA_ROOT, "apps/metas/map_data.json")
@login_required
def dashboard(request):
- if request.user.groups.filter(name__in=['SPDT-Servidores', 'SSPLF']).count() <= 0:
+ if (
+ request.user.groups.filter(
+ name__in=["SPDT-Servidores", "SSPLF"]
+ ).count()
+ <= 0
+ ):
raise PermissionDenied
desembolsos_max = 0
matriz = SortedDict()
dados = SortedDict()
projetos = Projeto.objects.all()
- meses = Desembolso.objects.dates('data', 'month', 'DESC')[:6]
- colors = ['ffff00', 'cc7900', 'ff0000', '92d050', '006600', '0097cc', '002776', 'ae78d6', 'ff00ff', '430080',
- '28d75c', '0000ff', 'fff200']
+ meses = Desembolso.objects.dates("data", "month", "DESC")[:6]
+ colors = [
+ "ffff00",
+ "cc7900",
+ "ff0000",
+ "92d050",
+ "006600",
+ "0097cc",
+ "002776",
+ "ae78d6",
+ "ff00ff",
+ "430080",
+ "28d75c",
+ "0000ff",
+ "fff200",
+ ]
for date in reversed(meses):
- mes_ano = '%s/%s' % (date.month, date.year)
+ mes_ano = "%s/%s" % (date.month, date.year)
dados[mes_ano] = 0
for p in projetos:
matriz[p.id] = (p.sigla, dados.copy())
for date in meses:
- mes_ano = '%s/%s' % (date.month, date.year)
- for d in Desembolso.objects.filter(data__year=date.year, data__month=date.month).values('projeto').annotate(total_dolar=Sum('valor_dolar')):
- if int(d['total_dolar']) > desembolsos_max:
- desembolsos_max = int(d['total_dolar'])
- matriz[d['projeto']][1][mes_ano] += int(d['total_dolar'])
+ mes_ano = "%s/%s" % (date.month, date.year)
+ for d in (
+ Desembolso.objects.filter(
+ data__year=date.year, data__month=date.month
+ )
+ .values("projeto")
+ .annotate(total_dolar=Sum("valor_dolar"))
+ ):
+ if int(d["total_dolar"]) > desembolsos_max:
+ desembolsos_max = int(d["total_dolar"])
+ matriz[d["projeto"]][1][mes_ano] += int(d["total_dolar"])
meses = ["%s/%s" % (m.month, m.year) for m in reversed(meses)]
- extra_context = {'desembolsos': matriz, 'desembolsos_max': desembolsos_max, 'meses': meses, 'colors': ','.join(colors[:len(matriz)])}
- return render_to_response('metas/dashboard.html', extra_context, context_instance=RequestContext(request))
+ extra_context = {
+ "desembolsos": matriz,
+ "desembolsos_max": desembolsos_max,
+ "meses": meses,
+ "colors": ",".join(colors[: len(matriz)]),
+ }
+ return render_to_response(
+ "metas/dashboard.html",
+ extra_context,
+ context_instance=RequestContext(request),
+ )
+
def openmap(request):
- reptype = request.GET.get('reptype', None)
+ reptype = request.GET.get("reptype", None)
if reptype is None:
context = {
- 'tipos_orgao': TipoOrgao.objects.filter(legislativo=True),
- 'tipos_servico': TipoServico.objects.all(),
- 'tipos_convenio': Projeto.objects.all(),
- 'gerentes': Servidor.objects.exclude(casas_que_gerencia=None),
- 'regioes': [(s, n, UnidadeFederativa.objects.filter(regiao=s))
- for s, n in UnidadeFederativa.REGIAO_CHOICES],
+ "tipos_orgao": TipoOrgao.objects.filter(legislativo=True),
+ "tipos_servico": TipoServico.objects.all(),
+ "tipos_convenio": Projeto.objects.all(),
+ "gerentes": Servidor.objects.exclude(casas_que_gerencia=None),
+ "regioes": [
+ (s, n, UnidadeFederativa.objects.filter(regiao=s))
+ for s, n in UnidadeFederativa.REGIAO_CHOICES
+ ],
}
- return render(request, 'metas/openmap.html', context)
+ return render(request, "metas/openmap.html", context)
else:
- tipos_orgao = request.GET.getlist('tipo_orgao', [])
- tipos_servico = request.GET.getlist('tipo_servico', [])
- tipos_convenio = request.GET.getlist('tipo_convenio', [])
- gerentes = request.GET.getlist('gerente', [])
- ufs = request.GET.getlist('uf', [])
+ tipos_orgao = request.GET.getlist("tipo_orgao", [])
+ tipos_servico = request.GET.getlist("tipo_servico", [])
+ tipos_convenio = request.GET.getlist("tipo_convenio", [])
+ gerentes = request.GET.getlist("gerente", [])
+ ufs = request.GET.getlist("uf", [])
casas = openmapdata(request)
context = {
- 'tipos_orgao': TipoOrgao.objects.filter(legislativo=True,
- sigla__in=tipos_orgao),
- 'tipos_servico': TipoServico.objects.filter(
+ "tipos_orgao": TipoOrgao.objects.filter(
+ legislativo=True, sigla__in=tipos_orgao
+ ),
+ "tipos_servico": TipoServico.objects.filter(
sigla__in=tipos_servico
),
- 'tipos_convenio': Projeto.objects.filter(sigla__in=tipos_convenio),
- 'gerentes': Servidor.objects.exclude(
- casas_que_gerencia=None).filter(id__in=gerentes),
- 'ufs': UnidadeFederativa.objects.filter(sigla__in=ufs),
- 'casas': casas
+ "tipos_convenio": Projeto.objects.filter(sigla__in=tipos_convenio),
+ "gerentes": Servidor.objects.exclude(
+ casas_que_gerencia=None
+ ).filter(id__in=gerentes),
+ "ufs": UnidadeFederativa.objects.filter(sigla__in=ufs),
+ "casas": casas,
}
if reptype == "lista":
return render_to_pdf("metas/lista_casas.html", context)
else:
- fieldnames = ['cnpj', 'nome', 'uf', 'regiao', 'endereco', 'bairro',
- 'cep', 'ult_alt_endereco', 'presidente',
- 'ult_atualizacao_presidente', 'telefone_presidente',
- 'email_presidente', 'telefones', 'emails', 'contatos',
- 'convenios', 'servicos']
- response = HttpResponse(content_type='text/csv')
+ fieldnames = [
+ "cnpj",
+ "nome",
+ "uf",
+ "regiao",
+ "endereco",
+ "bairro",
+ "cep",
+ "ult_alt_endereco",
+ "presidente",
+ "ult_atualizacao_presidente",
+ "telefone_presidente",
+ "email_presidente",
+ "telefones",
+ "emails",
+ "contatos",
+ "convenios",
+ "servicos",
+ ]
+ response = HttpResponse(content_type="text/csv")
writer = csv.DictWriter(response, fieldnames=fieldnames)
writer.writeheader()
for casa in casas:
row = {
- 'cnpj': casa.cnpj.encode('utf8'),
- 'nome': casa.nome.encode('utf8'),
- 'uf': casa.municipio.uf.nome.encode('utf8'),
- 'regiao':
- casa.municipio.uf.get_regiao_display().encode('utf8'),
- 'endereco': casa.logradouro.encode('utf8'),
- 'bairro': casa.bairro.encode('utf8'),
- 'cep': casa.cep.encode('utf8'),
- 'ult_alt_endereco': (casa.ult_alt_endereco.strftime(
- "%d/%m/%Y").encode('utf8')
- if casa.ult_alt_endereco else ""),
- 'telefones': ", ".join(casa.telefones.values_list('numero',
- flat=True)
- ).encode('utf8'),
- 'emails': ", ".join([casa.email] + list(
- casa.funcionario_set.values_list('email',flat=True))
- ).encode('utf8'),
- 'contatos': ", ".join(casa.funcionario_set.values_list(
- 'nome', flat=True)).encode('utf8'),
- 'convenios': ", ".join([c.__unicode__() for c in
- casa.convenio_set.all()]
- ).encode('utf8'),
- 'servicos': ", ".join(["{tipo} ({url})".format(
- tipo=s.tipo_servico.nome, url=s.url)
- for s in casa.servico_set.all()]
- ).encode('utf8')
+ "cnpj": casa.cnpj.encode("utf8"),
+ "nome": casa.nome.encode("utf8"),
+ "uf": casa.municipio.uf.nome.encode("utf8"),
+ "regiao": casa.municipio.uf.get_regiao_display().encode(
+ "utf8"
+ ),
+ "endereco": casa.logradouro.encode("utf8"),
+ "bairro": casa.bairro.encode("utf8"),
+ "cep": casa.cep.encode("utf8"),
+ "ult_alt_endereco": (
+ casa.ult_alt_endereco.strftime("%d/%m/%Y").encode(
+ "utf8"
+ )
+ if casa.ult_alt_endereco
+ else ""
+ ),
+ "telefones": ", ".join(
+ casa.telefones.values_list("numero", flat=True)
+ ).encode("utf8"),
+ "emails": ", ".join(
+ [casa.email]
+ + list(
+ casa.funcionario_set.values_list("email", flat=True)
+ )
+ ).encode("utf8"),
+ "contatos": ", ".join(
+ casa.funcionario_set.values_list("nome", flat=True)
+ ).encode("utf8"),
+ "convenios": ", ".join(
+ [c.__unicode__() for c in casa.convenio_set.all()]
+ ).encode("utf8"),
+ "servicos": ", ".join(
+ [
+ "{tipo} ({url})".format(
+ tipo=s.tipo_servico.nome, url=s.url
+ )
+ for s in casa.servico_set.all()
+ ]
+ ).encode("utf8"),
}
if casa.presidente:
- row['presidente'] = casa.presidente.nome.encode('utf8')
- row['ult_atualizacao_presidente'] = (
+ row["presidente"] = casa.presidente.nome.encode("utf8")
+ row["ult_atualizacao_presidente"] = (
casa.presidente.ult_alteracao.strftime("%d/%m/%Y")
- if casa.presidente.ult_alteracao else "")
- row['telefone_presidente'] = casa.presidente.nota.encode(
- 'utf8') if casa.presidente.nota else ""
- row['email_presidente'] = casa.presidente.email.encode(
- 'utf8')
+ if casa.presidente.ult_alteracao
+ else ""
+ )
+ row["telefone_presidente"] = (
+ casa.presidente.nota.encode("utf8")
+ if casa.presidente.nota
+ else ""
+ )
+ row["email_presidente"] = casa.presidente.email.encode(
+ "utf8"
+ )
writer.writerow(row)
return response
+
def openmapdata(request):
- tipos_orgao = request.GET.getlist('tipo_orgao', None)
- tipos_servico = request.GET.getlist('tipo_servico', None)
- tipos_convenio = request.GET.getlist('tipo_convenio', None)
- ufs = request.GET.getlist('uf', None)
- gerentes = request.GET.getlist('gerente', None)
- reptype = request.GET.get('reptype', None)
+ tipos_orgao = request.GET.getlist("tipo_orgao", None)
+ tipos_servico = request.GET.getlist("tipo_servico", None)
+ tipos_convenio = request.GET.getlist("tipo_convenio", None)
+ ufs = request.GET.getlist("uf", None)
+ gerentes = request.GET.getlist("gerente", None)
+ reptype = request.GET.get("reptype", None)
dados = Orgao.objects.all()
@@ -170,8 +242,10 @@ def openmapdata(request):
if "none" in tipos_servico:
dados = dados.filter(servico=None)
else:
- dados = dados.filter(servico__tipo_servico__sigla__in=tipos_servico,
- servico__data_desativacao=None)
+ dados = dados.filter(
+ servico__tipo_servico__sigla__in=tipos_servico,
+ servico__data_desativacao=None,
+ )
if tipos_convenio:
if "none" in tipos_convenio:
@@ -188,48 +262,53 @@ def openmapdata(request):
else:
dados = dados.filter(gerentes_interlegis__id__in=gerentes)
-
if not reptype:
- dados = dados.order_by('nome', 'id').distinct('nome', 'id')
- dados = dados.values_list("id", "nome", "municipio__latitude",
- "municipio__longitude")
+ dados = dados.order_by("nome", "id").distinct("nome", "id")
+ dados = dados.values_list(
+ "id", "nome", "municipio__latitude", "municipio__longitude"
+ )
return JsonResponse(list(dados), safe=False)
else:
- dados = dados.order_by(
- 'municipio__uf__regiao',
- 'municipio__uf__nome',
- 'nome',
- 'id'
- ).distinct(
- 'municipio__uf__regiao',
- 'municipio__uf__nome',
- 'nome',
- 'id'
- ).prefetch_related(
- 'servico_set',
- 'convenio_set',
- 'municipio__uf',
- 'gerentes_interlegis'
+ dados = (
+ dados.order_by(
+ "municipio__uf__regiao", "municipio__uf__nome", "nome", "id"
+ )
+ .distinct(
+ "municipio__uf__regiao", "municipio__uf__nome", "nome", "id"
+ )
+ .prefetch_related(
+ "servico_set",
+ "convenio_set",
+ "municipio__uf",
+ "gerentes_interlegis",
+ )
)
return dados
+
def openmapdetail(request, orgao_id):
orgao = get_object_or_404(Orgao, id=orgao_id)
- return render(request, "metas/openmapdetail.html", {'orgao': orgao})
+ return render(request, "metas/openmapdetail.html", {"orgao": orgao})
+
def openmapsearch(request):
- q = request.GET.get('q', '')
+ q = request.GET.get("q", "")
if len(q) < 3:
- return JsonResponse({'result': 'unsearchable'})
+ return JsonResponse({"result": "unsearchable"})
dados = Orgao.objects.filter(
- tipo__legislativo=True,
- search_text__icontains=to_ascii(q)
+ tipo__legislativo=True, search_text__icontains=to_ascii(q)
)[:10]
- dados = dados.values("id", "nome", "municipio__latitude",
- "municipio__longitude")
- dados = [{'id': d['id'],
- 'label': d['nome'],
- 'lat': d['municipio__latitude'],
- 'lng': d['municipio__longitude']} for d in dados]
+ dados = dados.values(
+ "id", "nome", "municipio__latitude", "municipio__longitude"
+ )
+ dados = [
+ {
+ "id": d["id"],
+ "label": d["nome"],
+ "lat": d["municipio__latitude"],
+ "lng": d["municipio__longitude"],
+ }
+ for d in dados
+ ]
return JsonResponse(list(dados), safe=False)
diff --git a/sigi/apps/ocorrencias/admin.py b/sigi/apps/ocorrencias/admin.py
index b8cbdbf..45015e8 100644
--- a/sigi/apps/ocorrencias/admin.py
+++ b/sigi/apps/ocorrencias/admin.py
@@ -4,8 +4,13 @@ from django.utils.translation import gettext as _
from django.utils.safestring import mark_safe
from sigi.apps.ocorrencias.filters import ServidorRegistroFilter
-from sigi.apps.ocorrencias.models import (Ocorrencia, Comentario, Anexo,
- Categoria, TipoContato)
+from sigi.apps.ocorrencias.models import (
+ Ocorrencia,
+ Comentario,
+ Anexo,
+ Categoria,
+ TipoContato,
+)
from sigi.apps.servidores.models import Servidor
from sigi.apps.utils.base_admin import BaseModelAdmin
from sigi.apps.casas.admin import GerentesInterlegisFilter
@@ -18,54 +23,110 @@ class ComentarioViewInline(admin.TabularInline):
can_delete = False
verbose_name = _("Comentário anterior")
verbose_name_plural = _("Comentários anteriores")
- fields = ('usuario', 'data_criacao', 'novo_status', 'descricao', )
+ fields = (
+ "usuario",
+ "data_criacao",
+ "novo_status",
+ "descricao",
+ )
readonly_fields = fields
+
class ComentarioInline(admin.StackedInline):
model = Comentario
extra = 1
verbose_name = _("Comentário novo")
verbose_name_plural = _("Comentários novos")
- fields = ('novo_status', 'descricao',)
+ fields = (
+ "novo_status",
+ "descricao",
+ )
def get_queryset(self, queryset):
return self.model.objects.none()
+
class AnexosInline(admin.TabularInline):
model = Anexo
extra = 2
- readonly_fields = ['data_pub', ]
+ readonly_fields = [
+ "data_pub",
+ ]
+
@admin.register(Ocorrencia)
class OcorrenciaAdmin(admin.ModelAdmin):
- list_display = ('data_criacao', 'casa_legislativa', 'get_municipio',
- 'get_uf', 'assunto', 'prioridade', 'status',
- 'data_modificacao',)
+ list_display = (
+ "data_criacao",
+ "casa_legislativa",
+ "get_municipio",
+ "get_uf",
+ "assunto",
+ "prioridade",
+ "status",
+ "data_modificacao",
+ )
list_filter = (
- 'status', 'prioridade', 'categoria__nome',
- ('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter),
- ('servidor_registro', ServidorRegistroFilter),
+ "status",
+ "prioridade",
+ "categoria__nome",
+ ("casa_legislativa__gerentes_interlegis", GerentesInterlegisFilter),
+ ("servidor_registro", ServidorRegistroFilter),
)
- search_fields = ('casa_legislativa__search_text', 'assunto',
- 'servidor_registro__nome_completo', 'descricao',
- 'resolucao', 'ticket',)
- date_hierarchy = 'data_criacao'
- fields = ('casa_legislativa', 'categoria', 'tipo_contato', 'assunto',
- 'status', 'prioridade', 'ticket', 'descricao',
- 'servidor_registro', 'resolucao', )
- readonly_fields = ('servidor_registro', )
- inlines = (ComentarioViewInline, ComentarioInline, AnexosInline, )
- autocomplete_fields = ('casa_legislativa', )
+ search_fields = (
+ "casa_legislativa__search_text",
+ "assunto",
+ "servidor_registro__nome_completo",
+ "descricao",
+ "resolucao",
+ "ticket",
+ )
+ date_hierarchy = "data_criacao"
+ fields = (
+ "casa_legislativa",
+ "categoria",
+ "tipo_contato",
+ "assunto",
+ "status",
+ "prioridade",
+ "ticket",
+ "descricao",
+ "servidor_registro",
+ "resolucao",
+ )
+ readonly_fields = ("servidor_registro",)
+ inlines = (
+ ComentarioViewInline,
+ ComentarioInline,
+ AnexosInline,
+ )
+ autocomplete_fields = ("casa_legislativa",)
def get_fieldsets(self, request, obj=None):
if obj is None:
- self.fields = ('casa_legislativa', 'categoria', 'tipo_contato',
- 'assunto', 'prioridade', 'ticket', 'descricao',
- 'resolucao', )
+ self.fields = (
+ "casa_legislativa",
+ "categoria",
+ "tipo_contato",
+ "assunto",
+ "prioridade",
+ "ticket",
+ "descricao",
+ "resolucao",
+ )
else:
- self.fields = ('casa_legislativa', 'categoria', 'tipo_contato',
- 'assunto', 'status', 'prioridade', 'ticket',
- 'descricao', 'servidor_registro', 'resolucao', )
+ self.fields = (
+ "casa_legislativa",
+ "categoria",
+ "tipo_contato",
+ "assunto",
+ "status",
+ "prioridade",
+ "ticket",
+ "descricao",
+ "servidor_registro",
+ "resolucao",
+ )
return super().get_fieldsets(request, obj)
@@ -80,17 +141,21 @@ class OcorrenciaAdmin(admin.ModelAdmin):
if isinstance(instance, Comentario):
instance.usuario = request.user.servidor
instance.save()
- super(OcorrenciaAdmin, self).save_formset(request, form, formset,
- change)
+ super(OcorrenciaAdmin, self).save_formset(
+ request, form, formset, change
+ )
def get_uf(self, obj):
return mark_safe(obj.casa_legislativa.municipio.uf)
- get_uf.short_description = _('UF')
+
+ get_uf.short_description = _("UF")
def get_municipio(self, obj):
return mark_safe(obj.casa_legislativa.municipio.nome)
- get_municipio.short_description = _('Município')
- get_municipio.admin_order_field = 'casa_legislativa__municipio__nome'
+
+ get_municipio.short_description = _("Município")
+ get_municipio.admin_order_field = "casa_legislativa__municipio__nome"
+
admin.site.register(Categoria)
admin.site.register(TipoContato)
diff --git a/sigi/apps/ocorrencias/filters.py b/sigi/apps/ocorrencias/filters.py
index 7d34429..3b04122 100644
--- a/sigi/apps/ocorrencias/filters.py
+++ b/sigi/apps/ocorrencias/filters.py
@@ -7,27 +7,28 @@ class ServidorRegistroFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
servidores = Servidor.objects.exclude(ocorrencia=None).order_by(
- 'nome_completo')
+ "nome_completo"
+ )
self.lookup_choices = [(x.id, x) for x in servidores]
class OcorrenciaListFilter(admin.SimpleListFilter):
- title = _('Relacionadas a Mim')
- parameter_name = 'minhas'
+ title = _("Relacionadas a Mim")
+ parameter_name = "minhas"
def lookups(self, request, model_admin):
if request.user.servidor is None:
return None
return (
- ('M', _('Registrados por mim')),
- ('G', _('Sobre casas que gerencio')),
+ ("M", _("Registrados por mim")),
+ ("G", _("Sobre casas que gerencio")),
)
def queryset(self, request, queryset):
servidor = request.user.servidor
- if self.value() == 'M':
+ if self.value() == "M":
return queryset.filter(servidor_registro=servidor)
- elif self.value() == 'G':
+ elif self.value() == "G":
return queryset.filter(
casa_legislativa__gerentes_interlegis=servidor
)
diff --git a/sigi/apps/ocorrencias/forms.py b/sigi/apps/ocorrencias/forms.py
index 6a6c603..51bddec 100644
--- a/sigi/apps/ocorrencias/forms.py
+++ b/sigi/apps/ocorrencias/forms.py
@@ -10,22 +10,25 @@ from material.admin.widgets import MaterialAdminTextareaWidget
from django.contrib.admin.widgets import AutocompleteSelect
from django.contrib import admin
+
class AjaxSelect(forms.TextInput):
url = ""
+
def __init__(self, url, attrs=None):
super(AjaxSelect, self).__init__(attrs)
self.url = url
def render(self, name, value, attrs=None):
if value is None:
- value = ''
+ value = ""
final_attrs = self.build_attrs(attrs, type=self.input_type)
- code_attrs = self.build_attrs(type='hidden', name=name,
- id='hidden_'+name)
- if value != '':
- final_attrs['value'] = force_str(self._format_value(value))
- result = format_html(' ', flatatt(final_attrs)) + "\n"
- result = result + format_html(' ', flatatt(code_attrs))
+ code_attrs = self.build_attrs(
+ type="hidden", name=name, id="hidden_" + name
+ )
+ if value != "":
+ final_attrs["value"] = force_str(self._format_value(value))
+ result = format_html(" ", flatatt(final_attrs)) + "\n"
+ result = result + format_html(" ", flatatt(code_attrs))
js = """
""" % {'name': name, 'url': self.url}
+ """ % {
+ "name": name,
+ "url": self.url,
+ }
result = result + mark_safe(js)
return result
+
class AnexoForm(forms.ModelForm):
class Meta:
model = Anexo
- fields = ['ocorrencia', 'descricao', 'arquivo',]
- widgets = {'ocorrencia': forms.HiddenInput()}
+ fields = [
+ "ocorrencia",
+ "descricao",
+ "arquivo",
+ ]
+ widgets = {"ocorrencia": forms.HiddenInput()}
+
class ComentarioForm(forms.ModelForm):
class Meta:
model = Comentario
- fields = ['ocorrencia', 'descricao', 'novo_status',]
+ fields = [
+ "ocorrencia",
+ "descricao",
+ "novo_status",
+ ]
widgets = {
- 'ocorrencia': forms.HiddenInput(),
- 'descricao': MaterialAdminTextareaWidget(),
+ "ocorrencia": forms.HiddenInput(),
+ "descricao": MaterialAdminTextareaWidget(),
}
+
class OcorrenciaForm(forms.ModelForm):
class Meta:
model = Ocorrencia
- fields = ['casa_legislativa', 'categoria', 'tipo_contato', 'assunto',
- 'prioridade', 'ticket', 'descricao',]
+ fields = [
+ "casa_legislativa",
+ "categoria",
+ "tipo_contato",
+ "assunto",
+ "prioridade",
+ "ticket",
+ "descricao",
+ ]
widgets = {
- 'casa_legislativa': AutocompleteSelect(
- Ocorrencia.casa_legislativa.field,
- admin.site
+ "casa_legislativa": AutocompleteSelect(
+ Ocorrencia.casa_legislativa.field, admin.site
)
}
# widgets = {
@@ -72,4 +95,4 @@ class OcorrenciaForm(forms.ModelForm):
# url=reverse_lazy('painel-buscacasa'),
# attrs={'size':100}
# ),
- # }
\ No newline at end of file
+ # }
diff --git a/sigi/apps/ocorrencias/migrations/0001_initial.py b/sigi/apps/ocorrencias/migrations/0001_initial.py
index 8a3e8d2..91c25bb 100644
--- a/sigi/apps/ocorrencias/migrations/0001_initial.py
+++ b/sigi/apps/ocorrencias/migrations/0001_initial.py
@@ -7,110 +7,320 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0001_initial'),
- ('servidores', '0001_initial'),
+ ("casas", "0001_initial"),
+ ("servidores", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='Anexo',
+ name="Anexo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('arquivo', models.FileField(upload_to='apps/ocorrencia/anexo/arquivo', max_length=500, verbose_name='Arquivo anexado')),
- ('descricao', models.CharField(max_length='70', verbose_name='descri\xe7\xe3o do anexo')),
- ('data_pub', models.DateTimeField(auto_now_add=True, verbose_name='data da publica\xe7\xe3o do anexo', null=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "arquivo",
+ models.FileField(
+ upload_to="apps/ocorrencia/anexo/arquivo",
+ max_length=500,
+ verbose_name="Arquivo anexado",
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length="70", verbose_name="descri\xe7\xe3o do anexo"
+ ),
+ ),
+ (
+ "data_pub",
+ models.DateTimeField(
+ auto_now_add=True,
+ verbose_name="data da publica\xe7\xe3o do anexo",
+ null=True,
+ ),
+ ),
],
options={
- 'ordering': ('-data_pub',),
- 'verbose_name': 'Anexo',
- 'verbose_name_plural': 'Anexos',
+ "ordering": ("-data_pub",),
+ "verbose_name": "Anexo",
+ "verbose_name_plural": "Anexos",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Categoria',
+ name="Categoria",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=50, verbose_name='Categoria')),
- ('descricao', models.TextField(null=True, verbose_name='descri\xe7\xe3o', blank=True)),
- ('setor_responsavel', models.ForeignKey(verbose_name='Setor respons\xe1vel', to='servidores.Servico', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(max_length=50, verbose_name="Categoria"),
+ ),
+ (
+ "descricao",
+ models.TextField(
+ null=True, verbose_name="descri\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "setor_responsavel",
+ models.ForeignKey(
+ verbose_name="Setor respons\xe1vel",
+ to="servidores.Servico",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'verbose_name': 'Categoria',
- 'verbose_name_plural': 'Categorias',
+ "verbose_name": "Categoria",
+ "verbose_name_plural": "Categorias",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Comentario',
+ name="Comentario",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('data_criacao', models.DateTimeField(auto_now_add=True, verbose_name='Data de cria\xe7\xe3o', null=True)),
- ('descricao', models.TextField(null=True, verbose_name='Descri\xe7\xe3o', blank=True)),
- ('novo_status', models.IntegerField(blank=True, null=True, verbose_name='Novo status', choices=[(1, 'Aberto'), (2, 'Reaberto'), (3, 'Resolvido'), (4, 'Fechado'), (5, 'Duplicado')])),
- ('encaminhar_setor', models.ForeignKey(verbose_name='Encaminhar para setor', blank=True, to='servidores.Servico', null=True, on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "data_criacao",
+ models.DateTimeField(
+ auto_now_add=True,
+ verbose_name="Data de cria\xe7\xe3o",
+ null=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.TextField(
+ null=True, verbose_name="Descri\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "novo_status",
+ models.IntegerField(
+ blank=True,
+ null=True,
+ verbose_name="Novo status",
+ choices=[
+ (1, "Aberto"),
+ (2, "Reaberto"),
+ (3, "Resolvido"),
+ (4, "Fechado"),
+ (5, "Duplicado"),
+ ],
+ ),
+ ),
+ (
+ "encaminhar_setor",
+ models.ForeignKey(
+ verbose_name="Encaminhar para setor",
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Ocorrencia',
+ name="Ocorrencia",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('data_criacao', models.DateField(auto_now_add=True, verbose_name='Data de cria\xe7\xe3o', null=True)),
- ('data_modificacao', models.DateField(auto_now=True, verbose_name='Data de modifica\xe7\xe3o', null=True)),
- ('assunto', models.CharField(max_length=200, verbose_name='Assunto')),
- ('status', models.IntegerField(default=1, verbose_name='Status', choices=[(1, 'Aberto'), (2, 'Reaberto'), (3, 'Resolvido'), (4, 'Fechado'), (5, 'Duplicado')])),
- ('prioridade', models.IntegerField(default=3, verbose_name='Prioridade', choices=[(1, 'Alt\xedssimo'), (2, 'Alto'), (3, 'Normal'), (4, 'Baixo'), (5, 'Baix\xedssimo')])),
- ('descricao', models.TextField(verbose_name='descri\xe7\xe3o', blank=True)),
- ('resolucao', models.TextField(verbose_name='resolu\xe7\xe3o', blank=True)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa', on_delete=models.CASCADE)),
- ('categoria', models.ForeignKey(verbose_name='Categoria', to='ocorrencias.Categoria', on_delete=models.CASCADE)),
- ('servidor_registro', models.ForeignKey(verbose_name='Servidor que registrou a ocorr\xeancia', to='servidores.Servidor', on_delete=models.CASCADE)),
- ('setor_responsavel', models.ForeignKey(verbose_name='Setor respons\xe1vel', to='servidores.Servico', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "data_criacao",
+ models.DateField(
+ auto_now_add=True,
+ verbose_name="Data de cria\xe7\xe3o",
+ null=True,
+ ),
+ ),
+ (
+ "data_modificacao",
+ models.DateField(
+ auto_now=True,
+ verbose_name="Data de modifica\xe7\xe3o",
+ null=True,
+ ),
+ ),
+ (
+ "assunto",
+ models.CharField(max_length=200, verbose_name="Assunto"),
+ ),
+ (
+ "status",
+ models.IntegerField(
+ default=1,
+ verbose_name="Status",
+ choices=[
+ (1, "Aberto"),
+ (2, "Reaberto"),
+ (3, "Resolvido"),
+ (4, "Fechado"),
+ (5, "Duplicado"),
+ ],
+ ),
+ ),
+ (
+ "prioridade",
+ models.IntegerField(
+ default=3,
+ verbose_name="Prioridade",
+ choices=[
+ (1, "Alt\xedssimo"),
+ (2, "Alto"),
+ (3, "Normal"),
+ (4, "Baixo"),
+ (5, "Baix\xedssimo"),
+ ],
+ ),
+ ),
+ (
+ "descricao",
+ models.TextField(
+ verbose_name="descri\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "resolucao",
+ models.TextField(
+ verbose_name="resolu\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "categoria",
+ models.ForeignKey(
+ verbose_name="Categoria",
+ to="ocorrencias.Categoria",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "servidor_registro",
+ models.ForeignKey(
+ verbose_name="Servidor que registrou a ocorr\xeancia",
+ to="servidores.Servidor",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "setor_responsavel",
+ models.ForeignKey(
+ verbose_name="Setor respons\xe1vel",
+ to="servidores.Servico",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ['prioridade', 'data_modificacao', 'data_criacao'],
- 'verbose_name': 'ocorr\xeancia',
- 'verbose_name_plural': 'ocorr\xeancias',
+ "ordering": ["prioridade", "data_modificacao", "data_criacao"],
+ "verbose_name": "ocorr\xeancia",
+ "verbose_name_plural": "ocorr\xeancias",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='TipoContato',
+ name="TipoContato",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('descricao', models.CharField(max_length=50, verbose_name='Descri\xe7\xe3o')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length=50, verbose_name="Descri\xe7\xe3o"
+ ),
+ ),
],
options={
- 'verbose_name': 'Tipo de contato',
- 'verbose_name_plural': 'Tipos de contato',
+ "verbose_name": "Tipo de contato",
+ "verbose_name_plural": "Tipos de contato",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='ocorrencia',
- name='tipo_contato',
- field=models.ForeignKey(verbose_name='Tipo de contato', to='ocorrencias.TipoContato', on_delete=models.CASCADE),
+ model_name="ocorrencia",
+ name="tipo_contato",
+ field=models.ForeignKey(
+ verbose_name="Tipo de contato",
+ to="ocorrencias.TipoContato",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='comentario',
- name='ocorrencia',
- field=models.ForeignKey(verbose_name='Ocorr\xeancia', to='ocorrencias.Ocorrencia', on_delete=models.CASCADE),
+ model_name="comentario",
+ name="ocorrencia",
+ field=models.ForeignKey(
+ verbose_name="Ocorr\xeancia",
+ to="ocorrencias.Ocorrencia",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='comentario',
- name='usuario',
- field=models.ForeignKey(verbose_name='Usu\xe1rio', to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="comentario",
+ name="usuario",
+ field=models.ForeignKey(
+ verbose_name="Usu\xe1rio",
+ to="servidores.Servidor",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='anexo',
- name='ocorrencia',
- field=models.ForeignKey(verbose_name='ocorr\xeancia', to='ocorrencias.Ocorrencia', on_delete=models.CASCADE),
+ model_name="anexo",
+ name="ocorrencia",
+ field=models.ForeignKey(
+ verbose_name="ocorr\xeancia",
+ to="ocorrencias.Ocorrencia",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0002_auto_20160308_0828.py b/sigi/apps/ocorrencias/migrations/0002_auto_20160308_0828.py
index 3ba07ed..765de5d 100644
--- a/sigi/apps/ocorrencias/migrations/0002_auto_20160308_0828.py
+++ b/sigi/apps/ocorrencias/migrations/0002_auto_20160308_0828.py
@@ -7,20 +7,30 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0001_initial'),
+ ("ocorrencias", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='ocorrencia',
- name='ticket',
- field=models.PositiveIntegerField(help_text='N\xfamero do ticket no osTicket', null=True, verbose_name='N\xfamero do ticket', blank=True),
+ model_name="ocorrencia",
+ name="ticket",
+ field=models.PositiveIntegerField(
+ help_text="N\xfamero do ticket no osTicket",
+ null=True,
+ verbose_name="N\xfamero do ticket",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='comentario',
- name='ocorrencia',
- field=models.ForeignKey(related_name='comentarios', verbose_name='Ocorr\xeancia', to='ocorrencias.Ocorrencia', on_delete=models.CASCADE),
+ model_name="comentario",
+ name="ocorrencia",
+ field=models.ForeignKey(
+ related_name="comentarios",
+ verbose_name="Ocorr\xeancia",
+ to="ocorrencias.Ocorrencia",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py b/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py
index e9f05b5..66020f1 100644
--- a/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py
+++ b/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py
@@ -7,15 +7,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0002_auto_20160308_0828'),
- ('casas', '0014_auto_20210406_1945'),
+ ("ocorrencias", "0002_auto_20160308_0828"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='ocorrencia',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="ocorrencia",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0004_auto_20210416_0841.py b/sigi/apps/ocorrencias/migrations/0004_auto_20210416_0841.py
index 54ce623..82e97af 100644
--- a/sigi/apps/ocorrencias/migrations/0004_auto_20210416_0841.py
+++ b/sigi/apps/ocorrencias/migrations/0004_auto_20210416_0841.py
@@ -8,50 +8,80 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0003_auto_20210406_1945'),
+ ("ocorrencias", "0003_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='categoria',
- name='setor_responsavel',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Setor respons\xe1vel', to='servidores.Servico'),
+ model_name="categoria",
+ name="setor_responsavel",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Setor respons\xe1vel",
+ to="servidores.Servico",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='comentario',
- name='encaminhar_setor',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Encaminhar para setor', blank=True, to='servidores.Servico', null=True),
+ model_name="comentario",
+ name="encaminhar_setor",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Encaminhar para setor",
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='comentario',
- name='usuario',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Usu\xe1rio', to='servidores.Servidor'),
+ model_name="comentario",
+ name="usuario",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Usu\xe1rio",
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='ocorrencia',
- name='categoria',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Categoria', to='ocorrencias.Categoria'),
+ model_name="ocorrencia",
+ name="categoria",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Categoria",
+ to="ocorrencias.Categoria",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='ocorrencia',
- name='servidor_registro',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Servidor que registrou a ocorr\xeancia', to='servidores.Servidor'),
+ model_name="ocorrencia",
+ name="servidor_registro",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Servidor que registrou a ocorr\xeancia",
+ to="servidores.Servidor",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='ocorrencia',
- name='setor_responsavel',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Setor respons\xe1vel', to='servidores.Servico'),
+ model_name="ocorrencia",
+ name="setor_responsavel",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Setor respons\xe1vel",
+ to="servidores.Servico",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='ocorrencia',
- name='tipo_contato',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo de contato', to='ocorrencias.TipoContato'),
+ model_name="ocorrencia",
+ name="tipo_contato",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Tipo de contato",
+ to="ocorrencias.TipoContato",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0005_auto_20210611_0946.py b/sigi/apps/ocorrencias/migrations/0005_auto_20210611_0946.py
index 9177578..64dcb3b 100644
--- a/sigi/apps/ocorrencias/migrations/0005_auto_20210611_0946.py
+++ b/sigi/apps/ocorrencias/migrations/0005_auto_20210611_0946.py
@@ -7,12 +7,16 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0004_auto_20210416_0841'),
+ ("ocorrencias", "0004_auto_20210416_0841"),
]
operations = [
migrations.AlterModelOptions(
- name='categoria',
- options={'ordering': ('nome',), 'verbose_name': 'Categoria', 'verbose_name_plural': 'Categorias'},
+ name="categoria",
+ options={
+ "ordering": ("nome",),
+ "verbose_name": "Categoria",
+ "verbose_name_plural": "Categorias",
+ },
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0006_alter_anexo_arquivo_alter_anexo_descricao_and_more.py b/sigi/apps/ocorrencias/migrations/0006_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
index 024cb0f..67bd3a8 100644
--- a/sigi/apps/ocorrencias/migrations/0006_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
+++ b/sigi/apps/ocorrencias/migrations/0006_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
@@ -6,43 +6,74 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0005_auto_20210611_0946'),
+ ("ocorrencias", "0005_auto_20210611_0946"),
]
operations = [
migrations.AlterField(
- model_name='anexo',
- name='arquivo',
- field=models.FileField(max_length=500, upload_to='apps/ocorrencia/anexo/arquivo', verbose_name='Arquivo anexado'),
+ model_name="anexo",
+ name="arquivo",
+ field=models.FileField(
+ max_length=500,
+ upload_to="apps/ocorrencia/anexo/arquivo",
+ verbose_name="Arquivo anexado",
+ ),
),
migrations.AlterField(
- model_name='anexo',
- name='descricao',
- field=models.CharField(max_length=70, verbose_name='descrição do anexo'),
+ model_name="anexo",
+ name="descricao",
+ field=models.CharField(
+ max_length=70, verbose_name="descrição do anexo"
+ ),
),
migrations.AlterField(
- model_name='anexo',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="anexo",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='categoria',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="categoria",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='comentario',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="comentario",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='ocorrencia',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="ocorrencia",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='tipocontato',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="tipocontato",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0007_remove_comentario_encaminhar_setor_and_more.py b/sigi/apps/ocorrencias/migrations/0007_remove_comentario_encaminhar_setor_and_more.py
index 317718a..53f4876 100644
--- a/sigi/apps/ocorrencias/migrations/0007_remove_comentario_encaminhar_setor_and_more.py
+++ b/sigi/apps/ocorrencias/migrations/0007_remove_comentario_encaminhar_setor_and_more.py
@@ -6,16 +6,19 @@ from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0006_alter_anexo_arquivo_alter_anexo_descricao_and_more'),
+ (
+ "ocorrencias",
+ "0006_alter_anexo_arquivo_alter_anexo_descricao_and_more",
+ ),
]
operations = [
migrations.RemoveField(
- model_name='comentario',
- name='encaminhar_setor',
+ model_name="comentario",
+ name="encaminhar_setor",
),
migrations.RemoveField(
- model_name='ocorrencia',
- name='setor_responsavel',
+ model_name="ocorrencia",
+ name="setor_responsavel",
),
]
diff --git a/sigi/apps/ocorrencias/migrations/0008_remove_categoria_setor_responsavel.py b/sigi/apps/ocorrencias/migrations/0008_remove_categoria_setor_responsavel.py
index 61fba3e..359c089 100644
--- a/sigi/apps/ocorrencias/migrations/0008_remove_categoria_setor_responsavel.py
+++ b/sigi/apps/ocorrencias/migrations/0008_remove_categoria_setor_responsavel.py
@@ -6,12 +6,12 @@ from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
- ('ocorrencias', '0007_remove_comentario_encaminhar_setor_and_more'),
+ ("ocorrencias", "0007_remove_comentario_encaminhar_setor_and_more"),
]
operations = [
migrations.RemoveField(
- model_name='categoria',
- name='setor_responsavel',
+ model_name="categoria",
+ name="setor_responsavel",
),
]
diff --git a/sigi/apps/ocorrencias/models.py b/sigi/apps/ocorrencias/models.py
index ea1e641..b6e369a 100644
--- a/sigi/apps/ocorrencias/models.py
+++ b/sigi/apps/ocorrencias/models.py
@@ -7,16 +7,17 @@ from django.utils.safestring import mark_safe
class Categoria(models.Model):
nome = models.CharField(_("Categoria"), max_length=50)
- descricao = models.TextField(_('descrição'), blank=True, null=True)
+ descricao = models.TextField(_("descrição"), blank=True, null=True)
class Meta:
- verbose_name = _('Categoria')
- verbose_name_plural = _('Categorias')
- ordering = ('nome',)
+ verbose_name = _("Categoria")
+ verbose_name_plural = _("Categorias")
+ ordering = ("nome",)
def __str__(self):
return self.nome
+
class TipoContato(models.Model):
descricao = models.CharField(_("Descrição"), max_length=50)
@@ -27,125 +28,125 @@ class TipoContato(models.Model):
def __str__(self):
return self.descricao
+
class Ocorrencia(models.Model):
- STATUS_ABERTO = 1
- STATUS_REABERTO = 2
+ STATUS_ABERTO = 1
+ STATUS_REABERTO = 2
STATUS_RESOLVIDO = 3
- STATUS_FECHADO = 4
+ STATUS_FECHADO = 4
STATUS_DUPLICADO = 5
STATUS_CHOICES = (
- (STATUS_ABERTO , _('Aberto')),
- (STATUS_REABERTO , _('Reaberto')),
- (STATUS_RESOLVIDO, _('Resolvido')),
- (STATUS_FECHADO , _('Fechado')),
- (STATUS_DUPLICADO, _('Duplicado')),
+ (STATUS_ABERTO, _("Aberto")),
+ (STATUS_REABERTO, _("Reaberto")),
+ (STATUS_RESOLVIDO, _("Resolvido")),
+ (STATUS_FECHADO, _("Fechado")),
+ (STATUS_DUPLICADO, _("Duplicado")),
)
PRIORITY_CHOICES = (
- (1, _('Altíssimo')),
- (2, _('Alto')),
- (3, _('Normal')),
- (4, _('Baixo')),
- (5, _('Baixíssimo')),
+ (1, _("Altíssimo")),
+ (2, _("Alto")),
+ (3, _("Normal")),
+ (4, _("Baixo")),
+ (5, _("Baixíssimo")),
)
casa_legislativa = models.ForeignKey(
- 'casas.Orgao',
+ "casas.Orgao",
on_delete=models.CASCADE,
- verbose_name=_('Casa Legislativa')
+ verbose_name=_("Casa Legislativa"),
)
data_criacao = models.DateField(
- _('Data de criação'),
- null=True,
- blank=True,
- auto_now_add=True
+ _("Data de criação"), null=True, blank=True, auto_now_add=True
)
data_modificacao = models.DateField(
- _('Data de modificação'),
- null=True,
- blank=True,
- auto_now=True
+ _("Data de modificação"), null=True, blank=True, auto_now=True
)
categoria = models.ForeignKey(
- Categoria,
- on_delete=models.PROTECT,
- verbose_name=_('Categoria')
+ Categoria, on_delete=models.PROTECT, verbose_name=_("Categoria")
)
tipo_contato = models.ForeignKey(
- TipoContato,
- on_delete=models.PROTECT,
- verbose_name=_("Tipo de contato")
- )
- assunto = models.CharField(_('Assunto'), max_length=200)
- status = models.IntegerField(
- _('Status'),
- choices=STATUS_CHOICES,
- default=1
+ TipoContato, on_delete=models.PROTECT, verbose_name=_("Tipo de contato")
)
+ assunto = models.CharField(_("Assunto"), max_length=200)
+ status = models.IntegerField(_("Status"), choices=STATUS_CHOICES, default=1)
prioridade = models.IntegerField(
- _('Prioridade'),
- choices=PRIORITY_CHOICES,
- default=3
+ _("Prioridade"), choices=PRIORITY_CHOICES, default=3
+ )
+ descricao = models.TextField(
+ _("descrição"),
+ blank=True,
+ )
+ resolucao = models.TextField(
+ _("resolução"),
+ blank=True,
)
- descricao = models.TextField(_('descrição'), blank=True,)
- resolucao = models.TextField(_('resolução'), blank=True,)
servidor_registro = models.ForeignKey(
- 'servidores.Servidor',
+ "servidores.Servidor",
on_delete=models.PROTECT,
- verbose_name=_("Servidor que registrou a ocorrência")
+ verbose_name=_("Servidor que registrou a ocorrência"),
)
ticket = models.PositiveIntegerField(
- _('Número do ticket'),
+ _("Número do ticket"),
blank=True,
null=True,
- help_text=_("Número do ticket no osTicket")
+ help_text=_("Número do ticket no osTicket"),
)
class Meta:
- verbose_name = _('ocorrência')
- verbose_name_plural = _('ocorrências')
- ordering = ['prioridade', 'data_modificacao', 'data_criacao', ]
+ verbose_name = _("ocorrência")
+ verbose_name_plural = _("ocorrências")
+ ordering = [
+ "prioridade",
+ "data_modificacao",
+ "data_criacao",
+ ]
def __str__(self):
return _(f"{self.casa_legislativa}: {self.assunto}")
def clean(self):
- if (self.ticket is not None
- and Ocorrencia.objects.exclude(pk=self.pk).filter(
- ticket=self.ticket).exists()
+ if (
+ self.ticket is not None
+ and Ocorrencia.objects.exclude(pk=self.pk)
+ .filter(ticket=self.ticket)
+ .exists()
):
- raise ValidationError({'ticket': _("Já existe ocorrência "
- "registrada para este ticket")})
+ raise ValidationError(
+ {
+ "ticket": _(
+ "Já existe ocorrência " "registrada para este ticket"
+ )
+ }
+ )
return super(Ocorrencia, self).clean()
def get_ticket_url(self):
return mark_safe(settings.OSTICKET_URL % self.ticket)
+
class Comentario(models.Model):
ocorrencia = models.ForeignKey(
Ocorrencia,
on_delete=models.CASCADE,
- verbose_name=_('Ocorrência'),
- related_name='comentarios'
+ verbose_name=_("Ocorrência"),
+ related_name="comentarios",
)
data_criacao = models.DateTimeField(
- _('Data de criação'),
- null=True,
- blank=True,
- auto_now_add=True
+ _("Data de criação"), null=True, blank=True, auto_now_add=True
)
- descricao = models.TextField(_('Descrição'), blank=True, null=True)
+ descricao = models.TextField(_("Descrição"), blank=True, null=True)
usuario = models.ForeignKey(
- 'servidores.Servidor',
+ "servidores.Servidor",
on_delete=models.PROTECT,
- verbose_name=_('Usuário')
+ verbose_name=_("Usuário"),
)
novo_status = models.IntegerField(
- _('Novo status'),
+ _("Novo status"),
choices=Ocorrencia.STATUS_CHOICES,
blank=True,
- null=True
+ null=True,
)
def save(self, *args, **kwargs):
@@ -154,32 +155,28 @@ class Comentario(models.Model):
self.ocorrencia.save()
super(Comentario, self).save(*args, **kwargs)
+
class Anexo(models.Model):
ocorrencia = models.ForeignKey(
- Ocorrencia,
- on_delete=models.CASCADE,
- verbose_name=_('ocorrência')
+ Ocorrencia, on_delete=models.CASCADE, verbose_name=_("ocorrência")
)
arquivo = models.FileField(
- _('Arquivo anexado'),
- upload_to='apps/ocorrencia/anexo/arquivo',
- max_length=500
- )
- descricao = models.CharField(
- _('descrição do anexo'),
- max_length=70
+ _("Arquivo anexado"),
+ upload_to="apps/ocorrencia/anexo/arquivo",
+ max_length=500,
)
+ descricao = models.CharField(_("descrição do anexo"), max_length=70)
data_pub = models.DateTimeField(
- _('data da publicação do anexo'),
+ _("data da publicação do anexo"),
null=True,
blank=True,
- auto_now_add=True
+ auto_now_add=True,
)
class Meta:
- ordering = ('-data_pub',)
- verbose_name = _('Anexo')
- verbose_name_plural =_('Anexos')
+ ordering = ("-data_pub",)
+ verbose_name = _("Anexo")
+ verbose_name_plural = _("Anexos")
def __str__(self):
return _(f"{self.arquivo.name}: {self.descricao}")
diff --git a/sigi/apps/ocorrencias/urls.py b/sigi/apps/ocorrencias/urls.py
index 6398686..25fcefc 100644
--- a/sigi/apps/ocorrencias/urls.py
+++ b/sigi/apps/ocorrencias/urls.py
@@ -2,13 +2,10 @@ from django.urls import path
from sigi.apps.ocorrencias.views import painel_ocorrencias
urlpatterns = [
- path('painel/', painel_ocorrencias, name='painel-ocorrencias'),
+ path("painel/", painel_ocorrencias, name="painel-ocorrencias"),
]
-
-
-
# # coding: utf-8
# from django.conf.urls import patterns, url
diff --git a/sigi/apps/ocorrencias/views.py b/sigi/apps/ocorrencias/views.py
index 81db03a..77473ad 100644
--- a/sigi/apps/ocorrencias/views.py
+++ b/sigi/apps/ocorrencias/views.py
@@ -12,20 +12,25 @@ from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.servidores.models import Servidor, Servico
from sigi.apps.ocorrencias.models import Ocorrencia, Anexo
-from sigi.apps.ocorrencias.forms import AnexoForm, ComentarioForm, OcorrenciaForm
+from sigi.apps.ocorrencias.forms import (
+ AnexoForm,
+ ComentarioForm,
+ OcorrenciaForm,
+)
from django.utils.html import escape
+
@login_required
def painel_ocorrencias(request):
- painel = request.GET.get('painel', None)
- id_servidor = request.GET.get('servidor', None)
- id_casa = request.GET.get('casa', None)
- page = int(request.GET.get('page', '0'))
+ painel = request.GET.get("painel", None)
+ id_servidor = request.GET.get("servidor", None)
+ id_casa = request.GET.get("casa", None)
+ page = int(request.GET.get("page", "0"))
paineis = {
- 'gerente': _("Casas que gerencio"),
- 'registro': _("Ocorrências registrados por mim"),
- 'tudo': _("Todas as ocorrências")
+ "gerente": _("Casas que gerencio"),
+ "registro": _("Ocorrências registrados por mim"),
+ "tudo": _("Todas as ocorrências"),
}
if id_servidor is None:
@@ -35,168 +40,233 @@ def painel_ocorrencias(request):
if id_casa is not None:
casa = get_object_or_404(Orgao, id=id_casa)
- painel = 'tudo'
+ painel = "tudo"
panel_title = _(f"Ocorrências da {casa.nome}, {casa.municipio.uf.nome}")
else:
casa = None
if servidor:
is_gerente = servidor.casas_que_gerencia.exists()
- is_registrador = (servidor.ocorrencia_set.exists() or
- servidor.comentario_set.exists())
+ is_registrador = (
+ servidor.ocorrencia_set.exists()
+ or servidor.comentario_set.exists()
+ )
panel_title = servidor.nome_completo
else:
is_gerente = False
is_registrador = False
- panel_title = _('Todas as ocorrências')
+ panel_title = _("Todas as ocorrências")
if (servidor is None) or (not is_gerente and not is_registrador):
- painel = 'tudo'
+ painel = "tudo"
elif not is_gerente and is_registrador:
- painel = 'registro'
+ painel = "registro"
elif is_gerente:
if painel is None:
- painel = 'gerente'
+ painel = "gerente"
- if painel == 'gerente':
+ if painel == "gerente":
ocorrencias = Ocorrencia.objects.filter(
- casa_legislativa__gerentes_interlegis=servidor)
- elif painel == 'registro':
- ocorrencias = (
- Ocorrencia.objects.filter(servidor_registro=servidor) |
- Ocorrencia.objects.filter(comentarios__usuario=servidor)
+ casa_legislativa__gerentes_interlegis=servidor
)
- else: # Tudo...
- if casa is None: # ...de todas as Casas...
+ elif painel == "registro":
+ ocorrencias = Ocorrencia.objects.filter(
+ servidor_registro=servidor
+ ) | Ocorrencia.objects.filter(comentarios__usuario=servidor)
+ else: # Tudo...
+ if casa is None: # ...de todas as Casas...
ocorrencias = Ocorrencia.objects.all()
- else: # ... ou da Casa escolhida
+ else: # ... ou da Casa escolhida
ocorrencias = casa.ocorrencia_set.all()
ocorrencias = ocorrencias.filter(status__in=[1, 2])
- ocorrencias = ocorrencias.order_by('prioridade', '-data_modificacao')
+ ocorrencias = ocorrencias.order_by("prioridade", "-data_modificacao")
ocorrencias = ocorrencias.select_related(
- 'casa_legislativa', 'casa_legislativa__municipio',
- 'casa_legislativa__municipio__uf', 'categoria', 'tipo_contato',
- 'servidor_registro',
+ "casa_legislativa",
+ "casa_legislativa__municipio",
+ "casa_legislativa__municipio__uf",
+ "categoria",
+ "tipo_contato",
+ "servidor_registro",
)
ocorrencias = ocorrencias.prefetch_related(
- 'comentarios', 'comentarios__usuario', 'anexo_set',
- 'casa_legislativa__gerentes_interlegis'
+ "comentarios",
+ "comentarios__usuario",
+ "anexo_set",
+ "casa_legislativa__gerentes_interlegis",
)
- ocorrencias = ocorrencias.annotate(total_anexos=Count('anexo'))
+ ocorrencias = ocorrencias.annotate(total_anexos=Count("anexo"))
if page * 100 > ocorrencias.count():
ocorrencias = ocorrencias[-100]
else:
- ocorrencias = ocorrencias[page * 100:page * 100 + 100]
-
+ ocorrencias = ocorrencias[page * 100 : page * 100 + 100]
context = {
- 'paineis': paineis,
- 'painel': painel,
- 'servidor': servidor,
- 'casa': casa,
- 'ocorrencias': ocorrencias,
- 'panel_title': panel_title,
- 'comentario_form': ComentarioForm(),
- 'ocorrencia_form': OcorrenciaForm(),
- 'PRIORITY_CHOICES': Ocorrencia.PRIORITY_CHOICES
+ "paineis": paineis,
+ "painel": painel,
+ "servidor": servidor,
+ "casa": casa,
+ "ocorrencias": ocorrencias,
+ "panel_title": panel_title,
+ "comentario_form": ComentarioForm(),
+ "ocorrencia_form": OcorrenciaForm(),
+ "PRIORITY_CHOICES": Ocorrencia.PRIORITY_CHOICES,
}
- return render(request, 'ocorrencias/painel.html', context)
+ return render(request, "ocorrencias/painel.html", context)
+
@login_required
def busca_nominal(request, origin="tudo"):
- term = request.GET.get('term', None)
+ term = request.GET.get("term", None)
if term is None:
- return JsonResponse([{'label': _('Erro na pesquisa por termo'), 'value': 'type=error'}], safe=False)
+ return JsonResponse(
+ [{"label": _("Erro na pesquisa por termo"), "value": "type=error"}],
+ safe=False,
+ )
data = []
if origin == "casa" or origin == "tudo":
- casas = Orgao.objects.filter(search_text__icontains=to_ascii(term)).select_related('municipio', 'municipio__uf')[:10]
- data += [{'value': c.pk, 'label': "%s, %s" % (c.nome, c.municipio.uf.sigla,), 'origin': 'casa'} for c in casas]
+ casas = Orgao.objects.filter(
+ search_text__icontains=to_ascii(term)
+ ).select_related("municipio", "municipio__uf")[:10]
+ data += [
+ {
+ "value": c.pk,
+ "label": "%s, %s"
+ % (
+ c.nome,
+ c.municipio.uf.sigla,
+ ),
+ "origin": "casa",
+ }
+ for c in casas
+ ]
if origin == "servidor" or origin == "tudo":
servidores = Servidor.objects.filter(nome_completo__icontains=term)[:10]
- data += [{'value': s.pk, 'label': s.nome_completo, 'origin': 'servidor'} for s in servidores]
+ data += [
+ {"value": s.pk, "label": s.nome_completo, "origin": "servidor"}
+ for s in servidores
+ ]
if origin == "servico" or origin == "tudo":
- setores = Servico.objects.filter(nome__icontains=term) | Servico.objects.filter(sigla__icontains=term)
+ setores = Servico.objects.filter(
+ nome__icontains=term
+ ) | Servico.objects.filter(sigla__icontains=term)
setores = setores[:10]
- data += [{'value': s.pk, 'label': '%s - %s' % (s.sigla, s.nome), 'origin': 'servico'} for s in setores]
+ data += [
+ {
+ "value": s.pk,
+ "label": "%s - %s" % (s.sigla, s.nome),
+ "origin": "servico",
+ }
+ for s in setores
+ ]
- data = sorted(data, key=lambda d: d['label'])
+ data = sorted(data, key=lambda d: d["label"])
return JsonResponse(data, safe=False)
+
@login_required
@require_POST
def muda_prioridade(request):
- id_ocorrencia = request.POST.get('id_ocorrencia', None)
- prioridade = request.POST.get('prioridade', None)
+ id_ocorrencia = request.POST.get("id_ocorrencia", None)
+ prioridade = request.POST.get("prioridade", None)
if id_ocorrencia is None or prioridade is None:
- return JsonResponse({'result': 'error', 'message': _('Erro nos parâmetros')})
+ return JsonResponse(
+ {"result": "error", "message": _("Erro nos parâmetros")}
+ )
if not any([int(prioridade) == p[0] for p in Ocorrencia.PRIORITY_CHOICES]):
- return JsonResponse({'result': 'error', 'message': _('Valor de prioridade não aceito')})
+ return JsonResponse(
+ {"result": "error", "message": _("Valor de prioridade não aceito")}
+ )
try:
ocorrencia = Ocorrencia.objects.get(pk=id_ocorrencia)
except Exception as e:
- return JsonResponse({'result': 'error', 'message': str(e)})
+ return JsonResponse({"result": "error", "message": str(e)})
ocorrencia.prioridade = prioridade
ocorrencia.save()
- return JsonResponse({'result': 'success', 'message': _('Prioridade alterada')})
+ return JsonResponse(
+ {"result": "success", "message": _("Prioridade alterada")}
+ )
+
@login_required
def exclui_anexo(request):
- anexo_id = request.GET.get('anexo_id', None)
+ anexo_id = request.GET.get("anexo_id", None)
if anexo_id is None:
- return JsonResponse({'result': 'error', 'message': _('Erro nos parâmetros')})
+ return JsonResponse(
+ {"result": "error", "message": _("Erro nos parâmetros")}
+ )
try:
anexo = Anexo.objects.get(pk=anexo_id)
except Exception as e:
- return JsonResponse({'result': 'error', 'message': str(e)})
+ return JsonResponse({"result": "error", "message": str(e)})
ocorrencia = anexo.ocorrencia
anexo.delete()
- link_label = (ngettext('%s arquivo anexo', '%s arquivos anexos', ocorrencia.anexo_set.count()) %
- (ocorrencia.anexo_set.count(),))
+ link_label = ngettext(
+ "%s arquivo anexo", "%s arquivos anexos", ocorrencia.anexo_set.count()
+ ) % (ocorrencia.anexo_set.count(),)
- painel = render_to_string('ocorrencias/anexos_snippet.html', {'ocorrencia': ocorrencia},
- context_instance=RequestContext(request))
+ painel = render_to_string(
+ "ocorrencias/anexos_snippet.html",
+ {"ocorrencia": ocorrencia},
+ context_instance=RequestContext(request),
+ )
+
+ return JsonResponse(
+ {
+ "result": "success",
+ "message": _("Anexo %s excluído com sucesso" % (anexo_id,)),
+ "link_label": link_label,
+ "anexos_panel": painel,
+ }
+ )
- return JsonResponse({'result': 'success', 'message': _('Anexo %s excluído com sucesso' % (anexo_id,)),
- 'link_label': link_label, 'anexos_panel': painel})
@login_required
def inclui_anexo(request):
- if request.method == 'POST':
+ if request.method == "POST":
form = AnexoForm(request.POST, request.FILES)
if form.is_valid():
anexo = form.save()
- return HttpResponse('' %
- escape(anexo.ocorrencia_id))
+ return HttpResponse(
+ ''
+ % escape(anexo.ocorrencia_id)
+ )
else:
ocorrencia = form.instance.ocorrencia
else:
- ocorrencia_id = request.GET.get('ocorrencia_id', None)
+ ocorrencia_id = request.GET.get("ocorrencia_id", None)
ocorrencia = get_object_or_404(Ocorrencia, pk=ocorrencia_id)
form = AnexoForm(instance=Anexo(ocorrencia=ocorrencia))
- return render(request, 'ocorrencias/anexo_form.html',
- {'form': form, 'ocorrencia': ocorrencia, 'is_popup': True})
+ return render(
+ request,
+ "ocorrencias/anexo_form.html",
+ {"form": form, "ocorrencia": ocorrencia, "is_popup": True},
+ )
+
@login_required
def anexo_snippet(request):
- ocorrencia_id = request.GET.get('ocorrencia_id', None)
+ ocorrencia_id = request.GET.get("ocorrencia_id", None)
ocorrencia = get_object_or_404(Ocorrencia, pk=ocorrencia_id)
- return render(request, 'ocorrencias/anexos_snippet.html', {'ocorrencia': ocorrencia})
+ return render(
+ request, "ocorrencias/anexos_snippet.html", {"ocorrencia": ocorrencia}
+ )
+
@login_required
@require_POST
@@ -211,10 +281,19 @@ def inclui_comentario(request):
else:
ocorrencia = form.instance.ocorrencia
- painel = render_to_string('ocorrencias/ocorrencia_snippet.html', {'ocorrencia': ocorrencia,
- 'comentario_form': form,}, context_instance=RequestContext(request))
+ painel = render_to_string(
+ "ocorrencias/ocorrencia_snippet.html",
+ {
+ "ocorrencia": ocorrencia,
+ "comentario_form": form,
+ },
+ context_instance=RequestContext(request),
+ )
+
+ return JsonResponse(
+ {"ocorrencia_id": ocorrencia.id, "ocorrencia_panel": painel}
+ )
- return JsonResponse({'ocorrencia_id': ocorrencia.id, 'ocorrencia_panel': painel})
@login_required
@require_POST
@@ -228,16 +307,23 @@ def inclui_ocorrencia(request):
ocorrencia.servidor_registro = Servidor.objects.get(user=request.user)
ocorrencia.save()
form = OcorrenciaForm()
- data['result'] = 'success'
- data['ocorrencia_panel'] = render_to_string('ocorrencias/ocorrencia_snippet.html',
- {'ocorrencia': ocorrencia, 'comentario_form': ComentarioForm(),
- 'PRIORITY_CHOICES': Ocorrencia.PRIORITY_CHOICES},
- context_instance=RequestContext(request))
+ data["result"] = "success"
+ data["ocorrencia_panel"] = render_to_string(
+ "ocorrencias/ocorrencia_snippet.html",
+ {
+ "ocorrencia": ocorrencia,
+ "comentario_form": ComentarioForm(),
+ "PRIORITY_CHOICES": Ocorrencia.PRIORITY_CHOICES,
+ },
+ context_instance=RequestContext(request),
+ )
else:
- data['result'] = 'error'
+ data["result"] = "error"
- data['ocorrencia_form'] = render_to_string('ocorrencias/ocorrencia_form.html',
- {'ocorrencia_form': form},
- context_instance=RequestContext(request))
+ data["ocorrencia_form"] = render_to_string(
+ "ocorrencias/ocorrencia_form.html",
+ {"ocorrencia_form": form},
+ context_instance=RequestContext(request),
+ )
- return JsonResponse(data)
\ No newline at end of file
+ return JsonResponse(data)
diff --git a/sigi/apps/parlamentares/admin.py b/sigi/apps/parlamentares/admin.py
index 886dcd5..5381490 100644
--- a/sigi/apps/parlamentares/admin.py
+++ b/sigi/apps/parlamentares/admin.py
@@ -7,8 +7,17 @@ from django.utils.translation import gettext as _
from sigi.apps.contatos.models import Telefone
from sigi.apps.parlamentares.models import (
- Partido, Parlamentar, Mandato, Legislatura, Coligacao, ComposicaoColigacao,
- SessaoLegislativa, MesaDiretora, Cargo, MembroMesaDiretora)
+ Partido,
+ Parlamentar,
+ Mandato,
+ Legislatura,
+ Coligacao,
+ ComposicaoColigacao,
+ SessaoLegislativa,
+ MesaDiretora,
+ Cargo,
+ MembroMesaDiretora,
+)
from sigi.apps.parlamentares.views import adicionar_parlamentar_carrinho
from sigi.apps.utils.base_admin import BaseModelAdmin
from sigi.apps.utils.filters import AlphabeticFilter
@@ -17,7 +26,7 @@ from sigi.apps.utils.filters import AlphabeticFilter
class MandatosInline(admin.TabularInline):
model = Mandato
extra = 1
- raw_id_fields = ('legislatura', 'partido')
+ raw_id_fields = ("legislatura", "partido")
class TelefonesInline(generic.GenericTabularInline):
@@ -26,159 +35,222 @@ class TelefonesInline(generic.GenericTabularInline):
class PartidoAdmin(BaseModelAdmin):
- list_display = ('nome', 'sigla')
- list_display_links = ('nome', 'sigla')
- search_fields = ('nome', 'sigla')
+ list_display = ("nome", "sigla")
+ list_display_links = ("nome", "sigla")
+ search_fields = ("nome", "sigla")
class ParlamentarNomeCompletoFilter(AlphabeticFilter):
- title = _('Inicial do Nome Completo')
- parameter_name = 'nome_completo'
+ title = _("Inicial do Nome Completo")
+ parameter_name = "nome_completo"
class ParlamentarAdmin(BaseModelAdmin):
inlines = (TelefonesInline, MandatosInline)
- list_display = ('nome_completo', 'nome_parlamentar', 'sexo')
- list_display_links = ('nome_completo', 'nome_parlamentar')
- list_filter = (ParlamentarNomeCompletoFilter, )
- actions = ['adiciona_parlamentar', ]
+ list_display = ("nome_completo", "nome_parlamentar", "sexo")
+ list_display_links = ("nome_completo", "nome_parlamentar")
+ list_filter = (ParlamentarNomeCompletoFilter,)
+ actions = [
+ "adiciona_parlamentar",
+ ]
fieldsets = (
- (None, {
- 'fields': ('nome_completo', 'nome_parlamentar', 'sexo'),
- }),
+ (
+ None,
+ {
+ "fields": ("nome_completo", "nome_parlamentar", "sexo"),
+ },
+ ),
# (_('Endereço'), {
# 'fields': ('logradouro', 'bairro', 'municipio', 'cep'),
# }),
- (_('Outras informações'), {
- 'fields': ('data_nascimento', 'email', 'pagina_web', 'foto'),
- }),
+ (
+ _("Outras informações"),
+ {
+ "fields": ("data_nascimento", "email", "pagina_web", "foto"),
+ },
+ ),
+ )
+ radio_fields = {"sexo": admin.VERTICAL}
+ # raw_id_fields = ('municipio',)
+ search_fields = (
+ "nome_completo",
+ "nome_parlamentar",
+ "email",
+ "pagina_web",
)
- radio_fields = {'sexo': admin.VERTICAL}
-# raw_id_fields = ('municipio',)
- search_fields = ('nome_completo', 'nome_parlamentar', 'email',
- 'pagina_web',)
def adiciona_parlamentar(self, request, queryset):
- if 'carrinho_parlametar' in request.session:
- q1 = len(request.session['carrinho_parlamentar'])
+ if "carrinho_parlametar" in request.session:
+ q1 = len(request.session["carrinho_parlamentar"])
else:
q1 = 0
adicionar_parlamentar_carrinho(request, queryset=queryset)
- q2 = len(request.session['carrinho_parlamentar'])
+ q2 = len(request.session["carrinho_parlamentar"])
quant = q2 - q1
if quant:
- self.message_user(request, _("%s Parlamentares adicionados no carrinho") % (quant))
+ self.message_user(
+ request, _("%s Parlamentares adicionados no carrinho") % (quant)
+ )
else:
- self.message_user(request, _("Os parlamentares selecionadas já foram adicionadas anteriormente"))
- return HttpResponseRedirect('.')
-
- adiciona_parlamentar.short_description = _("Armazenar parlamentar no carrinho para exportar")
+ self.message_user(
+ request,
+ _(
+ "Os parlamentares selecionadas já foram adicionadas anteriormente"
+ ),
+ )
+ return HttpResponseRedirect(".")
+
+ adiciona_parlamentar.short_description = _(
+ "Armazenar parlamentar no carrinho para exportar"
+ )
class MandatoAdmin(BaseModelAdmin):
- list_display = ('parlamentar', 'legislatura', 'partido',
- 'inicio_mandato', 'fim_mandato', 'is_afastado')
- list_filter = ('is_afastado', 'partido')
- search_fields = ('legislatura__numero', 'parlamentar__nome_completo',
- 'parlamentar__nome_parlamentar', 'partido__nome',
- 'partido__sigla')
- raw_id_fields = ('parlamentar', 'legislatura', 'partido')
+ list_display = (
+ "parlamentar",
+ "legislatura",
+ "partido",
+ "inicio_mandato",
+ "fim_mandato",
+ "is_afastado",
+ )
+ list_filter = ("is_afastado", "partido")
+ search_fields = (
+ "legislatura__numero",
+ "parlamentar__nome_completo",
+ "parlamentar__nome_parlamentar",
+ "partido__nome",
+ "partido__sigla",
+ )
+ raw_id_fields = ("parlamentar", "legislatura", "partido")
+
+
# radio_fields = {'suplencia': admin.VERTICAL}
class MandatoInline(admin.TabularInline):
model = Mandato
- raw_id_fields = ['parlamentar', ]
+ raw_id_fields = [
+ "parlamentar",
+ ]
class LegislaturaAdmin(BaseModelAdmin):
- date_hierarchy = 'data_inicio'
- list_display = ('numero', 'casa_legislativa', 'uf', 'data_inicio', 'data_fim', 'data_eleicao', 'total_parlamentares')
- raw_id_fields = ('casa_legislativa',)
- list_display_links = ('numero',)
- list_filter = ('casa_legislativa__municipio__uf', )
- search_fields = ('casa_legislativa__nome', 'casa_legislativa__municipio__nome')
+ date_hierarchy = "data_inicio"
+ list_display = (
+ "numero",
+ "casa_legislativa",
+ "uf",
+ "data_inicio",
+ "data_fim",
+ "data_eleicao",
+ "total_parlamentares",
+ )
+ raw_id_fields = ("casa_legislativa",)
+ list_display_links = ("numero",)
+ list_filter = ("casa_legislativa__municipio__uf",)
+ search_fields = (
+ "casa_legislativa__nome",
+ "casa_legislativa__municipio__nome",
+ )
inlines = (MandatoInline,)
def uf(self, obj):
return obj.casa_legislativa.municipio.uf.sigla
- uf.short_description = _('UF')
- uf.admin_order_field = 'casa_legislativa__municipio__uf'
+
+ uf.short_description = _("UF")
+ uf.admin_order_field = "casa_legislativa__municipio__uf"
def lookup_allowed(self, lookup, value):
- return super(LegislaturaAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact']
+ return super(LegislaturaAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in ["casa_legislativa__municipio__uf__codigo_ibge__exact"]
def response_change(self, request, obj):
response = super(LegislaturaAdmin, self).response_change(request, obj)
if "_popup" in request.POST:
- response = HttpResponse('' %
- # escape() calls force_unicode.
- (escape(obj.pk), escapejs(obj)))
+ response = HttpResponse(
+ ''
+ %
+ # escape() calls force_unicode.
+ (escape(obj.pk), escapejs(obj))
+ )
return response
class ColigacaoAdmin(BaseModelAdmin):
- list_display = ('nome', 'legislatura', 'numero_votos')
- list_display_links = ('nome',)
- raw_id_fields = ('legislatura',)
- search_fields = ('nome', 'legislatura__numero')
+ list_display = ("nome", "legislatura", "numero_votos")
+ list_display_links = ("nome",)
+ raw_id_fields = ("legislatura",)
+ search_fields = ("nome", "legislatura__numero")
class ComposicaoColigacaoAdmin(BaseModelAdmin):
- list_display = ('coligacao', 'partido')
- list_display_links = ('coligacao', 'partido')
- list_filter = ('partido',)
- raw_id_fields = ('coligacao', 'partido')
- search_fields = ('coligacao__nome', 'partido__nome', 'partido__sigla')
+ list_display = ("coligacao", "partido")
+ list_display_links = ("coligacao", "partido")
+ list_filter = ("partido",)
+ raw_id_fields = ("coligacao", "partido")
+ search_fields = ("coligacao__nome", "partido__nome", "partido__sigla")
class SessaoLegislativaAdmin(BaseModelAdmin):
- list_display = ('numero', 'mesa_diretora', 'legislatura', 'tipo',
- 'data_inicio', 'data_fim')
- list_display_links = ('numero',)
- list_filter = ('tipo',)
+ list_display = (
+ "numero",
+ "mesa_diretora",
+ "legislatura",
+ "tipo",
+ "data_inicio",
+ "data_fim",
+ )
+ list_display_links = ("numero",)
+ list_filter = ("tipo",)
fieldsets = (
- (None, {
- 'fields': ('numero', 'mesa_diretora', 'legislatura', 'tipo')
- }),
- (None, {
- 'fields': (('data_inicio', 'data_fim'),
- ('data_inicio_intervalo', 'data_fim_intervalo'))
- }),
+ (None, {"fields": ("numero", "mesa_diretora", "legislatura", "tipo")}),
+ (
+ None,
+ {
+ "fields": (
+ ("data_inicio", "data_fim"),
+ ("data_inicio_intervalo", "data_fim_intervalo"),
+ )
+ },
+ ),
)
- radio_fields = {'tipo': admin.VERTICAL}
- raw_id_fields = ('mesa_diretora', 'legislatura')
- search_fields = ('numero', 'mesa_diretora__casa_legislativa__nome')
+ radio_fields = {"tipo": admin.VERTICAL}
+ raw_id_fields = ("mesa_diretora", "legislatura")
+ search_fields = ("numero", "mesa_diretora__casa_legislativa__nome")
class CargoAdmin(BaseModelAdmin):
- list_display = ('descricao',)
- search_fields = ('descricao',)
+ list_display = ("descricao",)
+ search_fields = ("descricao",)
class MembroMesaDiretoraInline(admin.TabularInline):
model = MembroMesaDiretora
max_num = 11
extra = 4
- raw_id_fields = ('parlamentar', 'cargo')
+ raw_id_fields = ("parlamentar", "cargo")
class MembroMesaDiretoraAdmin(BaseModelAdmin):
- list_display = ('parlamentar', 'cargo', 'mesa_diretora')
- list_display_links = ('parlamentar',)
- list_filter = ('cargo',)
- raw_id_fields = ('parlamentar', 'cargo', 'mesa_diretora')
- search_fields = ('cargo__descricao', 'parlamentar__nome_completo',
- 'parlamentar__nome_parlamentar',
- 'mesa_diretora__casa_legislativa__nome')
+ list_display = ("parlamentar", "cargo", "mesa_diretora")
+ list_display_links = ("parlamentar",)
+ list_filter = ("cargo",)
+ raw_id_fields = ("parlamentar", "cargo", "mesa_diretora")
+ search_fields = (
+ "cargo__descricao",
+ "parlamentar__nome_completo",
+ "parlamentar__nome_parlamentar",
+ "mesa_diretora__casa_legislativa__nome",
+ )
class MesaDiretoraAdmin(BaseModelAdmin):
inlines = (MembroMesaDiretoraInline,)
- raw_id_fields = ('casa_legislativa',)
- list_display = ('id', 'casa_legislativa')
- search_fields = ('casa_legislativa__nome',)
+ raw_id_fields = ("casa_legislativa",)
+ list_display = ("id", "casa_legislativa")
+ search_fields = ("casa_legislativa__nome",)
admin.site.register(Partido, PartidoAdmin)
diff --git a/sigi/apps/parlamentares/migrations/0001_initial.py b/sigi/apps/parlamentares/migrations/0001_initial.py
index e786663..af6b63a 100644
--- a/sigi/apps/parlamentares/migrations/0001_initial.py
+++ b/sigi/apps/parlamentares/migrations/0001_initial.py
@@ -7,196 +7,404 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '__first__'),
+ ("casas", "__first__"),
]
operations = [
migrations.CreateModel(
- name='Cargo',
+ name="Cargo",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('descricao', models.CharField(max_length=30, verbose_name='descri\xe7\xe3o')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length=30, verbose_name="descri\xe7\xe3o"
+ ),
+ ),
],
options={
- 'ordering': ('descricao',),
+ "ordering": ("descricao",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Coligacao',
+ name="Coligacao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=50)),
- ('numero_votos', models.PositiveIntegerField(null=True, verbose_name='n\xfamero de votos', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=50)),
+ (
+ "numero_votos",
+ models.PositiveIntegerField(
+ null=True, verbose_name="n\xfamero de votos", blank=True
+ ),
+ ),
],
options={
- 'ordering': ('legislatura', 'nome'),
- 'verbose_name': 'coliga\xe7\xe3o',
- 'verbose_name_plural': 'coliga\xe7\xf5es',
+ "ordering": ("legislatura", "nome"),
+ "verbose_name": "coliga\xe7\xe3o",
+ "verbose_name_plural": "coliga\xe7\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='ComposicaoColigacao',
+ name="ComposicaoColigacao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('coligacao', models.ForeignKey(verbose_name='coliga\xe7\xe3o', to='parlamentares.Coligacao')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "coligacao",
+ models.ForeignKey(
+ verbose_name="coliga\xe7\xe3o",
+ to="parlamentares.Coligacao",
+ ),
+ ),
],
options={
- 'verbose_name': 'composi\xe7\xe3o da coliga\xe7\xe3o',
- 'verbose_name_plural': 'composi\xe7\xf5es das coliga\xe7\xf5es',
+ "verbose_name": "composi\xe7\xe3o da coliga\xe7\xe3o",
+ "verbose_name_plural": "composi\xe7\xf5es das coliga\xe7\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Legislatura',
+ name="Legislatura",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('numero', models.PositiveSmallIntegerField(verbose_name='n\xfamero legislatura')),
- ('data_inicio', models.DateField(verbose_name='in\xedcio')),
- ('data_fim', models.DateField(verbose_name='fim')),
- ('data_eleicao', models.DateField(verbose_name='data da elei\xe7\xe3o')),
- ('total_parlamentares', models.PositiveIntegerField(verbose_name='Total de parlamentares')),
- ('casa_legislativa', models.ForeignKey(to='casas.CasaLegislativa')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "numero",
+ models.PositiveSmallIntegerField(
+ verbose_name="n\xfamero legislatura"
+ ),
+ ),
+ ("data_inicio", models.DateField(verbose_name="in\xedcio")),
+ ("data_fim", models.DateField(verbose_name="fim")),
+ (
+ "data_eleicao",
+ models.DateField(verbose_name="data da elei\xe7\xe3o"),
+ ),
+ (
+ "total_parlamentares",
+ models.PositiveIntegerField(
+ verbose_name="Total de parlamentares"
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(to="casas.CasaLegislativa"),
+ ),
],
options={
- 'ordering': ['casa_legislativa__municipio__uf__sigla', '-data_inicio'],
+ "ordering": [
+ "casa_legislativa__municipio__uf__sigla",
+ "-data_inicio",
+ ],
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Mandato',
+ name="Mandato",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('inicio_mandato', models.DateField(verbose_name='in\xedcio de mandato')),
- ('fim_mandato', models.DateField(verbose_name='fim de mandato')),
- ('is_afastado', models.BooleanField(default=False, help_text='Marque caso parlamentar n\xe3o esteja ativo.', verbose_name='afastado')),
- ('cargo', models.ForeignKey(to='parlamentares.Cargo')),
- ('legislatura', models.ForeignKey(to='parlamentares.Legislatura')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "inicio_mandato",
+ models.DateField(verbose_name="in\xedcio de mandato"),
+ ),
+ (
+ "fim_mandato",
+ models.DateField(verbose_name="fim de mandato"),
+ ),
+ (
+ "is_afastado",
+ models.BooleanField(
+ default=False,
+ help_text="Marque caso parlamentar n\xe3o esteja ativo.",
+ verbose_name="afastado",
+ ),
+ ),
+ ("cargo", models.ForeignKey(to="parlamentares.Cargo")),
+ (
+ "legislatura",
+ models.ForeignKey(to="parlamentares.Legislatura"),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='MembroMesaDiretora',
+ name="MembroMesaDiretora",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('cargo', models.ForeignKey(to='parlamentares.Cargo')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("cargo", models.ForeignKey(to="parlamentares.Cargo")),
],
options={
- 'ordering': ('parlamentar',),
- 'verbose_name': 'membro de Mesa Diretora',
- 'verbose_name_plural': 'membros de Mesa Diretora',
+ "ordering": ("parlamentar",),
+ "verbose_name": "membro de Mesa Diretora",
+ "verbose_name_plural": "membros de Mesa Diretora",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='MesaDiretora',
+ name="MesaDiretora",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ ),
+ ),
],
options={
- 'verbose_name': 'Mesa Diretora',
- 'verbose_name_plural': 'Mesas Diretoras',
+ "verbose_name": "Mesa Diretora",
+ "verbose_name_plural": "Mesas Diretoras",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Parlamentar',
+ name="Parlamentar",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome_completo', models.CharField(max_length=128)),
- ('nome_parlamentar', models.CharField(max_length=35, blank=True)),
- ('foto', models.ImageField(height_field=b'foto_altura', width_field=b'foto_largura', upload_to=b'fotos/parlamentares', blank=True)),
- ('foto_largura', models.SmallIntegerField(null=True, editable=False)),
- ('foto_altura', models.SmallIntegerField(null=True, editable=False)),
- ('sexo', models.CharField(max_length=1, choices=[(b'M', 'Masculino'), (b'F', 'Feminino')])),
- ('data_nascimento', models.DateField(null=True, verbose_name='data de nascimento', blank=True)),
- ('email', models.EmailField(max_length=75, verbose_name='e-mail', blank=True)),
- ('pagina_web', models.URLField(verbose_name='p\xe1gina web', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome_completo", models.CharField(max_length=128)),
+ (
+ "nome_parlamentar",
+ models.CharField(max_length=35, blank=True),
+ ),
+ (
+ "foto",
+ models.ImageField(
+ height_field=b"foto_altura",
+ width_field=b"foto_largura",
+ upload_to=b"fotos/parlamentares",
+ blank=True,
+ ),
+ ),
+ (
+ "foto_largura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "foto_altura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "sexo",
+ models.CharField(
+ max_length=1,
+ choices=[(b"M", "Masculino"), (b"F", "Feminino")],
+ ),
+ ),
+ (
+ "data_nascimento",
+ models.DateField(
+ null=True, verbose_name="data de nascimento", blank=True
+ ),
+ ),
+ (
+ "email",
+ models.EmailField(
+ max_length=75, verbose_name="e-mail", blank=True
+ ),
+ ),
+ (
+ "pagina_web",
+ models.URLField(verbose_name="p\xe1gina web", blank=True),
+ ),
],
options={
- 'ordering': ('nome_completo',),
- 'verbose_name_plural': 'parlamentares',
+ "ordering": ("nome_completo",),
+ "verbose_name_plural": "parlamentares",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Partido',
+ name="Partido",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=50)),
- ('sigla', models.CharField(max_length=10)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=50)),
+ ("sigla", models.CharField(max_length=10)),
],
options={
- 'ordering': ('nome',),
+ "ordering": ("nome",),
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='SessaoLegislativa',
+ name="SessaoLegislativa",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('numero', models.PositiveSmallIntegerField(unique=True, verbose_name='n\xfamero da sess\xe3o')),
- ('tipo', models.CharField(default=b'O', max_length=1, choices=[(b'O', 'Ordin\xe1ria'), (b'E', 'Extraordin\xe1ria')])),
- ('data_inicio', models.DateField(verbose_name='in\xedcio')),
- ('data_fim', models.DateField(verbose_name='fim')),
- ('data_inicio_intervalo', models.DateField(null=True, verbose_name='in\xedcio de intervalo', blank=True)),
- ('data_fim_intervalo', models.DateField(null=True, verbose_name='fim de intervalo', blank=True)),
- ('legislatura', models.ForeignKey(to='parlamentares.Legislatura')),
- ('mesa_diretora', models.ForeignKey(verbose_name='Mesa Diretora', to='parlamentares.MesaDiretora')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "numero",
+ models.PositiveSmallIntegerField(
+ unique=True, verbose_name="n\xfamero da sess\xe3o"
+ ),
+ ),
+ (
+ "tipo",
+ models.CharField(
+ default=b"O",
+ max_length=1,
+ choices=[
+ (b"O", "Ordin\xe1ria"),
+ (b"E", "Extraordin\xe1ria"),
+ ],
+ ),
+ ),
+ ("data_inicio", models.DateField(verbose_name="in\xedcio")),
+ ("data_fim", models.DateField(verbose_name="fim")),
+ (
+ "data_inicio_intervalo",
+ models.DateField(
+ null=True,
+ verbose_name="in\xedcio de intervalo",
+ blank=True,
+ ),
+ ),
+ (
+ "data_fim_intervalo",
+ models.DateField(
+ null=True, verbose_name="fim de intervalo", blank=True
+ ),
+ ),
+ (
+ "legislatura",
+ models.ForeignKey(to="parlamentares.Legislatura"),
+ ),
+ (
+ "mesa_diretora",
+ models.ForeignKey(
+ verbose_name="Mesa Diretora",
+ to="parlamentares.MesaDiretora",
+ ),
+ ),
],
options={
- 'ordering': ('legislatura', 'numero'),
- 'verbose_name': 'Sess\xe3o Legislativa',
- 'verbose_name_plural': 'Sess\xf5es Legislativas',
+ "ordering": ("legislatura", "numero"),
+ "verbose_name": "Sess\xe3o Legislativa",
+ "verbose_name_plural": "Sess\xf5es Legislativas",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='membromesadiretora',
- name='mesa_diretora',
- field=models.ForeignKey(to='parlamentares.MesaDiretora'),
+ model_name="membromesadiretora",
+ name="mesa_diretora",
+ field=models.ForeignKey(to="parlamentares.MesaDiretora"),
preserve_default=True,
),
migrations.AddField(
- model_name='membromesadiretora',
- name='parlamentar',
- field=models.ForeignKey(to='parlamentares.Parlamentar'),
+ model_name="membromesadiretora",
+ name="parlamentar",
+ field=models.ForeignKey(to="parlamentares.Parlamentar"),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='membromesadiretora',
- unique_together=set([('cargo', 'mesa_diretora')]),
+ name="membromesadiretora",
+ unique_together=set([("cargo", "mesa_diretora")]),
),
migrations.AddField(
- model_name='mandato',
- name='parlamentar',
- field=models.ForeignKey(to='parlamentares.Parlamentar'),
+ model_name="mandato",
+ name="parlamentar",
+ field=models.ForeignKey(to="parlamentares.Parlamentar"),
preserve_default=True,
),
migrations.AddField(
- model_name='mandato',
- name='partido',
- field=models.ForeignKey(to='parlamentares.Partido'),
+ model_name="mandato",
+ name="partido",
+ field=models.ForeignKey(to="parlamentares.Partido"),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='legislatura',
- unique_together=set([('casa_legislativa', 'numero')]),
+ name="legislatura",
+ unique_together=set([("casa_legislativa", "numero")]),
),
migrations.AddField(
- model_name='composicaocoligacao',
- name='partido',
- field=models.ForeignKey(to='parlamentares.Partido'),
+ model_name="composicaocoligacao",
+ name="partido",
+ field=models.ForeignKey(to="parlamentares.Partido"),
preserve_default=True,
),
migrations.AddField(
- model_name='coligacao',
- name='legislatura',
- field=models.ForeignKey(to='parlamentares.Legislatura'),
+ model_name="coligacao",
+ name="legislatura",
+ field=models.ForeignKey(to="parlamentares.Legislatura"),
preserve_default=True,
),
]
diff --git a/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py b/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py
index b645ba0..3b5a6b1 100644
--- a/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py
+++ b/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py
@@ -7,21 +7,23 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('parlamentares', '0001_initial'),
- ('casas', '0014_auto_20210406_1945'),
+ ("parlamentares", "0001_initial"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='legislatura',
- name='casa_legislativa',
- field=models.ForeignKey(to='casas.Orgao'),
+ model_name="legislatura",
+ name="casa_legislativa",
+ field=models.ForeignKey(to="casas.Orgao"),
preserve_default=True,
),
migrations.AlterField(
- model_name='mesadiretora',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
+ model_name="mesadiretora",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa", to="casas.Orgao"
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/parlamentares/migrations/0003_auto_20210416_0841.py b/sigi/apps/parlamentares/migrations/0003_auto_20210416_0841.py
index f7d418b..d771444 100644
--- a/sigi/apps/parlamentares/migrations/0003_auto_20210416_0841.py
+++ b/sigi/apps/parlamentares/migrations/0003_auto_20210416_0841.py
@@ -8,26 +8,36 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('parlamentares', '0002_auto_20210406_1945'),
+ ("parlamentares", "0002_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='mandato',
- name='cargo',
- field=models.ForeignKey(to='parlamentares.Cargo', on_delete=django.db.models.deletion.PROTECT),
+ model_name="mandato",
+ name="cargo",
+ field=models.ForeignKey(
+ to="parlamentares.Cargo",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='membromesadiretora',
- name='cargo',
- field=models.ForeignKey(to='parlamentares.Cargo', on_delete=django.db.models.deletion.PROTECT),
+ model_name="membromesadiretora",
+ name="cargo",
+ field=models.ForeignKey(
+ to="parlamentares.Cargo",
+ on_delete=django.db.models.deletion.PROTECT,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='sessaolegislativa',
- name='mesa_diretora',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Mesa Diretora', to='parlamentares.MesaDiretora'),
+ model_name="sessaolegislativa",
+ name="mesa_diretora",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Mesa Diretora",
+ to="parlamentares.MesaDiretora",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/parlamentares/models.py b/sigi/apps/parlamentares/models.py
index f7d5f7f..4dadc9f 100644
--- a/sigi/apps/parlamentares/models.py
+++ b/sigi/apps/parlamentares/models.py
@@ -10,24 +10,24 @@ class Partido(models.Model):
sigla = models.CharField(max_length=10)
class Meta:
- ordering = ('nome',)
+ ordering = ("nome",)
def __unicode__(self):
- return '%s (%s)' % (unicode(self.nome), unicode(self.sigla))
+ return "%s (%s)" % (unicode(self.nome), unicode(self.sigla))
class Parlamentar(models.Model):
SEXO_CHOICES = (
- ('M', _('Masculino')),
- ('F', _('Feminino')),
+ ("M", _("Masculino")),
+ ("F", _("Feminino")),
)
nome_completo = models.CharField(max_length=128)
nome_parlamentar = models.CharField(max_length=35, blank=True)
foto = models.ImageField(
- upload_to='fotos/parlamentares',
- width_field='foto_largura',
- height_field='foto_altura',
- blank=True
+ upload_to="fotos/parlamentares",
+ width_field="foto_largura",
+ height_field="foto_altura",
+ blank=True,
)
foto_largura = models.SmallIntegerField(editable=False, null=True)
foto_altura = models.SmallIntegerField(editable=False, null=True)
@@ -36,17 +36,16 @@ class Parlamentar(models.Model):
choices=SEXO_CHOICES,
)
data_nascimento = models.DateField(
- _('data de nascimento'),
+ _("data de nascimento"),
blank=True,
null=True,
)
- email = models.EmailField(_('e-mail'), blank=True)
- pagina_web = models.URLField(_('página web'),
- blank=True)
+ email = models.EmailField(_("e-mail"), blank=True)
+ pagina_web = models.URLField(_("página web"), blank=True)
class Meta:
- ordering = ('nome_completo',)
- verbose_name_plural = _('parlamentares')
+ ordering = ("nome_completo",)
+ verbose_name_plural = _("parlamentares")
def __unicode__(self):
if self.nome_parlamentar:
@@ -56,29 +55,28 @@ class Parlamentar(models.Model):
class Mandato(models.Model):
SUPLENCIA_CHOICES = (
- ('T', _('Titular')),
- ('S', _('Suplente')),
+ ("T", _("Titular")),
+ ("S", _("Suplente")),
)
parlamentar = models.ForeignKey(Parlamentar, on_delete=models.CASCADE)
legislatura = models.ForeignKey(
- 'parlamentares.Legislatura',
- on_delete=models.CASCADE
+ "parlamentares.Legislatura", on_delete=models.CASCADE
)
partido = models.ForeignKey(Partido, on_delete=models.CASCADE)
- cargo = models.ForeignKey('parlamentares.Cargo', on_delete=models.PROTECT)
- inicio_mandato = models.DateField(_('início de mandato'))
- fim_mandato = models.DateField(_('fim de mandato'))
+ cargo = models.ForeignKey("parlamentares.Cargo", on_delete=models.PROTECT)
+ inicio_mandato = models.DateField(_("início de mandato"))
+ fim_mandato = models.DateField(_("fim de mandato"))
is_afastado = models.BooleanField(
- _('afastado'),
+ _("afastado"),
default=False,
- help_text=_('Marque caso parlamentar não esteja ativo.')
+ help_text=_("Marque caso parlamentar não esteja ativo."),
)
-# suplencia = models.CharField(
-# _('suplência'),
-# max_length=1,
-# choices=SUPLENCIA_CHOICES,
-# )
+ # suplencia = models.CharField(
+ # _('suplência'),
+ # max_length=1,
+ # choices=SUPLENCIA_CHOICES,
+ # )
def __unicode__(self):
return str(self.id)
@@ -86,40 +84,45 @@ class Mandato(models.Model):
class Legislatura(models.Model):
casa_legislativa = models.ForeignKey(Orgao, on_delete=models.CASCADE)
- numero = models.PositiveSmallIntegerField(_('número legislatura'))
- data_inicio = models.DateField(_('início'))
- data_fim = models.DateField(_('fim'))
- data_eleicao = models.DateField(_('data da eleição'))
- total_parlamentares = models.PositiveIntegerField(_("Total de parlamentares"))
+ numero = models.PositiveSmallIntegerField(_("número legislatura"))
+ data_inicio = models.DateField(_("início"))
+ data_fim = models.DateField(_("fim"))
+ data_eleicao = models.DateField(_("data da eleição"))
+ total_parlamentares = models.PositiveIntegerField(
+ _("Total de parlamentares")
+ )
casa_legislativa.convenio_uf_filter = True
casa_legislativa.convenio_cl_tipo_filter = True
class Meta:
- unique_together = (('casa_legislativa', 'numero'))
- ordering = ['casa_legislativa__municipio__uf__sigla', '-data_inicio']
+ unique_together = ("casa_legislativa", "numero")
+ ordering = ["casa_legislativa__municipio__uf__sigla", "-data_inicio"]
def __unicode__(self):
- return _("%(number)sª legislatura da %(parliament)s (%(initial_year)s-%(final_year)s)") % dict(
+ return _(
+ "%(number)sª legislatura da %(parliament)s (%(initial_year)s-%(final_year)s)"
+ ) % dict(
number=self.numero,
parliament=self.casa_legislativa.__unicode__(),
initial_year=self.data_inicio.year,
- final_year=self.data_fim.year)
+ final_year=self.data_fim.year,
+ )
class Coligacao(models.Model):
nome = models.CharField(max_length=50)
legislatura = models.ForeignKey(Legislatura, on_delete=models.CASCADE)
numero_votos = models.PositiveIntegerField(
- _('número de votos'),
+ _("número de votos"),
blank=True,
null=True,
)
class Meta:
- ordering = ('legislatura', 'nome')
- verbose_name = _('coligação')
- verbose_name_plural = _('coligações')
+ ordering = ("legislatura", "nome")
+ verbose_name = _("coligação")
+ verbose_name_plural = _("coligações")
def __unicode__(self):
return self.nome
@@ -127,18 +130,15 @@ class Coligacao(models.Model):
class ComposicaoColigacao(models.Model):
coligacao = models.ForeignKey(
- Coligacao,
- on_delete=models.CASCADE,
- verbose_name=_('coligação')
+ Coligacao, on_delete=models.CASCADE, verbose_name=_("coligação")
)
partido = models.ForeignKey(
- 'parlamentares.Partido',
- on_delete=models.CASCADE
+ "parlamentares.Partido", on_delete=models.CASCADE
)
class Meta:
- verbose_name = _('composição da coligação')
- verbose_name_plural = _('composições das coligações')
+ verbose_name = _("composição da coligação")
+ verbose_name_plural = _("composições das coligações")
def __unicode__(self):
return str(self.id)
@@ -146,38 +146,32 @@ class ComposicaoColigacao(models.Model):
class SessaoLegislativa(models.Model):
SESSAO_CHOICES = (
- ('O', _('Ordinária')),
- ('E', _('Extraordinária')),
+ ("O", _("Ordinária")),
+ ("E", _("Extraordinária")),
+ )
+ numero = models.PositiveSmallIntegerField(
+ _("número da sessão"), unique=True
)
- numero = models.PositiveSmallIntegerField(_('número da sessão'), unique=True)
mesa_diretora = models.ForeignKey(
- 'MesaDiretora',
+ "MesaDiretora",
on_delete=models.PROTECT,
- verbose_name=_('Mesa Diretora')
+ verbose_name=_("Mesa Diretora"),
)
legislatura = models.ForeignKey(Legislatura, on_delete=models.CASCADE)
- tipo = models.CharField(
- max_length=1,
- choices=SESSAO_CHOICES,
- default='O'
- )
- data_inicio = models.DateField(_('início'))
- data_fim = models.DateField(_('fim'))
+ tipo = models.CharField(max_length=1, choices=SESSAO_CHOICES, default="O")
+ data_inicio = models.DateField(_("início"))
+ data_fim = models.DateField(_("fim"))
data_inicio_intervalo = models.DateField(
- _('início de intervalo'),
- blank=True,
- null=True
+ _("início de intervalo"), blank=True, null=True
)
data_fim_intervalo = models.DateField(
- _('fim de intervalo'),
- blank=True,
- null=True
+ _("fim de intervalo"), blank=True, null=True
)
class Meta:
- ordering = ('legislatura', 'numero')
- verbose_name = _('Sessão Legislativa')
- verbose_name_plural = _('Sessões Legislativas')
+ ordering = ("legislatura", "numero")
+ verbose_name = _("Sessão Legislativa")
+ verbose_name_plural = _("Sessões Legislativas")
def __unicode__(self):
return str(self.numero)
@@ -185,24 +179,24 @@ class SessaoLegislativa(models.Model):
class MesaDiretora(models.Model):
casa_legislativa = models.ForeignKey(
- 'casas.Orgao',
+ "casas.Orgao",
on_delete=models.CASCADE,
- verbose_name=_('Casa Legislativa')
+ verbose_name=_("Casa Legislativa"),
)
class Meta:
- verbose_name = _('Mesa Diretora')
- verbose_name_plural = _('Mesas Diretoras')
+ verbose_name = _("Mesa Diretora")
+ verbose_name_plural = _("Mesas Diretoras")
def __unicode__(self):
- return _('Mesa Diretora da %s') % unicode(self.casa_legislativa)
+ return _("Mesa Diretora da %s") % unicode(self.casa_legislativa)
class Cargo(models.Model):
- descricao = models.CharField(_('descrição'), max_length=30)
+ descricao = models.CharField(_("descrição"), max_length=30)
class Meta:
- ordering = ('descricao',)
+ ordering = ("descricao",)
def __unicode__(self):
return self.descricao
@@ -210,17 +204,16 @@ class Cargo(models.Model):
class MembroMesaDiretora(models.Model):
parlamentar = models.ForeignKey(
- 'parlamentares.Parlamentar',
- on_delete=models.CASCADE
+ "parlamentares.Parlamentar", on_delete=models.CASCADE
)
cargo = models.ForeignKey(Cargo, on_delete=models.PROTECT)
mesa_diretora = models.ForeignKey(MesaDiretora, on_delete=models.CASCADE)
class Meta:
- ordering = ('parlamentar',)
- unique_together = ('cargo', 'mesa_diretora')
- verbose_name = _('membro de Mesa Diretora')
- verbose_name_plural = _('membros de Mesa Diretora')
+ ordering = ("parlamentar",)
+ unique_together = ("cargo", "mesa_diretora")
+ verbose_name = _("membro de Mesa Diretora")
+ verbose_name_plural = _("membros de Mesa Diretora")
def __unicode__(self):
- return '%s (%s)' % (unicode(self.parlamentar), unicode(self.cargo))
+ return "%s (%s)" % (unicode(self.parlamentar), unicode(self.cargo))
diff --git a/sigi/apps/parlamentares/reports.py b/sigi/apps/parlamentares/reports.py
index 1f0f826..9383e6e 100644
--- a/sigi/apps/parlamentares/reports.py
+++ b/sigi/apps/parlamentares/reports.py
@@ -1,7 +1,18 @@
# -*- coding: utf-8 -*-
from django.templatetags.static import static
from django.utils.translation import gettext as _
-from geraldo import Report, DetailBand, Label, ObjectValue, ReportGroup, ReportBand, landscape, SubReport, BAND_WIDTH, SystemField
+from geraldo import (
+ Report,
+ DetailBand,
+ Label,
+ ObjectValue,
+ ReportGroup,
+ ReportBand,
+ landscape,
+ SubReport,
+ BAND_WIDTH,
+ SystemField,
+)
from geraldo.graphics import Image
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import A4
@@ -13,22 +24,22 @@ from sigi.apps.relatorios.reports import ReportDefault
def string_to_cm(texto):
tamanho = 0
minEspeciais = {
- 'f': 0.1,
- 'i': 0.05,
- 'j': 0.05,
- 'l': 0.05,
- 'm': 0.2,
- 'r': 0.1,
- 't': 0.15,
+ "f": 0.1,
+ "i": 0.05,
+ "j": 0.05,
+ "l": 0.05,
+ "m": 0.2,
+ "r": 0.1,
+ "t": 0.15,
}
maiuEspeciais = {
- 'I': 0.05,
- 'J': 0.15,
- 'L': 0.15,
- 'P': 0.15,
+ "I": 0.05,
+ "J": 0.15,
+ "L": 0.15,
+ "P": 0.15,
}
for c in texto:
- if c > 'a' and c < 'z':
+ if c > "a" and c < "z":
if c in minEspeciais:
tamanho += minEspeciais[c]
else:
@@ -52,7 +63,8 @@ class ParlamentaresLabels(Report):
>>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')
"""
- formato = ''
+
+ formato = ""
y = 2
largura_etiqueta = 7
altura_etiqueta = 3.3
@@ -65,12 +77,14 @@ class ParlamentaresLabels(Report):
self.formato = formato
self.page_size = A4
- if formato == '3x9_etiqueta':
+ if formato == "3x9_etiqueta":
self.margin_top = 0.0 * cm
self.margin_bottom = 0.0 * cm
self.margin_left = -1 * cm
self.margin_right = 0.0 * cm
- self.delta = 0.4 # espaçamento entre as "strings/linhas" da etiqueta
+ self.delta = (
+ 0.4 # espaçamento entre as "strings/linhas" da etiqueta
+ )
self.start = 0.2 # valor entre a margin top e a etiqueta
else:
self.margin_top = 0.8 * cm
@@ -85,73 +99,101 @@ class ParlamentaresLabels(Report):
my_elements = [
Label(
- text=_('A Sua Excelência o(a) Senhor(a)'),
- top=(self.start + self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
+ text=_("A Sua Excelência o(a) Senhor(a)"),
+ top=(self.start + self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
),
ObjectValue(
- attribute_name='nome_completo',
- top=(self.start + 2 * self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
- get_value=lambda instance:
- instance.nome_completo or ""
+ attribute_name="nome_completo",
+ top=(self.start + 2 * self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
+ get_value=lambda instance: instance.nome_completo or "",
),
ObjectValue(
- attribute_name='logradouro',
- top=(self.start + 3 * self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
- get_value=lambda instance:
- logradouro_parlamentar(instance)
+ attribute_name="logradouro",
+ top=(self.start + 3 * self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
+ get_value=lambda instance: logradouro_parlamentar(instance),
),
ObjectValue(
- attribute_name='bairro',
- top=(self.start + 4 * self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
- get_value=lambda instance:
- bairro_parlamentar(instance)
+ attribute_name="bairro",
+ top=(self.start + 4 * self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
+ get_value=lambda instance: bairro_parlamentar(instance),
),
ObjectValue(
- attribute_name='municipio',
- top=(self.start + 5 * self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
- get_value=lambda instance:
- municipio_parlamentar(instance)
+ attribute_name="municipio",
+ top=(self.start + 5 * self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
+ get_value=lambda instance: municipio_parlamentar(instance),
),
ObjectValue(
- attribute_name='cep',
- top=(self.start + 6 * self.delta) * cm, left=self.y * cm, width=(self.largura_etiqueta - self.y) * cm,
- get_value=lambda instance:
- cep_parlamentar(instance)
+ attribute_name="cep",
+ top=(self.start + 6 * self.delta) * cm,
+ left=self.y * cm,
+ width=(self.largura_etiqueta - self.y) * cm,
+ get_value=lambda instance: cep_parlamentar(instance),
),
]
- self.band_detail = DetailBand(width=(self.largura_etiqueta) * cm, height=(self.altura_etiqueta) * cm, margin_left=0, margin_top=0, margin_bottom=0.0 * cm, margin_right=0, elements=my_elements, display_inline=True, default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte})
+ self.band_detail = DetailBand(
+ width=(self.largura_etiqueta) * cm,
+ height=(self.altura_etiqueta) * cm,
+ margin_left=0,
+ margin_top=0,
+ margin_bottom=0.0 * cm,
+ margin_right=0,
+ elements=my_elements,
+ display_inline=True,
+ default_style={
+ "fontName": "Helvetica",
+ "fontSize": self.tamanho_fonte,
+ },
+ )
def logradouro_parlamentar(instance):
try:
- return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.logradouro
+ return instance.mandato_set.latest(
+ "inicio_mandato"
+ ).legislatura.casa_legislativa.logradouro
except:
return _("<>")
def bairro_parlamentar(instance):
try:
- return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.bairro
+ return instance.mandato_set.latest(
+ "inicio_mandato"
+ ).legislatura.casa_legislativa.bairro
except:
return _("<>")
def municipio_parlamentar(instance):
try:
- return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.municipio
+ return instance.mandato_set.latest(
+ "inicio_mandato"
+ ).legislatura.casa_legislativa.municipio
except:
return _("<>")
def cep_parlamentar(instance):
try:
- return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.cep
+ return instance.mandato_set.latest(
+ "inicio_mandato"
+ ).legislatura.casa_legislativa.cep
except:
return _("<>")
class CasasLegislativasReport(ReportDefault):
- title = _('Relatório de Casas Legislativas')
+ title = _("Relatório de Casas Legislativas")
height = 80 * cm
page_size = landscape(A4)
@@ -162,23 +204,58 @@ class CasasLegislativasReport(ReportDefault):
elements = list(ReportDefault.band_page_header.elements)
elements = [
- Image(filename=ReportDefault.band_page_header.BASE_DIR + static('img/logo-interlegis.jpg'),
- left=23.5 * cm, right=1 * cm, top=0.1 * cm, bottom=1 * cm,
- width=4.2 * cm, height=3 * cm,
- ),
- Image(filename=ReportDefault.band_page_header.BASE_DIR + static('img/logo-senado.png'),
- left=1 * cm, right=1 * cm, top=0.1 * cm, bottom=1 * cm,
- width=3 * cm, height=3 * cm,
- ),
- Label(text=_("SENADO FEDERAL"), top=1 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 14, 'alignment': TA_CENTER}
- ),
- Label(text=_("SINTER - Secretaria Especial do Interlegis"), top=1.5 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 13, 'alignment': TA_CENTER}
- ),
+ Image(
+ filename=ReportDefault.band_page_header.BASE_DIR
+ + static("img/logo-interlegis.jpg"),
+ left=23.5 * cm,
+ right=1 * cm,
+ top=0.1 * cm,
+ bottom=1 * cm,
+ width=4.2 * cm,
+ height=3 * cm,
+ ),
+ Image(
+ filename=ReportDefault.band_page_header.BASE_DIR
+ + static("img/logo-senado.png"),
+ left=1 * cm,
+ right=1 * cm,
+ top=0.1 * cm,
+ bottom=1 * cm,
+ width=3 * cm,
+ height=3 * cm,
+ ),
+ Label(
+ text=_("SENADO FEDERAL"),
+ top=1 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 14,
+ "alignment": TA_CENTER,
+ },
+ ),
+ Label(
+ text=_("SINTER - Secretaria Especial do Interlegis"),
+ top=1.5 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 13,
+ "alignment": TA_CENTER,
+ },
+ ),
SystemField(
- expression='%(report_title)s', top=2.5 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 14, 'alignment': TA_CENTER}
+ expression="%(report_title)s",
+ top=2.5 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 14,
+ "alignment": TA_CENTER,
+ },
),
Label(
text=_("UF"),
@@ -210,8 +287,6 @@ class CasasLegislativasReport(ReportDefault):
left=label_left[5] * cm,
top=label_top,
),
-
-
]
class band_page_footer(ReportDefault.band_page_footer):
@@ -223,44 +298,44 @@ class CasasLegislativasReport(ReportDefault):
elements = [
ObjectValue(
- attribute_name='municipio.uf.sigla',
+ attribute_name="municipio.uf.sigla",
left=label_left[0] * cm,
width=1 * cm,
),
ObjectValue(
- attribute_name='municipio.nome',
+ attribute_name="municipio.nome",
left=label_left[1] * cm,
),
ObjectValue(
- attribute_name='presidente',
+ attribute_name="presidente",
left=label_left[2] * cm,
),
ObjectValue(
- attribute_name='logradouro',
+ attribute_name="logradouro",
left=label_left[3] * cm,
- get_value=lambda instance: instance.logradouro + ' - ' + instance.bairro,
+ get_value=lambda instance: instance.logradouro
+ + " - "
+ + instance.bairro,
),
ObjectValue(
- attribute_name='pagina_web',
+ attribute_name="pagina_web",
left=label_left[4] * cm,
),
ObjectValue(
- attribute_name='email',
+ attribute_name="email",
left=label_left[5] * cm,
),
-
]
groups = [
- ReportGroup(attribute_name='municipio.uf',
- band_header=ReportBand(
- height=0.7 * cm,
- elements=[
- ObjectValue(attribute_name='municipio.uf')
- ],
- borders={'top': True},
- )
- )
+ ReportGroup(
+ attribute_name="municipio.uf",
+ band_header=ReportBand(
+ height=0.7 * cm,
+ elements=[ObjectValue(attribute_name="municipio.uf")],
+ borders={"top": True},
+ ),
+ )
]
@@ -269,7 +344,7 @@ def label_text(text):
class InfoOrgao(ReportDefault):
- title = _('Casa Legislativa')
+ title = _("Casa Legislativa")
class band_summary(ReportBand):
pass
@@ -278,22 +353,34 @@ class InfoOrgao(ReportDefault):
height = 1 * cm
elements = [
- SystemField(expression=_('%(now:%d/%m/%Y)s às %(now:%H:%M)s'), top=0.3 * cm),
+ SystemField(
+ expression=_("%(now:%d/%m/%Y)s às %(now:%H:%M)s"), top=0.3 * cm
+ ),
]
class band_detail(ReportDefault.band_detail):
posicao_left = [
- 0, 1.3, # Tipo
- 0, 1.8, # Regiao
- 5.5, 6.8, # U.F.
- 0, 2.3, # Municipio
- 0, 2.4, # Endereco
- 0, 1.6, # Bairro
- 0, 1.3, # CEP
- 0, 1.6, # CNPJ
- 0, 2.3, # Telefone
- 0, 2.7, # Presidente
+ 0,
+ 1.3, # Tipo
+ 0,
+ 1.8, # Regiao
+ 5.5,
+ 6.8, # U.F.
+ 0,
+ 2.3, # Municipio
+ 0,
+ 2.4, # Endereco
+ 0,
+ 1.6, # Bairro
+ 0,
+ 1.3, # CEP
+ 0,
+ 1.6, # CNPJ
+ 0,
+ 2.3, # Telefone
+ 0,
+ 2.7, # Presidente
]
posicao_top = [
0.5, # Tipo
@@ -311,17 +398,16 @@ class InfoOrgao(ReportDefault):
height = 30 * cm
display_inline = True
- default_style = {'fontName': 'Helvetica', 'fontSize': 14}
+ default_style = {"fontName": "Helvetica", "fontSize": 14}
elements = [
-
Label(
text=label_text(_("Tipo")),
left=posicao_left[0] * cm,
top=posicao_top[0] * cm,
),
ObjectValue(
- attribute_name='tipo.nome',
+ attribute_name="tipo.nome",
left=posicao_left[1] * cm,
top=posicao_top[0] * cm,
width=6 * cm,
@@ -332,12 +418,16 @@ class InfoOrgao(ReportDefault):
top=posicao_top[1] * cm,
),
ObjectValue(
- attribute_name='municipio.uf.regiao',
+ attribute_name="municipio.uf.regiao",
left=posicao_left[3] * cm,
top=posicao_top[1] * cm,
- get_value=lambda instance:
- {'SL': _('Sul'), 'SD': _('Sudeste'), 'CO': _('Centro-Oeste'), 'NE': _('Nordeste'), 'NO': _('Norte'), }
- [instance.municipio.uf.regiao]
+ get_value=lambda instance: {
+ "SL": _("Sul"),
+ "SD": _("Sudeste"),
+ "CO": _("Centro-Oeste"),
+ "NE": _("Nordeste"),
+ "NO": _("Norte"),
+ }[instance.municipio.uf.regiao],
),
Label(
text=label_text(_("UF")),
@@ -345,7 +435,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[2] * cm,
),
ObjectValue(
- attribute_name='municipio.uf',
+ attribute_name="municipio.uf",
left=posicao_left[5] * cm,
top=posicao_top[2] * cm,
),
@@ -355,7 +445,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[3] * cm,
),
ObjectValue(
- attribute_name='municipio.nome',
+ attribute_name="municipio.nome",
left=posicao_left[7] * cm,
top=posicao_top[3] * cm,
width=20 * cm,
@@ -367,7 +457,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[4] * cm,
),
ObjectValue(
- attribute_name='logradouro',
+ attribute_name="logradouro",
left=posicao_left[9] * cm,
top=posicao_top[4] * cm,
width=20 * cm,
@@ -378,7 +468,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[5] * cm,
),
ObjectValue(
- attribute_name='bairro',
+ attribute_name="bairro",
left=posicao_left[11] * cm,
top=posicao_top[5] * cm,
),
@@ -388,7 +478,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[6] * cm,
),
ObjectValue(
- attribute_name='cep',
+ attribute_name="cep",
left=posicao_left[13] * cm,
top=posicao_top[6] * cm,
),
@@ -398,7 +488,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[7] * cm,
),
ObjectValue(
- attribute_name='cnpj',
+ attribute_name="cnpj",
left=posicao_left[15] * cm,
top=posicao_top[7] * cm,
),
@@ -408,7 +498,7 @@ class InfoOrgao(ReportDefault):
top=posicao_top[8] * cm,
),
ObjectValue(
- attribute_name='telefone',
+ attribute_name="telefone",
left=posicao_left[17] * cm,
top=posicao_top[8] * cm,
),
@@ -418,12 +508,13 @@ class InfoOrgao(ReportDefault):
top=posicao_top[9] * cm,
),
ObjectValue(
- attribute_name='presidente',
+ attribute_name="presidente",
left=posicao_left[19] * cm,
top=posicao_top[9] * cm,
width=20 * cm,
),
]
+
# Telefones
tel_top = 2 * cm
tel_left = [0, 3, 5]
@@ -436,14 +527,14 @@ class InfoOrgao(ReportDefault):
subreports = [
# Telefones
SubReport(
- queryset_string='%(object)s.telefones.all()',
+ queryset_string="%(object)s.telefones.all()",
band_header=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 12},
+ default_style={"fontName": "Helvetica", "fontSize": 12},
height=2.5 * cm,
elements=[
Label(
text=_("Telefone(s)"),
- style={'fontSize': 14, 'alignment': TA_CENTER},
+ style={"fontSize": 14, "alignment": TA_CENTER},
width=BAND_WIDTH,
top=1 * cm,
),
@@ -451,100 +542,167 @@ class InfoOrgao(ReportDefault):
Label(text=_("Tipo"), left=tel_left[1] * cm, top=tel_top),
Label(text=_("Nota"), left=tel_left[2] * cm, top=tel_top),
],
- borders={'bottom': True},
+ borders={"bottom": True},
),
band_detail=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 11},
+ default_style={"fontName": "Helvetica", "fontSize": 11},
height=0.5 * cm,
elements=[
- ObjectValue(attribute_name='__unicode__', left=tel_left[0] * cm),
- ObjectValue(attribute_name='tipo', left=tel_left[1] * cm,
- get_value=lambda instance:
- {'F': _('Fixo'), 'M': _('Móvel'), 'X': _('Fax'), 'I': _('Indefinido')}[instance.tipo],
- ),
- ObjectValue(attribute_name='nota', left=tel_left[2] * cm),
+ ObjectValue(
+ attribute_name="__unicode__", left=tel_left[0] * cm
+ ),
+ ObjectValue(
+ attribute_name="tipo",
+ left=tel_left[1] * cm,
+ get_value=lambda instance: {
+ "F": _("Fixo"),
+ "M": _("Móvel"),
+ "X": _("Fax"),
+ "I": _("Indefinido"),
+ }[instance.tipo],
+ ),
+ ObjectValue(attribute_name="nota", left=tel_left[2] * cm),
],
- #borders = {'all':True},
+ # borders = {'all':True},
),
),
# Contatos
SubReport(
- queryset_string='%(object)s.funcionario_set.all()',
+ queryset_string="%(object)s.funcionario_set.all()",
band_header=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 12},
+ default_style={"fontName": "Helvetica", "fontSize": 12},
height=2.5 * cm,
elements=[
Label(
text=_("Contato(s)"),
- style={'fontSize': 14, 'alignment': TA_CENTER},
+ style={"fontSize": 14, "alignment": TA_CENTER},
width=BAND_WIDTH,
top=1 * cm,
),
Label(text=_("Nome"), left=cont_left[0] * cm, top=cont_top),
Label(text=_("Nota"), left=cont_left[1] * cm, top=cont_top),
- Label(text=_("E-mail"), left=cont_left[2] * cm, top=cont_top),
+ Label(
+ text=_("E-mail"), left=cont_left[2] * cm, top=cont_top
+ ),
],
- borders={'bottom': True, 'top': True},
+ borders={"bottom": True, "top": True},
),
band_detail=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 11},
+ default_style={"fontName": "Helvetica", "fontSize": 11},
height=0.5 * cm,
elements=[
- ObjectValue(attribute_name='nome', left=cont_left[0] * cm),
- ObjectValue(attribute_name='nota', left=cont_left[1] * cm),
- ObjectValue(attribute_name='email', left=cont_left[2] * cm),
+ ObjectValue(attribute_name="nome", left=cont_left[0] * cm),
+ ObjectValue(attribute_name="nota", left=cont_left[1] * cm),
+ ObjectValue(attribute_name="email", left=cont_left[2] * cm),
],
- #borders = {'all':True},
+ # borders = {'all':True},
),
),
# Convenios
SubReport(
- queryset_string='%(object)s.convenio_set.all()',
+ queryset_string="%(object)s.convenio_set.all()",
band_header=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 12},
+ default_style={"fontName": "Helvetica", "fontSize": 12},
height=2.5 * cm,
elements=[
Label(
text=_("Convênio(s)"),
- style={'fontSize': 14, 'alignment': TA_CENTER},
+ style={"fontSize": 14, "alignment": TA_CENTER},
width=BAND_WIDTH,
top=1 * cm,
),
- Label(text=_("Projeto"), left=convenio_left[0] * cm, top=convenio_top),
- Label(text=_("Nº Convenio"), left=convenio_left[1] * cm, top=convenio_top),
- Label(text=_("Nº Processo SF"), left=convenio_left[2] * cm, top=convenio_top),
- Label(text=_("Adesão"), left=convenio_left[3] * cm, top=convenio_top),
- Label(text=_("Convênio"), left=convenio_left[4] * cm, top=convenio_top),
- Label(text=_("Equipada"), left=convenio_left[5] * cm, top=convenio_top),
- Label(text=_("Data D.O."), left=convenio_left[6] * cm, top=convenio_top),
+ Label(
+ text=_("Projeto"),
+ left=convenio_left[0] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Nº Convenio"),
+ left=convenio_left[1] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Nº Processo SF"),
+ left=convenio_left[2] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Adesão"),
+ left=convenio_left[3] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Convênio"),
+ left=convenio_left[4] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Equipada"),
+ left=convenio_left[5] * cm,
+ top=convenio_top,
+ ),
+ Label(
+ text=_("Data D.O."),
+ left=convenio_left[6] * cm,
+ top=convenio_top,
+ ),
],
- borders={'bottom': True}
+ borders={"bottom": True},
),
band_detail=ReportBand(
- default_style={'fontName': 'Helvetica', 'fontSize': 11},
+ default_style={"fontName": "Helvetica", "fontSize": 11},
height=0.5 * cm,
elements=[
- ObjectValue(attribute_name='projeto.sigla', left=convenio_left[0] * cm),
- ObjectValue(attribute_name='num_convenio', left=convenio_left[1] * cm),
- ObjectValue(attribute_name='num_processo_sf', left=convenio_left[2] * cm),
- ObjectValue(attribute_name='data_adesao', left=convenio_left[3] * cm,
- get_value=lambda instance:
- instance.data_adesao.strftime('%d/%m/%Y') if instance.data_adesao is not None else '-'
- ),
- ObjectValue(attribute_name='data_retorno_assinatura', left=convenio_left[4] * cm,
- get_value=lambda instance:
- instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura is not None else '-'
- ),
- ObjectValue(attribute_name='data_termo_aceite', left=convenio_left[5] * cm,
- get_value=lambda instance:
- instance.data_termo_aceite.strftime('%d/%m/%Y') if instance.data_termo_aceite is not None else '-'
- ),
- ObjectValue(attribute_name='data_pub_diario', left=convenio_left[6] * cm,
- get_value=lambda instance:
- instance.data_pub_diario.strftime('%d/%m/%Y') if instance.data_pub_diario is not None else '-'
- ),
+ ObjectValue(
+ attribute_name="projeto.sigla",
+ left=convenio_left[0] * cm,
+ ),
+ ObjectValue(
+ attribute_name="num_convenio",
+ left=convenio_left[1] * cm,
+ ),
+ ObjectValue(
+ attribute_name="num_processo_sf",
+ left=convenio_left[2] * cm,
+ ),
+ ObjectValue(
+ attribute_name="data_adesao",
+ left=convenio_left[3] * cm,
+ get_value=lambda instance: instance.data_adesao.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_adesao is not None
+ else "-",
+ ),
+ ObjectValue(
+ attribute_name="data_retorno_assinatura",
+ left=convenio_left[4] * cm,
+ get_value=lambda instance: instance.data_retorno_assinatura.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_retorno_assinatura is not None
+ else "-",
+ ),
+ ObjectValue(
+ attribute_name="data_termo_aceite",
+ left=convenio_left[5] * cm,
+ get_value=lambda instance: instance.data_termo_aceite.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_termo_aceite is not None
+ else "-",
+ ),
+ ObjectValue(
+ attribute_name="data_pub_diario",
+ left=convenio_left[6] * cm,
+ get_value=lambda instance: instance.data_pub_diario.strftime(
+ "%d/%m/%Y"
+ )
+ if instance.data_pub_diario is not None
+ else "-",
+ ),
],
- #borders = {'all':True},
+ # borders = {'all':True},
),
- )
+ ),
]
diff --git a/sigi/apps/parlamentares/test_parlamentares.py b/sigi/apps/parlamentares/test_parlamentares.py
index 271820d..2259a8e 100644
--- a/sigi/apps/parlamentares/test_parlamentares.py
+++ b/sigi/apps/parlamentares/test_parlamentares.py
@@ -10,7 +10,9 @@ pytestmark = pytest.mark.django_db
@pytest.fixture
def some_parliamentarians():
- return parliamentarians_from_names(["Andre Silva", "Bartolomeu Gusmao", "Camila Carla"])
+ return parliamentarians_from_names(
+ ["Andre Silva", "Bartolomeu Gusmao", "Camila Carla"]
+ )
def parliamentarians_from_names(names):
@@ -18,7 +20,7 @@ def parliamentarians_from_names(names):
def test_list_all(some_parliamentarians, app):
- response = app.get('/parlamentares/parlamentar/')
+ response = app.get("/parlamentares/parlamentar/")
assert response.status_code == 200
for x in some_parliamentarians:
@@ -26,7 +28,7 @@ def test_list_all(some_parliamentarians, app):
def test_list_filtered_by_capital_letter(some_parliamentarians, app):
- response = app.get('/parlamentares/parlamentar/?nome_completo=B')
+ response = app.get("/parlamentares/parlamentar/?nome_completo=B")
assert response.status_code == 200
a, b, c = some_parliamentarians
diff --git a/sigi/apps/parlamentares/urls.py b/sigi/apps/parlamentares/urls.py
index 395ef31..9b1b8b1 100644
--- a/sigi/apps/parlamentares/urls.py
+++ b/sigi/apps/parlamentares/urls.py
@@ -2,16 +2,25 @@
from django.conf.urls import patterns, url
urlpatterns = patterns(
- 'sigi.apps.parlamentares.views',
-
+ "sigi.apps.parlamentares.views",
# Reports labels parlamentares
- url(r'^parlamentar/labels/$', 'labels_report', name='labels-report-all'),
- url(r'^parlamentar/(?P\w+)/labels/$', 'labels_report', name='labels-report-id'),
-
+ url(r"^parlamentar/labels/$", "labels_report", name="labels-report-all"),
+ url(
+ r"^parlamentar/(?P\w+)/labels/$",
+ "labels_report",
+ name="labels-report-id",
+ ),
# Carrinho
- url(r'^parlamentar/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
- url(r'^parlamentar/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho'),
-
+ url(
+ r"^parlamentar/carrinho/$",
+ "visualizar_carrinho",
+ name="visualizar-carrinho",
+ ),
+ url(
+ r"^parlamentar/carrinho/deleta_itens_carrinho$",
+ "deleta_itens_carrinho",
+ name="deleta-itens-carrinho",
+ ),
# A view excluir_carrinho n existe ainda.
# url(r'^parlamentar/carrinho/exluir_carrinho$', 'excluir_carrinho', name='excluir-carrinho'),
)
diff --git a/sigi/apps/parlamentares/views.py b/sigi/apps/parlamentares/views.py
index d7f2090..74bd63b 100644
--- a/sigi/apps/parlamentares/views.py
+++ b/sigi/apps/parlamentares/views.py
@@ -19,17 +19,17 @@ from django.contrib.auth.decorators import login_required
def adicionar_parlamentar_carrinho(request, queryset=None, id=None):
- if request.method == 'POST':
- ids_selecionados = request.POST.getlist('_selected_action')
- if 'carrinho_parlametar' not in request.session:
- request.session['carrinho_parlamentar'] = ids_selecionados
+ if request.method == "POST":
+ ids_selecionados = request.POST.getlist("_selected_action")
+ if "carrinho_parlametar" not in request.session:
+ request.session["carrinho_parlamentar"] = ids_selecionados
else:
- lista = request.session['carrinho_parlamentar']
+ lista = request.session["carrinho_parlamentar"]
# Verifica se id já não está adicionado
for id in ids_selecionados:
if id not in lista:
lista.append(id)
- request.session['carrinho_parlamentar'] = lista
+ request.session["carrinho_parlamentar"] = lista
@login_required
@@ -43,7 +43,7 @@ def visualizar_carrinho(request):
# Make sure page request is an int. If not, deliver first page.
# Esteja certo de que o `page request` é um inteiro. Se não, mostre a primeira página.
try:
- page = int(request.GET.get('page', '1'))
+ page = int(request.GET.get("page", "1"))
except ValueError:
page = 1
@@ -53,25 +53,25 @@ def visualizar_carrinho(request):
except (EmptyPage, InvalidPage):
paginas = paginator.page(paginator.num_pages)
- carrinhoIsEmpty = not('carrinho_parlamentares' in request.session)
+ carrinhoIsEmpty = not ("carrinho_parlamentares" in request.session)
return render(
request,
- 'parlamentares/carrinho.html',
+ "parlamentares/carrinho.html",
{
- 'carIsEmpty': carrinhoIsEmpty,
- 'paginas': paginas,
- 'query_str': '?' + request.META['QUERY_STRING']
- }
+ "carIsEmpty": carrinhoIsEmpty,
+ "paginas": paginas,
+ "query_str": "?" + request.META["QUERY_STRING"],
+ },
)
def carrinhoOrGet_for_qs(request):
"""
- Verifica se existe parlamentares na sessão se não verifica get e retorna qs correspondente.
+ Verifica se existe parlamentares na sessão se não verifica get e retorna qs correspondente.
"""
- if 'carrinho_parlamentar' in request.session:
- ids = request.session['carrinho_parlamentar']
+ if "carrinho_parlamentar" in request.session:
+ ids = request.session["carrinho_parlamentar"]
qs = Parlamentar.objects.filter(pk__in=ids)
else:
qs = Parlamentar.objects.all()
@@ -81,10 +81,10 @@ def carrinhoOrGet_for_qs(request):
def query_ordena(qs, o, ot):
- list_display = ('nome_completo',)
+ list_display = ("nome_completo",)
aux = list_display[(int(o) - 1)]
- if ot == 'asc':
+ if ot == "asc":
qs = qs.order_by(aux)
else:
qs = qs.order_by("-" + aux)
@@ -97,8 +97,8 @@ def get_for_qs(get, qs):
"""
kwargs = {}
for k, v in get.iteritems():
- if not (k == 'page' or k == 'pop' or k == 'q'):
- if not k == 'o':
+ if not (k == "page" or k == "pop" or k == "q"):
+ if not k == "o":
if k == "ot":
qs = query_ordena(qs, get["o"], get["ot"])
else:
@@ -106,33 +106,34 @@ def get_for_qs(get, qs):
qs = qs.filter(**kwargs)
return qs
+
@login_required
def deleta_itens_carrinho(request):
"""
Deleta itens selecionados do carrinho
"""
- if request.method == 'POST':
- ids_selecionados = request.POST.getlist('_selected_action')
- if 'carrinho_parlamentar' in request.session:
- lista = request.session['carrinho_parlamentar']
+ if request.method == "POST":
+ ids_selecionados = request.POST.getlist("_selected_action")
+ if "carrinho_parlamentar" in request.session:
+ lista = request.session["carrinho_parlamentar"]
for item in ids_selecionados:
lista.remove(item)
if lista:
- request.session['carrinho_parlamentar'] = lista
+ request.session["carrinho_parlamentar"] = lista
else:
del lista
- del request.session['carrinho_parlamentar']
+ del request.session["carrinho_parlamentar"]
+
+ return HttpResponseRedirect(".")
- return HttpResponseRedirect('.')
@login_required
-def labels_report(request, id=None, formato='3x9_etiqueta'):
- """ TODO: adicionar suporte para resultado de pesquisa do admin.
- """
+def labels_report(request, id=None, formato="3x9_etiqueta"):
+ """TODO: adicionar suporte para resultado de pesquisa do admin."""
if request.POST:
- if 'tipo_etiqueta' in request.POST:
- tipo = request.POST['tipo_etiqueta']
+ if "tipo_etiqueta" in request.POST:
+ tipo = request.POST["tipo_etiqueta"]
if id:
qs = Parlamentar.objects.filter(pk=id)
@@ -141,10 +142,10 @@ def labels_report(request, id=None, formato='3x9_etiqueta'):
qs = carrinhoOrGet_for_qs(request)
if not qs:
- return HttpResponseRedirect('../')
+ return HttpResponseRedirect("../")
- response = HttpResponse(content_type='application/pdf')
- response['Content-Disposition'] = 'attachment; filename=casas.pdf'
+ response = HttpResponse(content_type="application/pdf")
+ response["Content-Disposition"] = "attachment; filename=casas.pdf"
report = ParlamentaresLabels(queryset=qs, formato=formato)
report.generate_by(PDFGenerator, filename=response)
diff --git a/sigi/apps/relatorios/reports.py b/sigi/apps/relatorios/reports.py
index 217e479..e2dc5aa 100644
--- a/sigi/apps/relatorios/reports.py
+++ b/sigi/apps/relatorios/reports.py
@@ -1,9 +1,19 @@
-#-*- coding:utf-8 -*-
+# -*- coding:utf-8 -*-
import os
from django.templatetags.static import static
from django.utils.translation import gettext as _
-from geraldo import Report, ReportBand, ObjectValue, DetailBand, Label, SystemField, BAND_WIDTH, FIELD_ACTION_COUNT, Line
+from geraldo import (
+ Report,
+ ReportBand,
+ ObjectValue,
+ DetailBand,
+ Label,
+ SystemField,
+ BAND_WIDTH,
+ FIELD_ACTION_COUNT,
+ Line,
+)
from geraldo.graphics import Image
from reportlab.lib.colors import navy
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
@@ -12,63 +22,106 @@ from reportlab.lib.units import cm
class ReportDefault(Report):
- #__metaclass__ = ABCMeta
- title = _('Relatório')
- author = _('Interlegis')
+ # __metaclass__ = ABCMeta
+ title = _("Relatório")
+ author = _("Interlegis")
print_if_empty = True
page_size = A4
class band_page_header(ReportBand):
height = 4.2 * cm
label_top = 3.7 * cm
- default_style = {'fontName': 'Helvetica', 'fontSize': 9}
+ default_style = {"fontName": "Helvetica", "fontSize": 9}
- BASE_DIR = os.path.abspath(os.path.dirname(__file__) + '../../../../')
- #BASE_DIR = os.path.abspath(os.getcwd() + '../..')
+ BASE_DIR = os.path.abspath(os.path.dirname(__file__) + "../../../../")
+ # BASE_DIR = os.path.abspath(os.getcwd() + '../..')
elements = [
- Image(filename=BASE_DIR + static('img/logo-interlegis.jpg'),
- left=15.5 * cm, right=1 * cm, top=0.1 * cm, bottom=1 * cm,
- width=4.2 * cm, height=3 * cm,
- ),
- Image(filename=BASE_DIR + static('img/logo-senado.png'),
- left=1 * cm, right=1 * cm, top=0.1 * cm, bottom=1 * cm,
- width=3 * cm, height=3 * cm,
- ),
- Label(text=_("SENADO FEDERAL"), top=1 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 14, 'alignment': TA_CENTER}
- ),
- Label(text=_("SINTER - Secretaria Especial do Interlegis"), top=1.5 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 13, 'alignment': TA_CENTER}
- ),
+ Image(
+ filename=BASE_DIR + static("img/logo-interlegis.jpg"),
+ left=15.5 * cm,
+ right=1 * cm,
+ top=0.1 * cm,
+ bottom=1 * cm,
+ width=4.2 * cm,
+ height=3 * cm,
+ ),
+ Image(
+ filename=BASE_DIR + static("img/logo-senado.png"),
+ left=1 * cm,
+ right=1 * cm,
+ top=0.1 * cm,
+ bottom=1 * cm,
+ width=3 * cm,
+ height=3 * cm,
+ ),
+ Label(
+ text=_("SENADO FEDERAL"),
+ top=1 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 14,
+ "alignment": TA_CENTER,
+ },
+ ),
+ Label(
+ text=_("SINTER - Secretaria Especial do Interlegis"),
+ top=1.5 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 13,
+ "alignment": TA_CENTER,
+ },
+ ),
SystemField(
- expression='%(report_title)s', top=2.5 * cm, left=0, width=BAND_WIDTH,
- style={'fontName': 'Helvetica-Bold', 'fontSize': 14, 'alignment': TA_CENTER}
+ expression="%(report_title)s",
+ top=2.5 * cm,
+ left=0,
+ width=BAND_WIDTH,
+ style={
+ "fontName": "Helvetica-Bold",
+ "fontSize": 14,
+ "alignment": TA_CENTER,
+ },
),
]
- borders = {'bottom': True}
+ borders = {"bottom": True}
class band_page_footer(ReportBand):
height = 1 * cm
elements = [
- SystemField(expression=_('%(now:%d/%m/%Y)s às %(now:%H:%M)s'), top=0.3 * cm),
- SystemField(expression=_('Página %(page_number)d de %(page_count)d'), top=0.3 * cm,
- width=BAND_WIDTH, style={'alignment': TA_RIGHT}
- ),
+ SystemField(
+ expression=_("%(now:%d/%m/%Y)s às %(now:%H:%M)s"), top=0.3 * cm
+ ),
+ SystemField(
+ expression=_("Página %(page_number)d de %(page_count)d"),
+ top=0.3 * cm,
+ width=BAND_WIDTH,
+ style={"alignment": TA_RIGHT},
+ ),
]
- #borders = {'top': True}
+ # borders = {'top': True}
class band_detail(DetailBand):
height = 0.5 * cm
- default_style = {'fontName': 'Helvetica', 'fontSize': 8}
+ default_style = {"fontName": "Helvetica", "fontSize": 8}
auto_expand_height = True
class band_summary(ReportBand):
height = 0.8 * cm
elements = [
Label(text=_("Total") + ":", top=0.1 * cm, left=0),
- ObjectValue(attribute_name='id', top=0.1 * cm, left=1 * cm,
- action=FIELD_ACTION_COUNT, display_format='%s'),
+ ObjectValue(
+ attribute_name="id",
+ top=0.1 * cm,
+ left=1 * cm,
+ action=FIELD_ACTION_COUNT,
+ display_format="%s",
+ ),
]
- borders = {'top': Line(stroke_color=navy, stroke_width=2)}
+ borders = {"top": Line(stroke_color=navy, stroke_width=2)}
diff --git a/sigi/apps/servicos/admin.py b/sigi/apps/servicos/admin.py
index 0c03843..969bb2b 100644
--- a/sigi/apps/servicos/admin.py
+++ b/sigi/apps/servicos/admin.py
@@ -7,39 +7,60 @@ from django.utils.translation import gettext as _
from import_export.fields import Field
from sigi.apps.casas.admin import FuncionariosInline, GerentesInterlegisFilter
from sigi.apps.casas.models import Orgao
-from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida,
- TipoServico)
+from sigi.apps.servicos.models import (
+ Servico,
+ LogServico,
+ CasaAtendida,
+ TipoServico,
+)
from sigi.apps.servicos.filters import ServicoAtivoFilter, DataUtimoUsoFilter
from sigi.apps.servicos.forms import ServicoFormAdmin
from sigi.apps.utils.filters import DateRangeFilter
from sigi.apps.utils.mixins import CartExportMixin, LabeledResourse
+
class ServicoExportResourse(LabeledResourse):
- telefone_casa = Field(column_name='Casa Legislativa/telefone')
- hospedagem_interlegis = Field(column_name='hospedagem no interlegis')
+ telefone_casa = Field(column_name="Casa Legislativa/telefone")
+ hospedagem_interlegis = Field(column_name="hospedagem no interlegis")
+
class Meta:
model = Servico
- fields = ('casa_legislativa__nome', 'casa_legislativa__municipio__nome',
- 'casa_legislativa__municipio__uf__sigla',
- 'casa_legislativa__email', 'telefone_casa',
- 'contato_tecnico__nome', 'contato_tecnico__email',
- 'contato_tecnico__nota', 'tipo_servico__nome', 'url',
- 'hospedagem_interlegis', 'data_ativacao', 'data_desativacao',
- 'motivo_desativacao', 'data_ultimo_uso', 'erro_atualizacao')
+ fields = (
+ "casa_legislativa__nome",
+ "casa_legislativa__municipio__nome",
+ "casa_legislativa__municipio__uf__sigla",
+ "casa_legislativa__email",
+ "telefone_casa",
+ "contato_tecnico__nome",
+ "contato_tecnico__email",
+ "contato_tecnico__nota",
+ "tipo_servico__nome",
+ "url",
+ "hospedagem_interlegis",
+ "data_ativacao",
+ "data_desativacao",
+ "motivo_desativacao",
+ "data_ultimo_uso",
+ "erro_atualizacao",
+ )
export_order = fields
+
def dehydrate_telefone_casa(self, servico):
return force_str(servico.casa_legislativa.telefone)
+
def dehydrate_hospedagem_interlegis(self, servico):
if servico.hospedagem_interlegis:
return _("Sim")
else:
return _("Não")
+
class LogServicoInline(admin.StackedInline):
model = LogServico
- Fieldset = ((None, {'fields': (('data', 'descricao'), 'log')}))
+ Fieldset = (None, {"fields": (("data", "descricao"), "log")})
extra = 1
+
class ContatosInline(FuncionariosInline):
can_delete = False # Equipe do SEIT não pode excluir pessoas de contato
# SEIT see all contacts, including President
@@ -47,143 +68,239 @@ class ContatosInline(FuncionariosInline):
return self.model.objects.all()
def get_queryset(self, request):
- return (self.model.objects.exclude(desativado=True)
- .extra(select={'ult_null': 'ult_alteracao is null'})
- .order_by('ult_null', '-ult_alteracao')
+ return (
+ self.model.objects.exclude(desativado=True)
+ .extra(select={"ult_null": "ult_alteracao is null"})
+ .order_by("ult_null", "-ult_alteracao")
# A função extra foi usada para quando existir um registro com o campo igual a null não aparecer na frente dos mais novos
)
+
@admin.register(TipoServico)
class TipoServicoAdmin(admin.ModelAdmin):
- list_display = ('id', 'sigla', 'nome', 'qtde_casas_atendidas', )
- ordering = ['id']
+ list_display = (
+ "id",
+ "sigla",
+ "nome",
+ "qtde_casas_atendidas",
+ )
+ ordering = ["id"]
+
@admin.register(Servico)
class ServicoAdmin(CartExportMixin, admin.ModelAdmin):
form = ServicoFormAdmin
- actions = ['calcular_data_uso', ]
- list_display = ('casa_legislativa', 'get_codigo_interlegis', 'get_uf',
- 'tipo_servico', 'hospedagem_interlegis', 'data_ativacao',
- 'data_desativacao', 'getUrl', 'data_ultimo_uso',
- 'get_link_erro')
- fieldsets = ((None, {
- 'fields': ('casa_legislativa', 'data_ativacao',)
- }),
- (_('Serviço'), {
- 'fields': ('tipo_servico', ('url', 'hospedagem_interlegis'),
- ('nome_servidor', 'porta_servico', 'senha_inicial'),)
- }),
- (_('Contatos'), {
- 'fields': ('contato_tecnico', 'contato_administrativo',)
- }),
- (_('Alterações'), {
- 'fields': ('data_alteracao', 'data_desativacao',
- 'motivo_desativacao',)
- }))
- readonly_fields = ('casa_legislativa', 'data_ativacao', 'data_alteracao')
+ actions = [
+ "calcular_data_uso",
+ ]
+ list_display = (
+ "casa_legislativa",
+ "get_codigo_interlegis",
+ "get_uf",
+ "tipo_servico",
+ "hospedagem_interlegis",
+ "data_ativacao",
+ "data_desativacao",
+ "getUrl",
+ "data_ultimo_uso",
+ "get_link_erro",
+ )
+ fieldsets = (
+ (
+ None,
+ {
+ "fields": (
+ "casa_legislativa",
+ "data_ativacao",
+ )
+ },
+ ),
+ (
+ _("Serviço"),
+ {
+ "fields": (
+ "tipo_servico",
+ ("url", "hospedagem_interlegis"),
+ ("nome_servidor", "porta_servico", "senha_inicial"),
+ )
+ },
+ ),
+ (
+ _("Contatos"),
+ {
+ "fields": (
+ "contato_tecnico",
+ "contato_administrativo",
+ )
+ },
+ ),
+ (
+ _("Alterações"),
+ {
+ "fields": (
+ "data_alteracao",
+ "data_desativacao",
+ "motivo_desativacao",
+ )
+ },
+ ),
+ )
+ readonly_fields = ("casa_legislativa", "data_ativacao", "data_alteracao")
list_filter = (
- 'tipo_servico',
- 'hospedagem_interlegis',
- ('data_ativacao', DateRangeFilter),
- ('data_desativacao', ServicoAtivoFilter),
+ "tipo_servico",
+ "hospedagem_interlegis",
+ ("data_ativacao", DateRangeFilter),
+ ("data_desativacao", ServicoAtivoFilter),
DataUtimoUsoFilter,
- ('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter),
- 'casa_legislativa__municipio__uf',
+ ("casa_legislativa__gerentes_interlegis", GerentesInterlegisFilter),
+ "casa_legislativa__municipio__uf",
)
list_display_links = []
- ordering = ('casa_legislativa__municipio__uf', 'casa_legislativa',
- 'tipo_servico',)
+ ordering = (
+ "casa_legislativa__municipio__uf",
+ "casa_legislativa",
+ "tipo_servico",
+ )
inlines = (LogServicoInline,)
- search_fields = ('casa_legislativa__search_text',)
+ search_fields = ("casa_legislativa__search_text",)
resource_class = ServicoExportResourse
def get_codigo_interlegis(self, obj):
return obj.casa_legislativa.codigo_interlegis
- get_codigo_interlegis.short_description = _('Código Interlegis')
+
+ get_codigo_interlegis.short_description = _("Código Interlegis")
get_codigo_interlegis.admin_order_field = (
- 'casa_legislativa__codigo_interlegis'
+ "casa_legislativa__codigo_interlegis"
)
def get_uf(self, obj):
- return '%s' % (obj.casa_legislativa.municipio.uf)
- get_uf.short_description = _('UF')
- get_uf.admin_order_field = 'casa_legislativa__municipio__uf'
+ return "%s" % (obj.casa_legislativa.municipio.uf)
+
+ get_uf.short_description = _("UF")
+ get_uf.admin_order_field = "casa_legislativa__municipio__uf"
def getUrl(self, obj):
return mark_safe(f'{obj.url} ')
- getUrl.short_description = _('Url')
+
+ getUrl.short_description = _("Url")
def get_link_erro(self, obj):
if not obj.erro_atualizacao:
return ""
url = obj.url
- if url[-1] != '/':
- url += '/'
+ if url[-1] != "/":
+ url += "/"
if obj.tipo_servico.string_pesquisa:
- url += obj.tipo_servico.string_pesquisa.splitlines()[0].split(" ")[0]
+ url += obj.tipo_servico.string_pesquisa.splitlines()[0].split(" ")[
+ 0
+ ]
return mark_safe(
f'{obj.erro_atualizacao} '
)
+
get_link_erro.short_description = _("Erro na atualização")
- get_link_erro.admin_order_field = 'erro_atualizacao'
+ get_link_erro.admin_order_field = "erro_atualizacao"
def calcular_data_uso(self, request, queryset):
for servico in queryset:
servico.atualiza_data_uso()
- self.message_user(request, _("Atualização concluída. Os sites que não "
- "responderam foram deixados com a data "
- "em branco"))
- return HttpResponseRedirect('.')
+ self.message_user(
+ request,
+ _(
+ "Atualização concluída. Os sites que não "
+ "responderam foram deixados com a data "
+ "em branco"
+ ),
+ )
+ return HttpResponseRedirect(".")
+
calcular_data_uso.short_description = _(
"Atualizar a data do último uso do(s) serviço(s)"
)
def lookup_allowed(self, lookup, value):
- return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact', ]
+ return super(ServicoAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in [
+ "casa_legislativa__municipio__uf__codigo_ibge__exact",
+ ]
- def add_view(self, request, form_url='', extra_context=None):
- id_casa = request.GET.get('id_casa', None)
+ def add_view(self, request, form_url="", extra_context=None):
+ id_casa = request.GET.get("id_casa", None)
if not id_casa:
raise Http404
- return super(ServicoAdmin, self).add_view(request, form_url,
- extra_context=extra_context)
+ return super(ServicoAdmin, self).add_view(
+ request, form_url, extra_context=extra_context
+ )
def response_add(self, request, obj):
opts = obj._meta
- msg = (_('The %(name)s "%(obj)s" was added successfully.') %
- {'name': force_str(opts.verbose_name),
- 'obj': force_str(obj)}
- )
+ msg = _('The %(name)s "%(obj)s" was added successfully.') % {
+ "name": force_str(opts.verbose_name),
+ "obj": force_str(obj),
+ }
if "_addanother" in request.POST:
- self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_str(opts.verbose_name)))
- return HttpResponseRedirect(request.path + '?id_casa=%s' % (obj.casa_legislativa.id,))
+ self.message_user(
+ request,
+ msg
+ + " "
+ + (
+ _("You may add another %s below.")
+ % force_str(opts.verbose_name)
+ ),
+ )
+ return HttpResponseRedirect(
+ request.path + "?id_casa=%s" % (obj.casa_legislativa.id,)
+ )
elif "_save" in request.POST:
self.message_user(request, msg)
- return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id]))
+ return HttpResponseRedirect(
+ reverse(
+ "admin:servicos_casaatendida_change",
+ args=[obj.casa_legislativa.id],
+ )
+ )
return super(ServicoAdmin, self).response_add(request, obj)
def response_change(self, request, obj):
opts = obj._meta
- msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_str(opts.verbose_name), 'obj': force_str(obj)}
+ msg = _('The %(name)s "%(obj)s" was changed successfully.') % {
+ "name": force_str(opts.verbose_name),
+ "obj": force_str(obj),
+ }
if "_addanother" in request.POST:
- self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_str(opts.verbose_name)))
- return HttpResponseRedirect("../add/?id_casa=%s" % (obj.casa_legislativa.id,))
+ self.message_user(
+ request,
+ msg
+ + " "
+ + (
+ _("You may add another %s below.")
+ % force_str(opts.verbose_name)
+ ),
+ )
+ return HttpResponseRedirect(
+ "../add/?id_casa=%s" % (obj.casa_legislativa.id,)
+ )
elif "_save" in request.POST:
self.message_user(request, msg)
- return HttpResponseRedirect(reverse('admin:servicos_casaatendida_change', args=[obj.casa_legislativa.id]))
+ return HttpResponseRedirect(
+ reverse(
+ "admin:servicos_casaatendida_change",
+ args=[obj.casa_legislativa.id],
+ )
+ )
return super(ServicoAdmin, self).response_change(request, obj)
def save_form(self, request, form, change):
obj = super(ServicoAdmin, self).save_form(request, form, change)
if not change:
- id_casa = request.GET.get('id_casa', None)
+ id_casa = request.GET.get("id_casa", None)
if not id_casa:
raise Http404
obj.casa_legislativa = Orgao.objects.get(pk=id_casa)
@@ -191,34 +308,59 @@ class ServicoAdmin(CartExportMixin, admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
from sigi.apps.convenios.views import normaliza_data
+
request.GET._mutable = True
- normaliza_data(request.GET, 'data_ativacao__gte')
- normaliza_data(request.GET, 'data_ativacao__lte')
+ normaliza_data(request.GET, "data_ativacao__gte")
+ normaliza_data(request.GET, "data_ativacao__lte")
request.GET._mutable = False
return super(ServicoAdmin, self).changelist_view(
request,
- extra_context={'query_str': '?' + request.META['QUERY_STRING']}
+ extra_context={"query_str": "?" + request.META["QUERY_STRING"]},
)
+
@admin.register(CasaAtendida)
class CasaAtendidaAdmin(admin.ModelAdmin):
actions = None
- list_display = ('codigo_interlegis', 'nome', 'get_servicos',)
- ordering = ['nome']
+ list_display = (
+ "codigo_interlegis",
+ "nome",
+ "get_servicos",
+ )
+ ordering = ["nome"]
fieldsets = (
- ('Casa Legislativa', {
- 'fields': (('codigo_interlegis', 'nome'), ('logradouro', 'bairro',
- 'municipio', 'cep'),
- ('email', 'pagina_web'))
- }),)
- readonly_fields = ('nome', 'logradouro', 'bairro', 'municipio', 'cep')
+ (
+ "Casa Legislativa",
+ {
+ "fields": (
+ ("codigo_interlegis", "nome"),
+ ("logradouro", "bairro", "municipio", "cep"),
+ ("email", "pagina_web"),
+ )
+ },
+ ),
+ )
+ readonly_fields = ("nome", "logradouro", "bairro", "municipio", "cep")
inlines = (ContatosInline,)
- list_filter = ('tipo', 'servico__tipo_servico', 'municipio__uf__nome',
- 'servico__casa_legislativa__convenio__projeto')
- search_fields = ('search_text', 'cnpj', 'bairro', 'logradouro',
- 'cep', 'municipio__nome', 'municipio__uf__nome',
- 'municipio__codigo_ibge', 'pagina_web', 'observacoes')
+ list_filter = (
+ "tipo",
+ "servico__tipo_servico",
+ "municipio__uf__nome",
+ "servico__casa_legislativa__convenio__projeto",
+ )
+ search_fields = (
+ "search_text",
+ "cnpj",
+ "bairro",
+ "logradouro",
+ "cep",
+ "municipio__nome",
+ "municipio__uf__nome",
+ "municipio__codigo_ibge",
+ "pagina_web",
+ "observacoes",
+ )
def get_servicos(self, obj):
result = [
@@ -228,21 +370,28 @@ class CasaAtendidaAdmin(admin.ModelAdmin):
]
return mark_safe("")
+
get_servicos.short_description = _("Serviços")
def lookup_allowed(self, lookup, value):
- return super(CasaAtendidaAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['municipio__uf__codigo_ibge__exact', 'servico__tipo_servico__id__exact', ]
+ return super(CasaAtendidaAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in [
+ "municipio__uf__codigo_ibge__exact",
+ "servico__tipo_servico__id__exact",
+ ]
def change_view(self, request, object_id, extra_context=None):
# Se a Casa ainda não é atendida, gerar o código interlegis para ela
# Assim ela passa a ser uma casa atendida
casa = Orgao.objects.get(id=object_id)
- if casa.codigo_interlegis == '':
+ if casa.codigo_interlegis == "":
casa.gerarCodigoInterlegis()
- return super(CasaAtendidaAdmin, self).change_view(request, object_id, extra_context=extra_context)
+ return super(CasaAtendidaAdmin, self).change_view(
+ request, object_id, extra_context=extra_context
+ )
def has_add_permission(self, request):
return False # Nunca é permitido inserir uma nova Casa Legislativa por aqui
diff --git a/sigi/apps/servicos/apps.py b/sigi/apps/servicos/apps.py
index 6df6334..7801a93 100644
--- a/sigi/apps/servicos/apps.py
+++ b/sigi/apps/servicos/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class ServicosConfig(AppConfig):
- name = 'sigi.apps.servicos'
- verbose_name = _('serviços SEIT')
+ name = "sigi.apps.servicos"
+ verbose_name = _("serviços SEIT")
diff --git a/sigi/apps/servicos/filters.py b/sigi/apps/servicos/filters.py
index ba432b1..dee8f2c 100644
--- a/sigi/apps/servicos/filters.py
+++ b/sigi/apps/servicos/filters.py
@@ -2,13 +2,14 @@ from datetime import date, timedelta
from django.utils.translation import gettext as _
from django.contrib import admin
+
class ServicoAtivoFilter(admin.FieldListFilter):
parameter_name = None
def __init__(self, field, request, params, model, model_admin, field_path):
self.model = model
self.model_admin = model_admin
- self.parameter_name = f'{field_path}__isnull'
+ self.parameter_name = f"{field_path}__isnull"
super().__init__(field, request, params, model, model_admin, field_path)
@@ -24,10 +25,7 @@ class ServicoAtivoFilter(admin.FieldListFilter):
self.lookup_choices = list(lookup_choices)
def lookups(self, request, model_admin):
- return (
- ('True', _('Ativo')),
- ('False', _('Inativo'))
- )
+ return (("True", _("Ativo")), ("False", _("Inativo")))
def has_output(self):
return self.model.objects.exists()
@@ -36,61 +34,73 @@ class ServicoAtivoFilter(admin.FieldListFilter):
return self.used_parameters.get(self.parameter_name)
def expected_parameters(self):
- return [self.parameter_name,]
+ return [
+ self.parameter_name,
+ ]
def choices(self, changelist):
yield {
- 'selected': self.value() is None,
- 'query_string': changelist.get_query_string(
- remove=[self.parameter_name]),
- 'display': _('All'),
+ "selected": self.value() is None,
+ "query_string": changelist.get_query_string(
+ remove=[self.parameter_name]
+ ),
+ "display": _("All"),
}
for lookup, title in self.lookup_choices:
yield {
- 'selected': str(self.value()) == str(lookup),
- 'query_string': changelist.get_query_string(
+ "selected": str(self.value()) == str(lookup),
+ "query_string": changelist.get_query_string(
{self.parameter_name: lookup}
),
- 'display': title,
+ "display": title,
}
+
class DataUtimoUsoFilter(admin.SimpleListFilter):
title = _("Atualização")
- parameter_name = 'atualizacao'
+ parameter_name = "atualizacao"
def lookups(self, request, model_admin):
return (
- ('err', _("Erro na verificação")),
- ('year', _("Sem atualização há um ano ou mais")),
- ('semester', _("Sem atualização de seis meses a um ano")),
- ('quarter', _("Sem atualização de três a seis meses")),
- ('month', _("Sem atualização de um a três meses")),
- ('week', _("Sem atualização de uma semana a um mês")),
- ('updated', _("Atualizado na última semana")),
+ ("err", _("Erro na verificação")),
+ ("year", _("Sem atualização há um ano ou mais")),
+ ("semester", _("Sem atualização de seis meses a um ano")),
+ ("quarter", _("Sem atualização de três a seis meses")),
+ ("month", _("Sem atualização de um a três meses")),
+ ("week", _("Sem atualização de uma semana a um mês")),
+ ("updated", _("Atualizado na última semana")),
)
def queryset(self, request, queryset):
if self.value() is not None:
queryset = queryset.exclude(tipo_servico__string_pesquisa="")
- if self.value() == 'err':
+ if self.value() == "err":
queryset = queryset.exclude(erro_atualizacao="")
- elif self.value() == 'year':
+ elif self.value() == "year":
limite = date.today() - timedelta(days=365)
queryset = queryset.filter(data_ultimo_uso__lte=limite)
else:
de = date.today() - (
- timedelta(days=365) if self.value() == 'semester' else
- timedelta(days=6*30) if self.value() == 'quarter' else
- timedelta(days=3*30) if self.value() == 'month' else
- timedelta(days=30) if self.value() == 'week' else
- timedelta(days=0)
+ timedelta(days=365)
+ if self.value() == "semester"
+ else timedelta(days=6 * 30)
+ if self.value() == "quarter"
+ else timedelta(days=3 * 30)
+ if self.value() == "month"
+ else timedelta(days=30)
+ if self.value() == "week"
+ else timedelta(days=0)
)
ate = date.today() - (
- timedelta(days=6*30) if self.value() == 'semester' else
- timedelta(days=3*30) if self.value() == 'quarter' else
- timedelta(days=30) if self.value() == 'month' else
- timedelta(days=7) if self.value() == 'week' else
- timedelta(days=0)
+ timedelta(days=6 * 30)
+ if self.value() == "semester"
+ else timedelta(days=3 * 30)
+ if self.value() == "quarter"
+ else timedelta(days=30)
+ if self.value() == "month"
+ else timedelta(days=7)
+ if self.value() == "week"
+ else timedelta(days=0)
)
queryset = queryset.filter(data_ultimo_uso__range=(de, ate))
return queryset
diff --git a/sigi/apps/servicos/forms.py b/sigi/apps/servicos/forms.py
index c584451..18c6a09 100644
--- a/sigi/apps/servicos/forms.py
+++ b/sigi/apps/servicos/forms.py
@@ -2,21 +2,22 @@ from django.forms.models import ModelForm
from django.utils.encoding import force_str
from sigi.apps.servicos.models import Servico, CasaAtendida
+
class ServicoFormAdmin(ModelForm):
class Meta:
model = Servico
- fields = '__all__'
+ fields = "__all__"
def __init__(self, *args, **kwargs):
super(ServicoFormAdmin, self).__init__(*args, **kwargs)
- self.fields['contato_tecnico'].choices = ()
- self.fields['contato_administrativo'].choices = ()
+ self.fields["contato_tecnico"].choices = ()
+ self.fields["contato_administrativo"].choices = ()
if self.instance.casa_legislativa_id:
id_casa = self.instance.casa_legislativa_id
- elif 'initial' in kwargs and 'id_casa' in kwargs['initial']:
- id_casa = kwargs['initial']['id_casa']
+ elif "initial" in kwargs and "id_casa" in kwargs["initial"]:
+ id_casa = kwargs["initial"]["id_casa"]
self.instance.casa_legislativa_id = id_casa
else:
id_casa = None
@@ -26,5 +27,5 @@ class ServicoFormAdmin(ModelForm):
contatos = [
(f.id, force_str(f)) for f in casa.funcionario_set.all()
]
- self.fields['contato_tecnico'].choices = contatos
- self.fields['contato_administrativo'].choices = contatos
+ self.fields["contato_tecnico"].choices = contatos
+ self.fields["contato_administrativo"].choices = contatos
diff --git a/sigi/apps/servicos/management/commands/atualiza_uso_servico.py b/sigi/apps/servicos/management/commands/atualiza_uso_servico.py
index 7605c41..10723a0 100644
--- a/sigi/apps/servicos/management/commands/atualiza_uso_servico.py
+++ b/sigi/apps/servicos/management/commands/atualiza_uso_servico.py
@@ -28,12 +28,21 @@ from sigi.apps.servicos.models import Servico
class Command(BaseCommand):
- help = _('Atualiza a informação de data de último serviço dos serviços SEIT hospedados no Interlegis.')
+ help = _(
+ "Atualiza a informação de data de último serviço dos serviços SEIT hospedados no Interlegis."
+ )
def handle(self, *args, **options):
- verbosity = int(options['verbosity'])
- queryset = Servico.objects.exclude(url="").exclude(tipo_servico__string_pesquisa="")
+ verbosity = int(options["verbosity"])
+ queryset = Servico.objects.exclude(url="").exclude(
+ tipo_servico__string_pesquisa=""
+ )
for obj in queryset:
obj.atualiza_data_uso()
- if ((verbosity == 1) and (obj.data_ultimo_uso is None)) or (verbosity > 1):
- self.stdout.write("%s \t %s \t %s\n" % (obj.url, obj.data_ultimo_uso, obj.erro_atualizacao))
+ if ((verbosity == 1) and (obj.data_ultimo_uso is None)) or (
+ verbosity > 1
+ ):
+ self.stdout.write(
+ "%s \t %s \t %s\n"
+ % (obj.url, obj.data_ultimo_uso, obj.erro_atualizacao)
+ )
diff --git a/sigi/apps/servicos/management/commands/importa_servico.py b/sigi/apps/servicos/management/commands/importa_servico.py
index 316b16b..308b280 100644
--- a/sigi/apps/servicos/management/commands/importa_servico.py
+++ b/sigi/apps/servicos/management/commands/importa_servico.py
@@ -8,93 +8,111 @@ from sigi.apps.utils import to_ascii
from sigi.apps.servicos.models import Servico, TipoServico
from sigi.apps.casas.models import Orgao, Funcionario
+
class Command(BaseCommand):
args = "nome_do_arquivo.txt"
help = """
Importa dados de serviços de arquivos TXT gerados pela COTIN.
"""
+
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError("Informe UM arquivo TXT a importar")
file_name = args[0]
- self.stdout.write('Verificando estrutura do arquivo...')
+ self.stdout.write("Verificando estrutura do arquivo...")
if not os.path.isfile(file_name):
raise CommandError("Arquivo '%s' não encontrado" % file_name)
- with open(file_name, 'r') as f:
+ with open(file_name, "r") as f:
reader = csv.DictReader(f, delimiter=" ")
- if (not 'TEMPLATE' in reader.fieldnames or
- not 'NAME' in reader.fieldnames or
- not 'COD_ORGAO' in reader.fieldnames):
- print (reader.fieldnames)
+ if (
+ not "TEMPLATE" in reader.fieldnames
+ or not "NAME" in reader.fieldnames
+ or not "COD_ORGAO" in reader.fieldnames
+ ):
+ print(reader.fieldnames)
raise CommandError("Formato inválido do arquivo.")
- self.stdout.write('Estrutura parece ok.')
+ self.stdout.write("Estrutura parece ok.")
self.stdout.write("Preparando dados...")
casas = {
- to_ascii(c.municipio.nome).replace(' ','').replace('-','').replace("'", '').lower()
- + '-' + to_ascii(c.municipio.uf.sigla).lower(): c.pk
- for c in Orgao.objects.filter(tipo__sigla='CM')
+ to_ascii(c.municipio.nome)
+ .replace(" ", "")
+ .replace("-", "")
+ .replace("'", "")
+ .lower()
+ + "-"
+ + to_ascii(c.municipio.uf.sigla).lower(): c.pk
+ for c in Orgao.objects.filter(tipo__sigla="CM")
}
casas.update(
- {'al-'+to_ascii(c.municipio.uf.sigla).lower(): c.pk
- for c in Orgao.objects.filter(tipo__sigla='AL')}
+ {
+ "al-" + to_ascii(c.municipio.uf.sigla).lower(): c.pk
+ for c in Orgao.objects.filter(tipo__sigla="AL")
+ }
)
casas.update(
- {'tce-'+to_ascii(c.municipio.uf.sigla).lower(): c.pk
- for c in Orgao.objects.filter(tipo__sigla='TCE')}
+ {
+ "tce-" + to_ascii(c.municipio.uf.sigla).lower(): c.pk
+ for c in Orgao.objects.filter(tipo__sigla="TCE")
+ }
)
self.stdout.write("Processando...")
lista_tipos = set()
agora = datetime.now()
- subdominios = {'PM': 'www', 'SAPL': 'sapl',
- 'EmailLeg': 'correioadm', 'edem': 'edemocracia',
- 'LEGBR': '', 'GOVBR': ''}
+ subdominios = {
+ "PM": "www",
+ "SAPL": "sapl",
+ "EmailLeg": "correioadm",
+ "edem": "edemocracia",
+ "LEGBR": "",
+ "GOVBR": "",
+ }
can_deactivate = True
for rec in reader:
- name = rec['NAME']
- template = rec['TEMPLATE']
- cod_orgao = rec['COD_ORGAO']
+ name = rec["NAME"]
+ template = rec["TEMPLATE"]
+ cod_orgao = rec["COD_ORGAO"]
- if template == 'DNS':
- s = name.split('.')
- nome_casa = s[0]+"-"+s[1]
+ if template == "DNS":
+ s = name.split(".")
+ nome_casa = s[0] + "-" + s[1]
dominio = s[0]
sufixo = ".".join(s[1:])
- if '.leg.br' in name:
- sigla = 'LEGBR'
- elif '.gov.br' in name:
- sigla = 'GOVBR'
+ if ".leg.br" in name:
+ sigla = "LEGBR"
+ elif ".gov.br" in name:
+ sigla = "GOVBR"
else:
s = name.split("-")
nome_casa = name
dominio = name[0]
- sufixo = ".".join(s[1:]) + '.leg.br'
+ sufixo = ".".join(s[1:]) + ".leg.br"
sigla = template
- if nome_casa.startswith('camara'):
- nome_casa = nome_casa.replace('camara', '')
- if nome_casa.startswith('cm'):
- nome_casa = nome_casa.replace('cm','')
+ if nome_casa.startswith("camara"):
+ nome_casa = nome_casa.replace("camara", "")
+ if nome_casa.startswith("cm"):
+ nome_casa = nome_casa.replace("cm", "")
url = "https://{subdominio}.{dominio}.{sufixo}".format(
subdominio=subdominios[sigla],
dominio=dominio,
- sufixo=sufixo
+ sufixo=sufixo,
)
tipo_servico = TipoServico.objects.get(sigla=sigla)
lista_tipos.add(tipo_servico)
if cod_orgao is not None:
- if cod_orgao == '*':
+ if cod_orgao == "*":
self.stdout.write(
"{template} {name} {cod_orgao} "
"registro ignorado".format(
template=template,
name=name,
- cod_orgao=cod_orgao
+ cod_orgao=cod_orgao,
)
)
continue
@@ -107,7 +125,7 @@ Importa dados de serviços de arquivos TXT gerados pela COTIN.
"codigo inexistente".format(
template=template,
name=name,
- cod_orgao=cod_orgao
+ cod_orgao=cod_orgao,
)
)
can_deactivate = False
@@ -120,30 +138,33 @@ Importa dados de serviços de arquivos TXT gerados pela COTIN.
try:
servico = Servico.objects.get(
url__icontains=dominio,
- tipo_servico=tipo_servico
+ tipo_servico=tipo_servico,
)
servico.save()
continue
- except (Servico.DoesNotExist,
- Servico.MultipleObjectsReturned):
+ except (
+ Servico.DoesNotExist,
+ Servico.MultipleObjectsReturned,
+ ):
# tenta descobrir outro serviço do mesmo domínio
casa = None
for servico in Servico.objects.filter(
- url__icontains=dominio):
+ url__icontains=dominio
+ ):
if casa is None:
casa = servico.casa_legislativa
elif casa != servico.casa_legislativa:
# Mais de uma casa usando o mesmo domínio!!!
casa = None
break
- if casa is None: # Impossível identificar a casa
+ if casa is None: # Impossível identificar a casa
self.stdout.write(
"{template} {name} {cod_orgao} "
"orgao nao encontrado ({s})".format(
template=template,
name=name,
cod_orgao=cod_orgao,
- s=nome_casa
+ s=nome_casa,
)
)
can_deactivate = False
@@ -151,25 +172,27 @@ Importa dados de serviços de arquivos TXT gerados pela COTIN.
try:
contato, created = casa.funcionario_set.get_or_create(
- setor='contato_interlegis',
- defaults={'nome': "<>"}
+ setor="contato_interlegis",
+ defaults={
+ "nome": "<>"
+ },
)
except Funcionario.MultipleObjectsReturned:
contato = casa.funcionario_set.filter(
- setor='contato_interlegis',
- ).first() # Hack - pega sempre o primeiro
+ setor="contato_interlegis",
+ ).first() # Hack - pega sempre o primeiro
try:
servico, created = casa.servico_set.get_or_create(
tipo_servico=tipo_servico,
data_desativacao=None,
defaults={
- 'contato_tecnico': contato,
- 'contato_administrativo': contato,
- 'url': url,
- 'hospedagem_interlegis': True,
- 'data_ativacao': date.today()
- }
+ "contato_tecnico": contato,
+ "contato_administrativo": contato,
+ "url": url,
+ "hospedagem_interlegis": True,
+ "data_ativacao": date.today(),
+ },
)
servico.save()
except Servico.MultipleObjectsReturned:
@@ -179,7 +202,7 @@ Importa dados de serviços de arquivos TXT gerados pela COTIN.
template=template,
name=name,
cod_orgao=cod_orgao,
- s=nome_casa
+ s=nome_casa,
)
)
can_deactivate = False
@@ -190,14 +213,15 @@ Importa dados de serviços de arquivos TXT gerados pela COTIN.
data_alteracao__lt=agora
).update(
data_desativacao=agora,
- motivo_desativacao=("[AUTOMÁTICO] Não consta da lista "
- "da COTIN")
+ motivo_desativacao=(
+ "[AUTOMÁTICO] Não consta da lista " "da COTIN"
+ ),
)
else:
self.stdout.write(
- self.style.ERROR("Os serviços excendentes não podem ser "
- "desativados porque foram encontradas "
- "inconsistências no arquivo de origem")
+ self.style.ERROR(
+ "Os serviços excendentes não podem ser "
+ "desativados porque foram encontradas "
+ "inconsistências no arquivo de origem"
+ )
)
-
-
diff --git a/sigi/apps/servicos/migrations/0001_initial.py b/sigi/apps/servicos/migrations/0001_initial.py
index 9d2c183..46c0d86 100644
--- a/sigi/apps/servicos/migrations/0001_initial.py
+++ b/sigi/apps/servicos/migrations/0001_initial.py
@@ -8,135 +8,363 @@ import datetime
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0001_initial'),
+ ("casas", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='CasaManifesta',
+ name="CasaManifesta",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('data_manifestacao', models.DateTimeField(auto_now_add=True)),
- ('data_atualizacao', models.DateTimeField(auto_now=True)),
- ('informante', models.CharField(max_length=100, verbose_name='Nome do informante', blank=True)),
- ('cargo', models.CharField(max_length=100, verbose_name='Cargo do informante', blank=True)),
- ('email', models.EmailField(max_length=75, verbose_name='E-mail de contato', blank=True)),
- ('casa_legislativa', models.OneToOneField(to='casas.CasaLegislativa', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("data_manifestacao", models.DateTimeField(auto_now_add=True)),
+ ("data_atualizacao", models.DateTimeField(auto_now=True)),
+ (
+ "informante",
+ models.CharField(
+ max_length=100,
+ verbose_name="Nome do informante",
+ blank=True,
+ ),
+ ),
+ (
+ "cargo",
+ models.CharField(
+ max_length=100,
+ verbose_name="Cargo do informante",
+ blank=True,
+ ),
+ ),
+ (
+ "email",
+ models.EmailField(
+ max_length=75,
+ verbose_name="E-mail de contato",
+ blank=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.OneToOneField(
+ to="casas.CasaLegislativa", on_delete=models.CASCADE
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='LogServico',
+ name="LogServico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('descricao', models.CharField(max_length=60, verbose_name='Breve descri\xe7\xe3o da a\xe7\xe3o')),
- ('data', models.DateField(default=datetime.date.today, verbose_name='Data da a\xe7\xe3o')),
- ('log', models.TextField(verbose_name='Log da a\xe7\xe3o')),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.CharField(
+ max_length=60,
+ verbose_name="Breve descri\xe7\xe3o da a\xe7\xe3o",
+ ),
+ ),
+ (
+ "data",
+ models.DateField(
+ default=datetime.date.today,
+ verbose_name="Data da a\xe7\xe3o",
+ ),
+ ),
+ ("log", models.TextField(verbose_name="Log da a\xe7\xe3o")),
],
options={
- 'verbose_name': 'Log do servi\xe7o',
- 'verbose_name_plural': 'Logs do servi\xe7o',
+ "verbose_name": "Log do servi\xe7o",
+ "verbose_name_plural": "Logs do servi\xe7o",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='RegistroServico',
+ name="RegistroServico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('produto', models.CharField(max_length=50)),
- ('versao', models.CharField(max_length=30)),
- ('url', models.URLField()),
- ('data_registro', models.DateTimeField(auto_now=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("produto", models.CharField(max_length=50)),
+ ("versao", models.CharField(max_length=30)),
+ ("url", models.URLField()),
+ ("data_registro", models.DateTimeField(auto_now=True)),
],
options={
- 'verbose_name_plural': 'Registro de servi\xe7os',
+ "verbose_name_plural": "Registro de servi\xe7os",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Servico',
+ name="Servico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('url', models.URLField(verbose_name='URL do servi\xe7o', blank=True)),
- ('hospedagem_interlegis', models.BooleanField(default=False, verbose_name='Hospedagem no Interlegis?')),
- ('nome_servidor', models.CharField(help_text='Se hospedado no Interlegis, informe o nome do servidor. Sen\xe3o, informe o nome do provedor de servi\xe7os.', max_length=60, verbose_name='Hospedado em', blank=True)),
- ('porta_servico', models.PositiveSmallIntegerField(null=True, verbose_name='Porta de servi\xe7o (inst\xe2ncia)', blank=True)),
- ('senha_inicial', models.CharField(max_length=33, verbose_name='Senha inicial', blank=True)),
- ('data_ativacao', models.DateField(default=datetime.date.today, verbose_name='Data de ativa\xe7\xe3o')),
- ('data_alteracao', models.DateField(auto_now=True, verbose_name='Data da \xfaltima altera\xe7\xe3o', null=True)),
- ('data_desativacao', models.DateField(null=True, verbose_name='Data de desativa\xe7\xe3o', blank=True)),
- ('motivo_desativacao', models.TextField(verbose_name='Motivo da desativa\xe7\xe3o', blank=True)),
- ('data_ultimo_uso', models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vezN\xc3O \xc9 ATUALIZADO AUTOMATICAMENTE! ', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True)),
- ('erro_atualizacao', models.CharField(help_text='Erro ocorrido na \xfaltima tentativa de atualizar a data de \xfaltimo acesso', max_length=200, verbose_name='Erro na atualiza\xe7\xe3o', blank=True)),
- ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa', on_delete=models.CASCADE)),
- ('contato_administrativo', models.ForeignKey(related_name='contato_administrativo', verbose_name='Contato administrativo', to='casas.Funcionario', on_delete=models.CASCADE)),
- ('contato_tecnico', models.ForeignKey(related_name='contato_tecnico', verbose_name='Contato t\xe9cnico', to='casas.Funcionario', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "url",
+ models.URLField(
+ verbose_name="URL do servi\xe7o", blank=True
+ ),
+ ),
+ (
+ "hospedagem_interlegis",
+ models.BooleanField(
+ default=False, verbose_name="Hospedagem no Interlegis?"
+ ),
+ ),
+ (
+ "nome_servidor",
+ models.CharField(
+ help_text="Se hospedado no Interlegis, informe o nome do servidor. Sen\xe3o, informe o nome do provedor de servi\xe7os.",
+ max_length=60,
+ verbose_name="Hospedado em",
+ blank=True,
+ ),
+ ),
+ (
+ "porta_servico",
+ models.PositiveSmallIntegerField(
+ null=True,
+ verbose_name="Porta de servi\xe7o (inst\xe2ncia)",
+ blank=True,
+ ),
+ ),
+ (
+ "senha_inicial",
+ models.CharField(
+ max_length=33, verbose_name="Senha inicial", blank=True
+ ),
+ ),
+ (
+ "data_ativacao",
+ models.DateField(
+ default=datetime.date.today,
+ verbose_name="Data de ativa\xe7\xe3o",
+ ),
+ ),
+ (
+ "data_alteracao",
+ models.DateField(
+ auto_now=True,
+ verbose_name="Data da \xfaltima altera\xe7\xe3o",
+ null=True,
+ ),
+ ),
+ (
+ "data_desativacao",
+ models.DateField(
+ null=True,
+ verbose_name="Data de desativa\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "motivo_desativacao",
+ models.TextField(
+ verbose_name="Motivo da desativa\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "data_ultimo_uso",
+ models.DateField(
+ help_text="Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vezN\xc3O \xc9 ATUALIZADO AUTOMATICAMENTE! ",
+ null=True,
+ verbose_name="Data da \xfaltima utiliza\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "erro_atualizacao",
+ models.CharField(
+ help_text="Erro ocorrido na \xfaltima tentativa de atualizar a data de \xfaltimo acesso",
+ max_length=200,
+ verbose_name="Erro na atualiza\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "casa_legislativa",
+ models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.CasaLegislativa",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "contato_administrativo",
+ models.ForeignKey(
+ related_name="contato_administrativo",
+ verbose_name="Contato administrativo",
+ to="casas.Funcionario",
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "contato_tecnico",
+ models.ForeignKey(
+ related_name="contato_tecnico",
+ verbose_name="Contato t\xe9cnico",
+ to="casas.Funcionario",
+ on_delete=models.CASCADE,
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='ServicoManifesto',
+ name="ServicoManifesto",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('url', models.URLField(blank=True)),
- ('hospedagem_interlegis', models.BooleanField(default=False, verbose_name='Hospedagem no Interlegis?')),
- ('casa_manifesta', models.ForeignKey(to='servicos.CasaManifesta', on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("url", models.URLField(blank=True)),
+ (
+ "hospedagem_interlegis",
+ models.BooleanField(
+ default=False, verbose_name="Hospedagem no Interlegis?"
+ ),
+ ),
+ (
+ "casa_manifesta",
+ models.ForeignKey(
+ to="servicos.CasaManifesta", on_delete=models.CASCADE
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
migrations.CreateModel(
- name='TipoServico',
+ name="TipoServico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=60, verbose_name='Nome')),
- ('sigla', models.CharField(max_length='12', verbose_name='Sigla')),
- ('string_pesquisa', models.CharField(help_text='Sufixo para pesquisa RSS para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o', max_length=200, verbose_name='String de pesquisa', blank=True)),
- ('template_email_ativa', models.TextField(help_text='Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o', verbose_name='Template de email de ativa\xe7\xe3o', blank=True)),
- ('template_email_altera', models.TextField(help_text='Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o', verbose_name='Template de email de altera\xe7\xe3o', blank=True)),
- ('template_email_desativa', models.TextField(help_text='Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o {motivo} para incluir o motivo da desativa\xe7\xe3o do servi\xe7o', verbose_name='Template de email de desativa\xe7\xe3o', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=60, verbose_name="Nome")),
+ (
+ "sigla",
+ models.CharField(max_length="12", verbose_name="Sigla"),
+ ),
+ (
+ "string_pesquisa",
+ models.CharField(
+ help_text="Sufixo para pesquisa RSS para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o",
+ max_length=200,
+ verbose_name="String de pesquisa",
+ blank=True,
+ ),
+ ),
+ (
+ "template_email_ativa",
+ models.TextField(
+ help_text="Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o",
+ verbose_name="Template de email de ativa\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "template_email_altera",
+ models.TextField(
+ help_text="Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o",
+ verbose_name="Template de email de altera\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "template_email_desativa",
+ models.TextField(
+ help_text="Use: \n {url} para incluir a URL do servi\xe7o, \n {senha} para incluir a senha inicial do servi\xe7o {motivo} para incluir o motivo da desativa\xe7\xe3o do servi\xe7o",
+ verbose_name="Template de email de desativa\xe7\xe3o",
+ blank=True,
+ ),
+ ),
],
options={
- 'verbose_name': 'Tipo de servi\xe7o',
- 'verbose_name_plural': 'Tipos de servi\xe7o',
+ "verbose_name": "Tipo de servi\xe7o",
+ "verbose_name_plural": "Tipos de servi\xe7o",
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='servicomanifesto',
- name='servico',
- field=models.ForeignKey(to='servicos.TipoServico', on_delete=models.CASCADE),
+ model_name="servicomanifesto",
+ name="servico",
+ field=models.ForeignKey(
+ to="servicos.TipoServico", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AlterUniqueTogether(
- name='servicomanifesto',
- unique_together=set([('casa_manifesta', 'servico')]),
+ name="servicomanifesto",
+ unique_together=set([("casa_manifesta", "servico")]),
),
migrations.AddField(
- model_name='servico',
- name='tipo_servico',
- field=models.ForeignKey(verbose_name='Tipo de servi\xe7o', to='servicos.TipoServico', on_delete=models.CASCADE),
+ model_name="servico",
+ name="tipo_servico",
+ field=models.ForeignKey(
+ verbose_name="Tipo de servi\xe7o",
+ to="servicos.TipoServico",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='logservico',
- name='servico',
- field=models.ForeignKey(verbose_name='Servi\xe7o', to='servicos.Servico', on_delete=models.CASCADE),
+ model_name="logservico",
+ name="servico",
+ field=models.ForeignKey(
+ verbose_name="Servi\xe7o",
+ to="servicos.Servico",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.CreateModel(
- name='CasaAtendida',
- fields=[
- ],
+ name="CasaAtendida",
+ fields=[],
options={
- 'proxy': True,
- 'verbose_name_plural': 'Casas atendidas',
+ "proxy": True,
+ "verbose_name_plural": "Casas atendidas",
},
- bases=('casas.casalegislativa',),
+ bases=("casas.casalegislativa",),
),
]
diff --git a/sigi/apps/servicos/migrations/0002_tiposervico_modo.py b/sigi/apps/servicos/migrations/0002_tiposervico_modo.py
index 6dd0776..3fda59b 100644
--- a/sigi/apps/servicos/migrations/0002_tiposervico_modo.py
+++ b/sigi/apps/servicos/migrations/0002_tiposervico_modo.py
@@ -7,14 +7,19 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0001_initial'),
+ ("servicos", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='tiposervico',
- name='modo',
- field=models.CharField(default='H', max_length=1, verbose_name='Modo de presta\xe7\xe3o do servi\xe7o', choices=[('H', 'Hospedagem'), ('R', 'Registro')]),
+ model_name="tiposervico",
+ name="modo",
+ field=models.CharField(
+ default="H",
+ max_length=1,
+ verbose_name="Modo de presta\xe7\xe3o do servi\xe7o",
+ choices=[("H", "Hospedagem"), ("R", "Registro")],
+ ),
preserve_default=False,
),
]
diff --git a/sigi/apps/servicos/migrations/0003_auto_20170407_1003.py b/sigi/apps/servicos/migrations/0003_auto_20170407_1003.py
index 26fa40f..ad777be 100644
--- a/sigi/apps/servicos/migrations/0003_auto_20170407_1003.py
+++ b/sigi/apps/servicos/migrations/0003_auto_20170407_1003.py
@@ -8,20 +8,30 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0002_tiposervico_modo'),
+ ("servicos", "0002_tiposervico_modo"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='contato_administrativo',
- field=models.ForeignKey(related_name='contato_administrativo', on_delete=django.db.models.deletion.PROTECT, verbose_name='Contato administrativo', to='casas.Funcionario'),
+ model_name="servico",
+ name="contato_administrativo",
+ field=models.ForeignKey(
+ related_name="contato_administrativo",
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Contato administrativo",
+ to="casas.Funcionario",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servico',
- name='contato_tecnico',
- field=models.ForeignKey(related_name='contato_tecnico', on_delete=django.db.models.deletion.PROTECT, verbose_name='Contato t\xe9cnico', to='casas.Funcionario'),
+ model_name="servico",
+ name="contato_tecnico",
+ field=models.ForeignKey(
+ related_name="contato_tecnico",
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Contato t\xe9cnico",
+ to="casas.Funcionario",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servicos/migrations/0004_delete_casaatendida.py b/sigi/apps/servicos/migrations/0004_delete_casaatendida.py
index 6e42dc8..00faaa7 100644
--- a/sigi/apps/servicos/migrations/0004_delete_casaatendida.py
+++ b/sigi/apps/servicos/migrations/0004_delete_casaatendida.py
@@ -7,11 +7,11 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0003_auto_20170407_1003'),
+ ("servicos", "0003_auto_20170407_1003"),
]
operations = [
migrations.DeleteModel(
- name='CasaAtendida',
+ name="CasaAtendida",
),
]
diff --git a/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py b/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py
index 35af3c6..20227e3 100644
--- a/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py
+++ b/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py
@@ -7,21 +7,27 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0004_delete_casaatendida'),
- ('casas', '0014_auto_20210406_1945'),
+ ("servicos", "0004_delete_casaatendida"),
+ ("casas", "0014_auto_20210406_1945"),
]
operations = [
migrations.AlterField(
- model_name='casamanifesta',
- name='casa_legislativa',
- field=models.OneToOneField(to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="casamanifesta",
+ name="casa_legislativa",
+ field=models.OneToOneField(
+ to="casas.Orgao", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servico',
- name='casa_legislativa',
- field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao', on_delete=models.CASCADE),
+ model_name="servico",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ verbose_name="Casa Legislativa",
+ to="casas.Orgao",
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servicos/migrations/0006_casaatendida.py b/sigi/apps/servicos/migrations/0006_casaatendida.py
index 6a58804..ae1d9fb 100644
--- a/sigi/apps/servicos/migrations/0006_casaatendida.py
+++ b/sigi/apps/servicos/migrations/0006_casaatendida.py
@@ -7,19 +7,18 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('casas', '0014_auto_20210406_1945'),
- ('servicos', '0005_auto_20210406_1945'),
+ ("casas", "0014_auto_20210406_1945"),
+ ("servicos", "0005_auto_20210406_1945"),
]
operations = [
migrations.CreateModel(
- name='CasaAtendida',
- fields=[
- ],
+ name="CasaAtendida",
+ fields=[],
options={
- 'proxy': True,
- 'verbose_name_plural': 'Casas atendidas',
+ "proxy": True,
+ "verbose_name_plural": "Casas atendidas",
},
- bases=('casas.orgao',),
+ bases=("casas.orgao",),
),
]
diff --git a/sigi/apps/servicos/migrations/0007_auto_20210416_0841.py b/sigi/apps/servicos/migrations/0007_auto_20210416_0841.py
index 4480c55..694742a 100644
--- a/sigi/apps/servicos/migrations/0007_auto_20210416_0841.py
+++ b/sigi/apps/servicos/migrations/0007_auto_20210416_0841.py
@@ -8,20 +8,28 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0006_casaatendida'),
+ ("servicos", "0006_casaatendida"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='casa_legislativa',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa Legislativa', to='casas.Orgao'),
+ model_name="servico",
+ name="casa_legislativa",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Casa Legislativa",
+ to="casas.Orgao",
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servico',
- name='tipo_servico',
- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo de servi\xe7o', to='servicos.TipoServico'),
+ model_name="servico",
+ name="tipo_servico",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ verbose_name="Tipo de servi\xe7o",
+ to="servicos.TipoServico",
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servicos/migrations/0008_auto_20210519_1117.py b/sigi/apps/servicos/migrations/0008_auto_20210519_1117.py
index 885ee28..cc29e9b 100644
--- a/sigi/apps/servicos/migrations/0008_auto_20210519_1117.py
+++ b/sigi/apps/servicos/migrations/0008_auto_20210519_1117.py
@@ -7,44 +7,61 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0007_auto_20210416_0841'),
+ ("servicos", "0007_auto_20210416_0841"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='data_ultimo_uso',
- field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True),
+ model_name="servico",
+ name="data_ultimo_uso",
+ field=models.DateField(
+ help_text="Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez",
+ null=True,
+ verbose_name="Data da \xfaltima utiliza\xe7\xe3o",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servico',
- name='erro_atualizacao',
- field=models.TextField(help_text='Erro ocorrido na \xfaltima tentativa de verificar a data de \xfaltima atualiza\xe7\xe3o do servi\xe7o', verbose_name='Erro na atualiza\xe7\xe3o', blank=True),
+ model_name="servico",
+ name="erro_atualizacao",
+ field=models.TextField(
+ help_text="Erro ocorrido na \xfaltima tentativa de verificar a data de \xfaltima atualiza\xe7\xe3o do servi\xe7o",
+ verbose_name="Erro na atualiza\xe7\xe3o",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='tiposervico',
- name='modo',
- field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[('H', 'Hospedagem'), ('R', 'Registro')]),
+ model_name="tiposervico",
+ name="modo",
+ field=models.CharField(
+ max_length=1,
+ verbose_name="modo de presta\xe7\xe3o do servi\xe7o",
+ choices=[("H", "Hospedagem"), ("R", "Registro")],
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='tiposervico',
- name='nome',
- field=models.CharField(max_length=60, verbose_name='nome'),
+ model_name="tiposervico",
+ name="nome",
+ field=models.CharField(max_length=60, verbose_name="nome"),
preserve_default=True,
),
migrations.AlterField(
- model_name='tiposervico',
- name='sigla',
- field=models.CharField(max_length='12', verbose_name='sigla'),
+ model_name="tiposervico",
+ name="sigla",
+ field=models.CharField(max_length="12", verbose_name="sigla"),
preserve_default=True,
),
migrations.AlterField(
- model_name='tiposervico',
- name='string_pesquisa',
- field=models.TextField(help_text='Par\xe2metros da pesquisa para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o. Formato:/caminho/da/pesquisa/?parametros [xml|json] campo.de.data ', verbose_name='string de pesquisa', blank=True),
+ model_name="tiposervico",
+ name="string_pesquisa",
+ field=models.TextField(
+ help_text="Par\xe2metros da pesquisa para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o. Formato:/caminho/da/pesquisa/?parametros [xml|json] campo.de.data ",
+ verbose_name="string de pesquisa",
+ blank=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py b/sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py
index f7cac17..2b133d4 100644
--- a/sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py
+++ b/sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py
@@ -6,53 +6,89 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('servicos', '0008_auto_20210519_1117'),
+ ("servicos", "0008_auto_20210519_1117"),
]
operations = [
migrations.AlterField(
- model_name='casamanifesta',
- name='email',
- field=models.EmailField(blank=True, max_length=254, verbose_name='E-mail de contato'),
+ model_name="casamanifesta",
+ name="email",
+ field=models.EmailField(
+ blank=True, max_length=254, verbose_name="E-mail de contato"
+ ),
),
migrations.AlterField(
- model_name='casamanifesta',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="casamanifesta",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='logservico',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="logservico",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='registroservico',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="registroservico",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='servico',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="servico",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='servicomanifesto',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="servicomanifesto",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='tiposervico',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="tiposervico",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='tiposervico',
- name='modo',
- field=models.CharField(choices=[('H', 'Hospedagem'), ('R', 'Registro')], max_length=1, verbose_name='modo de prestação do serviço'),
+ model_name="tiposervico",
+ name="modo",
+ field=models.CharField(
+ choices=[("H", "Hospedagem"), ("R", "Registro")],
+ max_length=1,
+ verbose_name="modo de prestação do serviço",
+ ),
),
migrations.AlterField(
- model_name='tiposervico',
- name='sigla',
- field=models.CharField(max_length=12, verbose_name='sigla'),
+ model_name="tiposervico",
+ name="sigla",
+ field=models.CharField(max_length=12, verbose_name="sigla"),
),
]
diff --git a/sigi/apps/servicos/models.py b/sigi/apps/servicos/models.py
index 5fb7944..bbe5c82 100644
--- a/sigi/apps/servicos/models.py
+++ b/sigi/apps/servicos/models.py
@@ -5,32 +5,36 @@ from django.utils.translation import gettext as _
class TipoServico(models.Model):
- MODO_CHOICES = (
- ('H', _("Hospedagem")),
- ('R', _("Registro"))
- )
- email_help = '''Use:
+ MODO_CHOICES = (("H", _("Hospedagem")), ("R", _("Registro")))
+ email_help = """Use:
{url} para incluir a URL do serviço,
- {senha} para incluir a senha inicial do serviço'''
- string_pesquisa_help = ("Parâmetros da pesquisa para averiguar a data da "
- "última atualização do serviço. Formato: "
- "/caminho/da/pesquisa/?parametros "
- "[xml|json] campo.de.data ")
- nome = models.CharField(_('nome'), max_length=60)
- sigla = models.CharField(_('sigla'), max_length=12)
+ {senha} para incluir a senha inicial do serviço"""
+ string_pesquisa_help = (
+ "Parâmetros da pesquisa para averiguar a data da "
+ "última atualização do serviço. Formato: "
+ "/caminho/da/pesquisa/?parametros "
+ "[xml|json] campo.de.data "
+ )
+ nome = models.CharField(_("nome"), max_length=60)
+ sigla = models.CharField(_("sigla"), max_length=12)
modo = models.CharField(
- _('modo de prestação do serviço'),
- max_length=1,
- choices=MODO_CHOICES
+ _("modo de prestação do serviço"), max_length=1, choices=MODO_CHOICES
)
string_pesquisa = models.TextField(
- _('string de pesquisa'),
+ _("string de pesquisa"), blank=True, help_text=string_pesquisa_help
+ )
+ template_email_ativa = models.TextField(
+ _("Template de email de ativação"), help_text=email_help, blank=True
+ )
+ template_email_altera = models.TextField(
+ _("Template de email de alteração"), help_text=email_help, blank=True
+ )
+ template_email_desativa = models.TextField(
+ _("Template de email de desativação"),
+ help_text=email_help
+ + _(" {motivo} para incluir o motivo da desativação do serviço"),
blank=True,
- help_text=string_pesquisa_help
)
- template_email_ativa = models.TextField(_('Template de email de ativação'), help_text=email_help, blank=True)
- template_email_altera = models.TextField(_('Template de email de alteração'), help_text=email_help, blank=True)
- template_email_desativa = models.TextField(_('Template de email de desativação'), help_text=email_help + _(' {motivo} para incluir o motivo da desativação do serviço'), blank=True)
@property
def qtde_casas_atendidas(self):
@@ -38,85 +42,77 @@ class TipoServico(models.Model):
return self.servico_set.filter(data_desativacao=None).count()
class Meta:
- verbose_name = _('Tipo de serviço')
- verbose_name_plural = _('Tipos de serviço')
+ verbose_name = _("Tipo de serviço")
+ verbose_name_plural = _("Tipos de serviço")
def __str__(self):
return self.nome
+
class Servico(models.Model):
casa_legislativa = models.ForeignKey(
- Orgao,
- on_delete=models.PROTECT,
- verbose_name=_('Casa Legislativa')
+ Orgao, on_delete=models.PROTECT, verbose_name=_("Casa Legislativa")
)
tipo_servico = models.ForeignKey(
- TipoServico,
- on_delete=models.PROTECT,
- verbose_name=_('Tipo de serviço')
+ TipoServico, on_delete=models.PROTECT, verbose_name=_("Tipo de serviço")
)
contato_tecnico = models.ForeignKey(
Funcionario,
on_delete=models.PROTECT,
- verbose_name=_('Contato técnico'),
- related_name='contato_tecnico'
+ verbose_name=_("Contato técnico"),
+ related_name="contato_tecnico",
)
contato_administrativo = models.ForeignKey(
Funcionario,
on_delete=models.PROTECT,
- verbose_name=_('Contato administrativo'),
- related_name='contato_administrativo'
+ verbose_name=_("Contato administrativo"),
+ related_name="contato_administrativo",
)
- url = models.URLField(_('URL do serviço'), blank=True)
+ url = models.URLField(_("URL do serviço"), blank=True)
hospedagem_interlegis = models.BooleanField(
- _('Hospedagem no Interlegis?'),
- default=False
+ _("Hospedagem no Interlegis?"), default=False
)
nome_servidor = models.CharField(
- _('Hospedado em'),
+ _("Hospedado em"),
max_length=60,
blank=True,
- help_text=_('Se hospedado no Interlegis, informe o nome do servidor.'
- ' Senão, informe o nome do provedor de serviços.')
+ help_text=_(
+ "Se hospedado no Interlegis, informe o nome do servidor."
+ " Senão, informe o nome do provedor de serviços."
+ ),
)
porta_servico = models.PositiveSmallIntegerField(
- _('Porta de serviço (instância)'),
- blank=True,
- null=True
+ _("Porta de serviço (instância)"), blank=True, null=True
)
senha_inicial = models.CharField(
- _('Senha inicial'),
- max_length=33,
- blank=True
+ _("Senha inicial"), max_length=33, blank=True
)
- data_ativacao = models.DateField(_('Data de ativação'), default=date.today)
+ data_ativacao = models.DateField(_("Data de ativação"), default=date.today)
data_alteracao = models.DateField(
- _('Data da última alteração'),
- blank=True,
- null=True,
- auto_now=True
+ _("Data da última alteração"), blank=True, null=True, auto_now=True
)
data_desativacao = models.DateField(
- _('Data de desativação'),
- blank=True,
- null=True
+ _("Data de desativação"), blank=True, null=True
)
motivo_desativacao = models.TextField(
- _('Motivo da desativação'),
- blank=True
+ _("Motivo da desativação"), blank=True
)
data_ultimo_uso = models.DateField(
- _('Data da última utilização'),
+ _("Data da última utilização"),
blank=True,
null=True,
- help_text=_('Data em que o serviço foi utilizado pela Casa Legislativa'
- ' pela última vez')
+ help_text=_(
+ "Data em que o serviço foi utilizado pela Casa Legislativa"
+ " pela última vez"
+ ),
)
erro_atualizacao = models.TextField(
_("Erro na atualização"),
blank=True,
- help_text=_("Erro ocorrido na última tentativa de verificar a data "
- "de última atualização do serviço")
+ help_text=_(
+ "Erro ocorrido na última tentativa de verificar a data "
+ "de última atualização do serviço"
+ ),
)
@property
@@ -133,7 +129,7 @@ class Servico(models.Model):
def reset():
if self.data_ultimo_uso is not None:
self.data_ultimo_uso = None
- self.erro_atualizacao = ''
+ self.erro_atualizacao = ""
self.save()
return
@@ -141,12 +137,14 @@ class Servico(models.Model):
param_pesquisa = string_pesquisa.split(" ")
if len(param_pesquisa) != 3:
return {
- 'data': '',
- 'erro':_("String de pesquisa mal configurada"),
- 'comment':_("Corrija a string de pesquisa")
+ "data": "",
+ "erro": _("String de pesquisa mal configurada"),
+ "comment": _("Corrija a string de pesquisa"),
}
- campos = [int(s) if s.isdigit() else s for s in
- param_pesquisa[2].split('.')]
+ campos = [
+ int(s) if s.isdigit() else s
+ for s in param_pesquisa[2].split(".")
+ ]
url += param_pesquisa[0]
@@ -154,60 +152,66 @@ class Servico(models.Model):
req = requests.get(url, verify=False, allow_redirects=True)
except Exception as e:
return {
- 'data': '',
- 'erro':str(e),
- 'comment':_("Não foi possível conectar com o servidor. "
- "Pode estar fora do ar ou não ser "
- "um {tipo}".format(
- tipo=self.tipo_servico.nome))
+ "data": "",
+ "erro": str(e),
+ "comment": _(
+ "Não foi possível conectar com o servidor. "
+ "Pode estar fora do ar ou não ser "
+ "um {tipo}".format(tipo=self.tipo_servico.nome)
+ ),
}
if req.status_code != 200:
return {
- 'data': '',
- 'erro': req.reason,
- 'comment':_("Não foi possível receber os dados do "
- "servidor. O acesso pode ter sido negado.")
+ "data": "",
+ "erro": req.reason,
+ "comment": _(
+ "Não foi possível receber os dados do "
+ "servidor. O acesso pode ter sido negado."
+ ),
}
try:
- if param_pesquisa[1] == 'xml':
+ if param_pesquisa[1] == "xml":
data = parseString(req.content)
- elif param_pesquisa[1] == 'json':
+ elif param_pesquisa[1] == "json":
data = req.json()
else:
return {
- 'data': '',
- 'erro': _('String de pesquisa mal configurada'),
- 'comment': ''
+ "data": "",
+ "erro": _("String de pesquisa mal configurada"),
+ "comment": "",
}
for c in campos:
if isinstance(c, int):
- if (len(data)-1) < c:
+ if (len(data) - 1) < c:
return {
- 'data': '',
- 'erro': _('Sem dados para verificação'),
- 'comment': _('Parece que nunca foi usado')
+ "data": "",
+ "erro": _("Sem dados para verificação"),
+ "comment": _("Parece que nunca foi usado"),
}
data = data[c]
else:
- if param_pesquisa[1] == 'xml':
+ if param_pesquisa[1] == "xml":
data = data.getElementsByTagName(c)
else:
data = data[c]
- if param_pesquisa[1] == 'xml':
+ if param_pesquisa[1] == "xml":
data = data.firstChild.nodeValue
data = data[:10]
- data = data.replace('/','-')
- return {'data': data, 'erro': '', 'comment': ''}
+ data = data.replace("/", "-")
+ return {"data": data, "erro": "", "comment": ""}
except Exception as e:
return {
- 'data': '',
- 'erro': str(e),
- 'comment': _("Parece que não é um {tipo}".format(
- tipo=self.tipo_servico.nome))
+ "data": "",
+ "erro": str(e),
+ "comment": _(
+ "Parece que não é um {tipo}".format(
+ tipo=self.tipo_servico.nome
+ )
+ ),
}
if self.tipo_servico.string_pesquisa == "":
@@ -222,24 +226,30 @@ class Servico(models.Model):
self.save()
return
- if url[-1] != '/':
- url += '/'
+ if url[-1] != "/":
+ url += "/"
resultados = []
for string_pesquisa in self.tipo_servico.string_pesquisa.splitlines():
resultados.append(ultimo_uso(url, string_pesquisa))
- data = max([r['data'] for r in resultados])
+ data = max([r["data"] for r in resultados])
- if data == '':
+ if data == "":
# Nenhuma busca deu resultado, guardar log de erro
self.data_ultimo_uso = None
- self.erro_atualizacao = " ".join(set(
- ["{erro} ({comment})".format(erro=r['erro'],
- comment=r['comment'])
- for r in resultados if r['erro'] != '' and r['comment'] != ''
- ]))
+ self.erro_atualizacao = " ".join(
+ set(
+ [
+ "{erro} ({comment})".format(
+ erro=r["erro"], comment=r["comment"]
+ )
+ for r in resultados
+ if r["erro"] != "" and r["comment"] != ""
+ ]
+ )
+ )
self.save()
else:
# Atualiza a maior data de atualização
@@ -260,19 +270,30 @@ class Servico(models.Model):
if self.id is None:
# Novo serviço, email de ativação
- subject = _('INTERLEGIS - Ativação de serviço %s') % (self.tipo_servico.nome,)
+ subject = _("INTERLEGIS - Ativação de serviço %s") % (
+ self.tipo_servico.nome,
+ )
body = self.tipo_servico.template_email_ativa
- elif self.data_desativacao is not None and original.data_desativacao is None:
+ elif (
+ self.data_desativacao is not None
+ and original.data_desativacao is None
+ ):
# Serviço foi desativado. Email de desativação
- subject = _('INTERLEGIS - Desativação de serviço %s') % (self.tipo_servico.nome,)
+ subject = _("INTERLEGIS - Desativação de serviço %s") % (
+ self.tipo_servico.nome,
+ )
body = self.tipo_servico.template_email_desativa
- elif (self.tipo_servico != original.tipo_servico or
- self.contato_tecnico != original.contato_tecnico or
- self.url != original.url or
- self.nome_servidor != original.nome_servidor or
- self.senha_inicial != original.senha_inicial):
+ elif (
+ self.tipo_servico != original.tipo_servico
+ or self.contato_tecnico != original.contato_tecnico
+ or self.url != original.url
+ or self.nome_servidor != original.nome_servidor
+ or self.senha_inicial != original.senha_inicial
+ ):
# Serviço foi alterado
- subject = _('INTERLEGIS - Alteração de serviço %s') % (self.tipo_servico.nome,)
+ subject = _("INTERLEGIS - Alteração de serviço %s") % (
+ self.tipo_servico.nome,
+ )
body = self.tipo_servico.template_email_altera
else:
# Salvar o Servico
@@ -280,64 +301,76 @@ class Servico(models.Model):
return # sem enviar email
# Prepara e envia o email
- body = body.replace('{url}', self.url) \
- .replace('{senha}', self.senha_inicial) \
- .replace('{motivo}', self.motivo_desativacao)
+ body = (
+ body.replace("{url}", self.url)
+ .replace("{senha}", self.senha_inicial)
+ .replace("{motivo}", self.motivo_desativacao)
+ )
-# send_mail(subject, body, DEFAULT_FROM_EMAIL, \
-# (self.contato_tecnico.email,), fail_silently=False)
+ # send_mail(subject, body, DEFAULT_FROM_EMAIL, \
+ # (self.contato_tecnico.email,), fail_silently=False)
# Salvar o Servico
super(Servico, self).save(*args, **kwargs)
return
+
class LogServico(models.Model):
servico = models.ForeignKey(
- Servico,
- on_delete=models.CASCADE,
- verbose_name=_('Serviço')
+ Servico, on_delete=models.CASCADE, verbose_name=_("Serviço")
)
- descricao = models.CharField(_('Breve descrição da ação'), max_length=60)
- data = models.DateField(_('Data da ação'), default=date.today)
- log = models.TextField(_('Log da ação'))
+ descricao = models.CharField(_("Breve descrição da ação"), max_length=60)
+ data = models.DateField(_("Data da ação"), default=date.today)
+ log = models.TextField(_("Log da ação"))
def __str__(self):
return f"{self.descricao} ({self.data})"
class Meta:
- verbose_name = _('Log do serviço')
- verbose_name_plural = _('Logs do serviço')
+ verbose_name = _("Log do serviço")
+ verbose_name_plural = _("Logs do serviço")
+
class CasaAtendidaManager(models.Manager):
def get_queryset(self):
qs = super(CasaAtendidaManager, self).get_queryset()
- qs = qs.exclude(codigo_interlegis='')
+ qs = qs.exclude(codigo_interlegis="")
return qs
+
class CasaAtendida(Orgao):
class Meta:
proxy = True
- verbose_name_plural = _('Casas atendidas')
+ verbose_name_plural = _("Casas atendidas")
objects = CasaAtendidaManager()
+
class CasaManifesta(models.Model):
casa_legislativa = models.OneToOneField(Orgao, on_delete=models.CASCADE)
data_manifestacao = models.DateTimeField(auto_now_add=True)
data_atualizacao = models.DateTimeField(auto_now=True)
- informante = models.CharField(_('Nome do informante'), max_length=100, blank=True)
- cargo = models.CharField(_('Cargo do informante'), max_length=100, blank=True)
- email = models.EmailField(_('E-mail de contato'), blank=True)
+ informante = models.CharField(
+ _("Nome do informante"), max_length=100, blank=True
+ )
+ cargo = models.CharField(
+ _("Cargo do informante"), max_length=100, blank=True
+ )
+ email = models.EmailField(_("E-mail de contato"), blank=True)
+
class ServicoManifesto(models.Model):
casa_manifesta = models.ForeignKey(CasaManifesta, on_delete=models.CASCADE)
servico = models.ForeignKey(TipoServico, on_delete=models.CASCADE)
url = models.URLField(blank=True)
- hospedagem_interlegis = models.BooleanField(_('Hospedagem no Interlegis?'), default=False)
+ hospedagem_interlegis = models.BooleanField(
+ _("Hospedagem no Interlegis?"), default=False
+ )
class Meta:
- unique_together = ('casa_manifesta', 'servico')
+ unique_together = ("casa_manifesta", "servico")
+
class RegistroServico(models.Model):
produto = models.CharField(max_length=50)
@@ -346,5 +379,4 @@ class RegistroServico(models.Model):
data_registro = models.DateTimeField(auto_now=True)
class Meta:
- verbose_name_plural = _('Registro de serviços')
-
+ verbose_name_plural = _("Registro de serviços")
diff --git a/sigi/apps/servicos/urls.py b/sigi/apps/servicos/urls.py
index fb40db4..3a4bfd4 100644
--- a/sigi/apps/servicos/urls.py
+++ b/sigi/apps/servicos/urls.py
@@ -6,14 +6,29 @@ from .views import MapaView
urlpatterns = patterns(
- 'sigi.apps.servicos.views',
-
- url(r'^manifesta/$', 'casa_manifesta_view', name="casa-manifesta-view"),
- url(r'^servico/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
- url(r'^servico/carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # tagerror
- url(r'^servico/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho'), # tagerror
- url(r'^servico/csv/$', 'export_csv', name='servicos-csv'),
- url(r'^munatenjson/(?P\w+)/$', 'municipios_atendidos', name="municipios-atendidos"),
- url(r'^mapa/(?P\w+)/$', MapaView.as_view(), name="servicos-mapa"),
+ "sigi.apps.servicos.views",
+ url(r"^manifesta/$", "casa_manifesta_view", name="casa-manifesta-view"),
+ url(
+ r"^servico/carrinho/$",
+ "visualizar_carrinho",
+ name="visualizar-carrinho",
+ ),
+ url(
+ r"^servico/carrinho/excluir_carrinho/$",
+ "excluir_carrinho",
+ name="excluir-carrinho",
+ ), # tagerror
+ url(
+ r"^servico/carrinho/deleta_itens_carrinho$",
+ "deleta_itens_carrinho",
+ name="deleta-itens-carrinho",
+ ), # tagerror
+ url(r"^servico/csv/$", "export_csv", name="servicos-csv"),
+ url(
+ r"^munatenjson/(?P\w+)/$",
+ "municipios_atendidos",
+ name="municipios-atendidos",
+ ),
+ url(r"^mapa/(?P\w+)/$", MapaView.as_view(), name="servicos-mapa"),
# url(r'^listacasas/(?P\w+)', 'casas_usam_servico', name="casas-usam-servico"),
)
diff --git a/sigi/apps/servicos/views.py b/sigi/apps/servicos/views.py
index 56ef66d..118640f 100644
--- a/sigi/apps/servicos/views.py
+++ b/sigi/apps/servicos/views.py
@@ -18,8 +18,13 @@ from django.views.generic.base import TemplateView
from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.convenios.views import normaliza_data, query_ordena
-from sigi.apps.servicos.models import (Servico, TipoServico, CasaManifesta, CasaAtendida,
- ServicoManifesto)
+from sigi.apps.servicos.models import (
+ Servico,
+ TipoServico,
+ CasaManifesta,
+ CasaAtendida,
+ ServicoManifesto,
+)
class MapaView(TemplateView):
@@ -28,7 +33,7 @@ class MapaView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MapaView, self).get_context_data(**kwargs)
- context['servicos'] = TipoServico.objects.all()
+ context["servicos"] = TipoServico.objects.all()
return context
@@ -38,8 +43,8 @@ def municipios_atendidos(self, servico):
query = Q()
- if servico != 'ALL':
- for sigla in servico.split('_'):
+ if servico != "ALL":
+ for sigla in servico.split("_"):
query = query | Q(tipo_servico__sigla=sigla)
query = Q(data_desativacao=None) & query
@@ -47,13 +52,24 @@ def municipios_atendidos(self, servico):
for casa in CasaAtendida.objects.all():
if casa.servico_set.filter(query).exists():
m = casa.municipio
- municipio = {'nome': casa.nome + ', ' + m.uf.sigla,
- 'lat': str(m.latitude),
- 'lng': str(m.longitude),
- 'servicos': "" + " ".join([s.tipo_servico.nome for s in casa.servico_set.filter(query)]) + " ", }
+ municipio = {
+ "nome": casa.nome + ", " + m.uf.sigla,
+ "lat": str(m.latitude),
+ "lng": str(m.longitude),
+ "servicos": ""
+ + " ".join(
+ [
+ s.tipo_servico.nome
+ for s in casa.servico_set.filter(query)
+ ]
+ )
+ + " ",
+ }
municipios.append(municipio)
- return HttpResponse(simplejson.dumps(municipios), content_type='application/json')
+ return HttpResponse(
+ simplejson.dumps(municipios), content_type="application/json"
+ )
class CasaManifestaProtoForm(forms.Form):
@@ -75,147 +91,205 @@ class CasaManifestaProtoForm(forms.Form):
bf = BoundField(self, field, field_name)
field_line.append(bf)
field_lines.append(field_line)
- result.append({'name': name, 'lines': field_lines},)
+ result.append(
+ {"name": name, "lines": field_lines},
+ )
self.fieldsets = result
def casa_manifesta_view(request):
- if 'casa_id' in request.GET:
- casa_id = request.GET.get('casa_id')
+ if "casa_id" in request.GET:
+ casa_id = request.GET.get("casa_id")
casa = get_object_or_404(Orgao, pk=casa_id)
# Criar um formulário dinâmico
campos = {}
- fieldsets = ((None, ('informante', 'cargo', 'email'),),)
+ fieldsets = (
+ (
+ None,
+ ("informante", "cargo", "email"),
+ ),
+ )
for ts in TipoServico.objects.all():
- campos['possui_%s' % ts.pk] = forms.BooleanField(label=_('Possui o serviço de %s') % ts.nome, required=False)
- campos['url_%s' % ts.pk] = forms.URLField(label=_('Informe a URL'), required=False)
- campos['hospedagem_interlegis_%s' % ts.pk] = forms.BooleanField(label=_('Serviço está hospedado no Interlegis'), required=False)
- fieldsets += ((ts.nome, ('possui_%s' % ts.pk, 'url_%s' % ts.pk, 'hospedagem_interlegis_%s' % ts.pk)),)
-
- CasaManifestaForm = type('', (CasaManifestaProtoForm,), campos)
-
- if request.method == 'POST':
+ campos["possui_%s" % ts.pk] = forms.BooleanField(
+ label=_("Possui o serviço de %s") % ts.nome, required=False
+ )
+ campos["url_%s" % ts.pk] = forms.URLField(
+ label=_("Informe a URL"), required=False
+ )
+ campos["hospedagem_interlegis_%s" % ts.pk] = forms.BooleanField(
+ label=_("Serviço está hospedado no Interlegis"), required=False
+ )
+ fieldsets += (
+ (
+ ts.nome,
+ (
+ "possui_%s" % ts.pk,
+ "url_%s" % ts.pk,
+ "hospedagem_interlegis_%s" % ts.pk,
+ ),
+ ),
+ )
+
+ CasaManifestaForm = type("", (CasaManifestaProtoForm,), campos)
+
+ if request.method == "POST":
cmf = CasaManifestaForm(request.POST)
if cmf.is_valid():
thanks = []
- cm, created = CasaManifesta.objects.get_or_create(casa_legislativa=casa)
- cm.informante = cmf.cleaned_data['informante']
- cm.cargo = cmf.cleaned_data['cargo']
- cm.email = cmf.cleaned_data['email']
+ cm, created = CasaManifesta.objects.get_or_create(
+ casa_legislativa=casa
+ )
+ cm.informante = cmf.cleaned_data["informante"]
+ cm.cargo = cmf.cleaned_data["cargo"]
+ cm.email = cmf.cleaned_data["email"]
cm.save()
- thanks.append((_('Informante'), cmf.cleaned_data['informante']))
- thanks.append((_('Cargo'), cmf.cleaned_data['cargo']))
- thanks.append((_('E-mail'), cmf.cleaned_data['email']))
+ thanks.append((_("Informante"), cmf.cleaned_data["informante"]))
+ thanks.append((_("Cargo"), cmf.cleaned_data["cargo"]))
+ thanks.append((_("E-mail"), cmf.cleaned_data["email"]))
for ts in TipoServico.objects.all():
- if cmf.cleaned_data['possui_%s' % ts.pk]:
- sm, created = ServicoManifesto.objects.get_or_create(casa_manifesta=cm, servico=ts)
- sm.url = cmf.cleaned_data['url_%s' % ts.pk]
- sm.hospedagem_interlegis = cmf.cleaned_data['hospedagem_interlegis_%s' % ts.pk]
+ if cmf.cleaned_data["possui_%s" % ts.pk]:
+ sm, created = ServicoManifesto.objects.get_or_create(
+ casa_manifesta=cm, servico=ts
+ )
+ sm.url = cmf.cleaned_data["url_%s" % ts.pk]
+ sm.hospedagem_interlegis = cmf.cleaned_data[
+ "hospedagem_interlegis_%s" % ts.pk
+ ]
sm.save()
- thanks.append((ts.nome, _('Possui o serviço acessível em %(url)s %(obs)s') % dict(
- url=sm.url,
- obs=_('hospedado no Interlegis') if sm.hospedagem_interlegis else '')))
+ thanks.append(
+ (
+ ts.nome,
+ _(
+ "Possui o serviço acessível em %(url)s %(obs)s"
+ )
+ % dict(
+ url=sm.url,
+ obs=_("hospedado no Interlegis")
+ if sm.hospedagem_interlegis
+ else "",
+ ),
+ )
+ )
else:
- ServicoManifesto.objects.filter(casa_manifesta=cm, servico=ts).delete()
- thanks.append((ts.nome, _('Não possui')))
- extra_context = {'casa': casa, 'thanks': thanks}
+ ServicoManifesto.objects.filter(
+ casa_manifesta=cm, servico=ts
+ ).delete()
+ thanks.append((ts.nome, _("Não possui")))
+ extra_context = {"casa": casa, "thanks": thanks}
else:
- extra_context = {'casa': casa, 'cmf': cmf}
+ extra_context = {"casa": casa, "cmf": cmf}
else:
try:
cm = casa.casamanifesta
values = {
- 'informante': cm.informante,
- 'cargo': cm.cargo,
- 'email': cm.email,
+ "informante": cm.informante,
+ "cargo": cm.cargo,
+ "email": cm.email,
}
for sm in cm.servicomanifesto_set.all():
- values['possui_%s' % sm.servico.pk] = True
- values['url_%s' % sm.servico.pk] = sm.url
- values['hospedagem_interlegis_%s' % sm.servico.pk] = sm.hospedagem_interlegis
+ values["possui_%s" % sm.servico.pk] = True
+ values["url_%s" % sm.servico.pk] = sm.url
+ values[
+ "hospedagem_interlegis_%s" % sm.servico.pk
+ ] = sm.hospedagem_interlegis
cmf = CasaManifestaForm(values)
except:
cmf = CasaManifestaForm()
cmf.set_fieldsets(fieldsets)
- extra_context = {'casa': casa, 'cmf': cmf}
- elif 'uf' in request.GET:
- uf = request.GET.get('uf')
- extra_context = {'casa_list': Orgao.objects.filter(municipio__uf__sigla=uf)}
+ extra_context = {"casa": casa, "cmf": cmf}
+ elif "uf" in request.GET:
+ uf = request.GET.get("uf")
+ extra_context = {
+ "casa_list": Orgao.objects.filter(municipio__uf__sigla=uf)
+ }
else:
- extra_context = {'uf_list': UnidadeFederativa.objects.all()}
+ extra_context = {"uf_list": UnidadeFederativa.objects.all()}
+
+ return render_to_response(
+ "servicos/casa_manifesta.html",
+ extra_context,
+ context_instance=RequestContext(request),
+ )
- return render_to_response('servicos/casa_manifesta.html', extra_context, context_instance=RequestContext(request))
def adicionar_servicos_carrinho(request, queryset=None, id=None):
- if request.method == 'POST':
- ids_selecionados = request.POST.getlist('_selected_action')
- if 'carrinho_servicos' not in request.session:
- request.session['carrinho_servicos'] = ids_selecionados
+ if request.method == "POST":
+ ids_selecionados = request.POST.getlist("_selected_action")
+ if "carrinho_servicos" not in request.session:
+ request.session["carrinho_servicos"] = ids_selecionados
else:
- lista = request.session['carrinho_servicos']
+ lista = request.session["carrinho_servicos"]
# Verifica se id já não está adicionado
for id in ids_selecionados:
if id not in lista:
lista.append(id)
- request.session['carrinho_servicos'] = lista
+ request.session["carrinho_servicos"] = lista
+
def carrinhoOrGet_for_qs(request):
"""
- Verifica se existe convênios na sessão se não verifica get e retorna qs correspondente.
+ Verifica se existe convênios na sessão se não verifica get e retorna qs correspondente.
"""
- if 'carrinho_servicos' in request.session:
- ids = request.session['carrinho_servicos']
+ if "carrinho_servicos" in request.session:
+ ids = request.session["carrinho_servicos"]
qs = Servico.objects.filter(pk__in=ids)
- qs = qs.order_by("casa_legislativa__municipio__uf", "casa_legislativa__municipio")
+ qs = qs.order_by(
+ "casa_legislativa__municipio__uf", "casa_legislativa__municipio"
+ )
qs = get_for_qs(request.GET, qs)
else:
qs = Servico.objects.all()
if request.GET:
- qs = qs.order_by("casa_legislativa__municipio__uf", "casa_legislativa__municipio")
+ qs = qs.order_by(
+ "casa_legislativa__municipio__uf", "casa_legislativa__municipio"
+ )
qs = get_for_qs(request.GET, qs)
return qs
def adicionar_servicos_carrinho(request, queryset=None, id=None):
- if request.method == 'POST':
- ids_selecionados = request.POST.getlist('_selected_action')
- if 'carrinho_servicos' not in request.session:
- request.session['carrinho_servicos'] = ids_selecionados
+ if request.method == "POST":
+ ids_selecionados = request.POST.getlist("_selected_action")
+ if "carrinho_servicos" not in request.session:
+ request.session["carrinho_servicos"] = ids_selecionados
else:
- lista = request.session['carrinho_servicos']
+ lista = request.session["carrinho_servicos"]
# Verifica se id já não está adicionado
for id in ids_selecionados:
if id not in lista:
lista.append(id)
- request.session['carrinho_servicos'] = lista
+ request.session["carrinho_servicos"] = lista
+
@login_required
def excluir_carrinho(request):
- if 'carrinho_servicos' in request.session:
- del request.session['carrinho_servicos']
- messages.info(request, 'O carrinho foi esvaziado')
- return HttpResponseRedirect('../../')
+ if "carrinho_servicos" in request.session:
+ del request.session["carrinho_servicos"]
+ messages.info(request, "O carrinho foi esvaziado")
+ return HttpResponseRedirect("../../")
+
@login_required
def deleta_itens_carrinho(request):
- if request.method == 'POST':
- ids_selecionados = request.POST.getlist('_selected_action')
- if 'carrinho_servicos' in request.session:
- lista = request.session['carrinho_servicos']
+ if request.method == "POST":
+ ids_selecionados = request.POST.getlist("_selected_action")
+ if "carrinho_servicos" in request.session:
+ lista = request.session["carrinho_servicos"]
for item in ids_selecionados:
lista.remove(item)
if lista:
- request.session['carrinho_servicos'] = lista
+ request.session["carrinho_servicos"] = lista
else:
del lista
- del request.session['carrinho_servicos']
+ del request.session["carrinho_servicos"]
+
+ return HttpResponseRedirect(".")
- return HttpResponseRedirect('.')
@login_required
def visualizar_carrinho(request):
@@ -227,7 +301,7 @@ def visualizar_carrinho(request):
# Make sure page request is an int. If not, deliver first page.
# Esteja certo de que o `page request` é um inteiro. Se não, mostre a primeira página.
try:
- page = int(request.GET.get('page', '1'))
+ page = int(request.GET.get("page", "1"))
except ValueError:
page = 1
@@ -237,53 +311,59 @@ def visualizar_carrinho(request):
except (EmptyPage, InvalidPage):
paginas = paginator.page(paginator.num_pages)
- carrinhoIsEmpty = not('carrinho_servicos' in request.session)
+ carrinhoIsEmpty = not ("carrinho_servicos" in request.session)
return render(
request,
- 'servicos/carrinho.html',
+ "servicos/carrinho.html",
{
- 'carIsEmpty': carrinhoIsEmpty,
- 'paginas': paginas,
- 'query_str': '?' + request.META['QUERY_STRING']
- }
+ "carIsEmpty": carrinhoIsEmpty,
+ "paginas": paginas,
+ "query_str": "?" + request.META["QUERY_STRING"],
+ },
)
+
def get_for_qs(get, qs):
kwargs = {}
ids = 0
get._mutable = True
- normaliza_data(get, 'data_ativacao__gte')
- normaliza_data(get, 'data_ativacao__lte')
+ normaliza_data(get, "data_ativacao__gte")
+ normaliza_data(get, "data_ativacao__lte")
get._mutable = False
for k, v in get.iteritems():
- if k not in ['page', 'pop', 'q', '_popup']:
- if not k == 'o':
+ if k not in ["page", "pop", "q", "_popup"]:
+ if not k == "o":
if k == "ot":
qs = query_ordena(qs, get["o"], get["ot"])
else:
kwargs[str(k)] = v
- if(str(k) == 'ids'):
+ if str(k) == "ids":
ids = 1
break
qs = qs.filter(**kwargs)
if ids:
- query = 'id IN (' + kwargs['ids'].__str__() + ')'
+ query = "id IN (" + kwargs["ids"].__str__() + ")"
qs = Servico.objects.extra(where=[query])
return qs
+
@login_required
def export_csv(request):
- response = HttpResponse(content_type='text/csv')
- response['Content-Disposition'] = 'attachment; filename=servicos.csv'
+ response = HttpResponse(content_type="text/csv")
+ response["Content-Disposition"] = "attachment; filename=servicos.csv"
csv_writer = csv.writer(response)
servicos = carrinhoOrGet_for_qs(request)
if not servicos:
- return HttpResponseRedirect('../')
+ return HttpResponseRedirect("../")
- atributos = [_("Casa Legislativa"), _("Contato Interlegis"), _("Produto"),
- _("Data de Ativação"), ]
+ atributos = [
+ _("Casa Legislativa"),
+ _("Contato Interlegis"),
+ _("Produto"),
+ _("Data de Ativação"),
+ ]
if request.POST:
atributos = request.POST.getlist("itens_csv_selected")
@@ -292,9 +372,9 @@ def export_csv(request):
if _("Casa Legislativa") in col_titles:
pos = col_titles.index(_("Casa Legislativa")) + 1
col_titles.insert(pos, _("uf"))
- pos+=1
+ pos += 1
col_titles.insert(pos, _("email"))
- pos+=1
+ pos += 1
col_titles.insert(pos, _("telefone"))
if _("Contato Interlegis") in col_titles:
@@ -308,7 +388,9 @@ def export_csv(request):
for atributo in atributos:
if _("Casa Legislativa") == atributo:
lista.append(servico.casa_legislativa.nome.encode("utf-8"))
- lista.append(servico.casa_legislativa.municipio.uf.sigla.encode("utf-8"))
+ lista.append(
+ servico.casa_legislativa.municipio.uf.sigla.encode("utf-8")
+ )
lista.append(servico.casa_legislativa.email.encode("utf-8"))
if servico.casa_legislativa.telefone is not None:
lista.append(servico.casa_legislativa.telefone)
@@ -317,14 +399,18 @@ def export_csv(request):
elif _("Contato Interlegis") == atributo:
if servico.casa_legislativa.contato_interlegis is not None:
lista.append(servico.casa_legislativa.contato_interlegis)
- lista.append(servico.casa_legislativa.contato_interlegis.email.encode("utf-8"))
+ lista.append(
+ servico.casa_legislativa.contato_interlegis.email.encode(
+ "utf-8"
+ )
+ )
else:
lista.append("")
lista.append("")
elif _("Produto") == atributo:
lista.append(servico.tipo_servico.nome.encode("utf-8"))
elif _("Data de Ativação") == atributo:
- data = ''
+ data = ""
if servico.data_ativacao:
data = servico.data_ativacao.strftime("%d/%m/%Y")
lista.append(data.encode("utf-8"))
diff --git a/sigi/apps/servidores/admin.py b/sigi/apps/servidores/admin.py
index 18097e1..40a70b9 100644
--- a/sigi/apps/servidores/admin.py
+++ b/sigi/apps/servidores/admin.py
@@ -8,13 +8,28 @@ from sigi.apps.servidores.filters import ServicoFilter
class ServicoInline(admin.TabularInline):
model = Servico
- fields = ['nome', 'sigla', 'responsavel',]
- autocomplete_fields = ['responsavel',]
+ fields = [
+ "nome",
+ "sigla",
+ "responsavel",
+ ]
+ autocomplete_fields = [
+ "responsavel",
+ ]
+
class ServidorInline(admin.TabularInline):
model = Servidor
- fields = ('imagem_foto', 'nome_completo', 'is_active', )
- readonly_fields = ('imagem_foto', 'nome_completo', 'is_active', )
+ fields = (
+ "imagem_foto",
+ "nome_completo",
+ "is_active",
+ )
+ readonly_fields = (
+ "imagem_foto",
+ "nome_completo",
+ "is_active",
+ )
def has_add_permission(self, request, obj):
return False
@@ -30,6 +45,7 @@ class ServidorInline(admin.TabularInline):
)
else:
return ""
+
imagem_foto.short_description = _("foto")
def is_active(self, servidor):
@@ -37,48 +53,93 @@ class ServidorInline(admin.TabularInline):
return servidor.user.is_active
else:
return False
- is_active.admin_order_field = 'user__is_active'
+
+ is_active.admin_order_field = "user__is_active"
is_active.boolean = True
- is_active.short_description = _('ativo')
+ is_active.short_description = _("ativo")
+
@admin.register(Servico)
class ServicoAdmin(admin.ModelAdmin):
- list_display = ['sigla', 'nome', 'subordinado', 'responsavel']
- list_filter = [ServicoFilter,]
- search_fields = ['nome', 'sigla',]
- autocomplete_fields = ['subordinado', 'responsavel',]
- inlines = [ServicoInline, ServidorInline,]
+ list_display = ["sigla", "nome", "subordinado", "responsavel"]
+ list_filter = [
+ ServicoFilter,
+ ]
+ search_fields = [
+ "nome",
+ "sigla",
+ ]
+ autocomplete_fields = [
+ "subordinado",
+ "responsavel",
+ ]
+ inlines = [
+ ServicoInline,
+ ServidorInline,
+ ]
+
@admin.register(Servidor)
class ServidorAdmin(admin.ModelAdmin):
- list_display = ('imagem_foto', 'nome_completo', 'is_active', 'servico', )
- list_display_links = ('imagem_foto', 'nome_completo',)
- list_filter = ('user__is_active', 'externo', 'servico',)
- search_fields = ('nome_completo', 'user__email', 'user__first_name',
- 'user__last_name', 'user__username', 'servico__nome',
- 'servico__sigla')
- raw_id_fields = ('user',)
+ list_display = (
+ "imagem_foto",
+ "nome_completo",
+ "is_active",
+ "servico",
+ )
+ list_display_links = (
+ "imagem_foto",
+ "nome_completo",
+ )
+ list_filter = (
+ "user__is_active",
+ "externo",
+ "servico",
+ )
+ search_fields = (
+ "nome_completo",
+ "user__email",
+ "user__first_name",
+ "user__last_name",
+ "user__username",
+ "servico__nome",
+ "servico__sigla",
+ )
+ raw_id_fields = ("user",)
fieldsets = (
- (None, {
- 'fields': ('user', 'nome_completo', 'foto', 'servico',)
- }),
- (_("outros órgãos"), {
- 'fields': ('externo', 'orgao_origem', 'qualificacoes'),
- }),
+ (
+ None,
+ {
+ "fields": (
+ "user",
+ "nome_completo",
+ "foto",
+ "servico",
+ )
+ },
+ ),
+ (
+ _("outros órgãos"),
+ {
+ "fields": ("externo", "orgao_origem", "qualificacoes"),
+ },
+ ),
)
def lookup_allowed(self, lookup, value):
- return super(ServidorAdmin, self).lookup_allowed(lookup, value) or \
- lookup in ['user__is_active__exact']
+ return super(ServidorAdmin, self).lookup_allowed(
+ lookup, value
+ ) or lookup in ["user__is_active__exact"]
def is_active(self, servidor):
if servidor.user:
return servidor.user.is_active
else:
return False
- is_active.admin_order_field = 'user__is_active'
+
+ is_active.admin_order_field = "user__is_active"
is_active.boolean = True
- is_active.short_description = _('ativo')
+ is_active.short_description = _("ativo")
def imagem_foto(sels, servidor):
if servidor.foto:
@@ -88,4 +149,5 @@ class ServidorAdmin(admin.ModelAdmin):
)
else:
return ""
- imagem_foto.short_description = _("foto")
\ No newline at end of file
+
+ imagem_foto.short_description = _("foto")
diff --git a/sigi/apps/servidores/apps.py b/sigi/apps/servidores/apps.py
index d9db5ec..92445ed 100644
--- a/sigi/apps/servidores/apps.py
+++ b/sigi/apps/servidores/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class ServidoresConfig(AppConfig):
- name = 'sigi.apps.servidores'
- verbose_name = _('servidores')
+ name = "sigi.apps.servidores"
+ verbose_name = _("servidores")
diff --git a/sigi/apps/servidores/filters.py b/sigi/apps/servidores/filters.py
index bc4841a..ecbd440 100644
--- a/sigi/apps/servidores/filters.py
+++ b/sigi/apps/servidores/filters.py
@@ -5,11 +5,12 @@ from sigi.apps.servidores.models import Servico
class ServicoFilter(admin.SimpleListFilter):
title = _("Subordinados à")
- parameter_name = 'subordinado__id__exact'
+ parameter_name = "subordinado__id__exact"
def lookups(self, request, model_admin):
- return ([('None', _("Nenhum"))] +
- [(s.id, s.nome) for s in Servico.objects.exclude(servico=None)])
+ return [("None", _("Nenhum"))] + [
+ (s.id, s.nome) for s in Servico.objects.exclude(servico=None)
+ ]
def queryset(self, request, queryset):
if self.value():
diff --git a/sigi/apps/servidores/management/commands/mescla_servidor.py b/sigi/apps/servidores/management/commands/mescla_servidor.py
index 7ad62a8..020d450 100644
--- a/sigi/apps/servidores/management/commands/mescla_servidor.py
+++ b/sigi/apps/servidores/management/commands/mescla_servidor.py
@@ -3,9 +3,10 @@ from django.contrib.auth.models import User, Group
from sigi.apps.servidores.models import Servidor
from django.core.management.base import BaseCommand
+
class Command(BaseCommand):
- help = 'Transfere os dados do servidor OLD para o servidor NEW.'
- args = 'old_id new_id'
+ help = "Transfere os dados do servidor OLD para o servidor NEW."
+ args = "old_id new_id"
def handle(self, *args, **options):
if len(args) != 2:
@@ -18,12 +19,13 @@ class Command(BaseCommand):
old = Servidor.objects.get(id=old_id)
new = Servidor.objects.get(id=new_id)
- self.stdout.write(self.style.WARNING(
- "Transferir dados de {old_name} para {new_name}".format(
- old_name=old.nome_completo,
- new_name=new.nome_completo
+ self.stdout.write(
+ self.style.WARNING(
+ "Transferir dados de {old_name} para {new_name}".format(
+ old_name=old.nome_completo, new_name=new.nome_completo
+ )
)
- ))
+ )
self.stdout.write("\t* Transferindo a carteira de atendimento...")
for casa in old.casas_que_gerencia.all():
@@ -65,4 +67,4 @@ class Command(BaseCommand):
old.user = None
old.save()
- self.stdout.write("Concluído!")
\ No newline at end of file
+ self.stdout.write("Concluído!")
diff --git a/sigi/apps/servidores/management/commands/migra.py b/sigi/apps/servidores/management/commands/migra.py
index e504b79..eedb3ae 100644
--- a/sigi/apps/servidores/management/commands/migra.py
+++ b/sigi/apps/servidores/management/commands/migra.py
@@ -24,13 +24,15 @@ class MigrationError(Exception):
class Command(BaseCommand):
- help = _('Migra usuários do antigo Sistema de RH')
+ help = _("Migra usuários do antigo Sistema de RH")
def to_date(self, data):
return datetime.strptime(data, "%Y-%m-%d 00:00:00")
def handle(self, *args, **options):
- reader = csv.reader(open("/tmp/pessoal.csv"), delimiter=',', quotechar="\"")
+ reader = csv.reader(
+ open("/tmp/pessoal.csv"), delimiter=",", quotechar='"'
+ )
BRASILIA = Municipio.objects.get(codigo_ibge=5300108)
@@ -44,15 +46,15 @@ class Command(BaseCommand):
p[name] = value.strip()
user = None
- if not p['email']:
- username = ''
- email = ''
- elif not ('@interlegis' in p['email']):
- username = p['email'].split('@')[0].strip().lower()
- email = ''
+ if not p["email"]:
+ username = ""
+ email = ""
+ elif not ("@interlegis" in p["email"]):
+ username = p["email"].split("@")[0].strip().lower()
+ email = ""
else:
- username = p['email'].split('@')[0].strip().lower()
- email = username + '@interlegis.leg.br'
+ username = p["email"].split("@")[0].strip().lower()
+ email = username + "@interlegis.leg.br"
# buscar usuário e servidor da linha atual
try:
@@ -61,7 +63,7 @@ class Command(BaseCommand):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
- email = username + '@interlegis.leg.br'
+ email = username + "@interlegis.leg.br"
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
@@ -83,9 +85,9 @@ class Command(BaseCommand):
if not email:
# cria um username a partir do email sem
# colidir com os usuarios ldap
- username = username + '__'
+ username = username + "__"
- names = p['nome_completo'].split(' ')
+ names = p["nome_completo"].split(" ")
first_name = names[0]
last_name = " ".join(names[1:])
@@ -94,153 +96,153 @@ class Command(BaseCommand):
email=email,
first_name=first_name,
last_name=last_name[:30],
- is_active=False
+ is_active=False,
)
servidor = user.servidor
except Servidor.DoesNotExist:
servidor = Servidor.objects.create(
user=user,
- nome_completo="%s %s" % (user.first_name, user.last_name)
+ nome_completo="%s %s" % (user.first_name, user.last_name),
)
except MigrationError as e:
- print (", ".join(row))
+ print(", ".join(row))
continue
# mapeando dados simples
- servidor.nome_completo = p['nome_completo']
- servidor.cpf = p['cpf']
- servidor.rg = p['identidade']
- servidor.apelido = p['username']
- servidor.matricula = p['matricula']
- servidor.ato_exoneracao = p['ato_exoneracao']
- servidor.ato_numero = p['ato_numero']
- servidor.ramal = p['ramal']
-
- if p['email'] and not '@interlegis' in p['email']:
- servidor.email_pessoal = p['email']
-
- if p['inativo'] == "-1":
+ servidor.nome_completo = p["nome_completo"]
+ servidor.cpf = p["cpf"]
+ servidor.rg = p["identidade"]
+ servidor.apelido = p["username"]
+ servidor.matricula = p["matricula"]
+ servidor.ato_exoneracao = p["ato_exoneracao"]
+ servidor.ato_numero = p["ato_numero"]
+ servidor.ramal = p["ramal"]
+
+ if p["email"] and not "@interlegis" in p["email"]:
+ servidor.email_pessoal = p["email"]
+
+ if p["inativo"] == "-1":
servidor.user.is_active = False
else:
servidor.user.is_active = True
servidor.user.save()
- if p['de_fora'] == "-1":
+ if p["de_fora"] == "-1":
servidor.de_fora = True
else:
servidor.de_fora = False
- if p['sexo'].upper() == 'M':
- servidor.sexo = 'M'
- elif p['sexo'].upper() == 'F':
- servidor.sexo = 'F'
+ if p["sexo"].upper() == "M":
+ servidor.sexo = "M"
+ elif p["sexo"].upper() == "F":
+ servidor.sexo = "F"
- if p['turno'] == "1":
- servidor.turno = 'M'
- elif p['turno'] == "2":
- servidor.turno = 'T'
- elif p['turno'] == "3":
- servidor.turno = 'N'
+ if p["turno"] == "1":
+ servidor.turno = "M"
+ elif p["turno"] == "2":
+ servidor.turno = "T"
+ elif p["turno"] == "3":
+ servidor.turno = "N"
- if p['aniversario']:
- servidor.data_nascimento = self.to_date(p['aniversario'])
+ if p["aniversario"]:
+ servidor.data_nascimento = self.to_date(p["aniversario"])
- if p['data_nomeacao']:
- servidor.data_nomeacao = self.to_date(p['data_nomeacao'])
+ if p["data_nomeacao"]:
+ servidor.data_nomeacao = self.to_date(p["data_nomeacao"])
- if p['secretaria_sigla']:
- if ' - ' in p['secretaria_nome']:
- secretaria_nome = p['secretaria_nome'].split(' - ')[1]
+ if p["secretaria_sigla"]:
+ if " - " in p["secretaria_nome"]:
+ secretaria_nome = p["secretaria_nome"].split(" - ")[1]
else:
- secretaria_nome = p['secretaria_nome']
+ secretaria_nome = p["secretaria_nome"]
secretaria = Subsecretaria.objects.get_or_create(
- sigla=p['secretaria_sigla'],
- nome=secretaria_nome
+ sigla=p["secretaria_sigla"], nome=secretaria_nome
)[0]
- if ' - ' in p['servico_nome']:
- servico_nome = p['servico_nome'].split(' - ')[1]
+ if " - " in p["servico_nome"]:
+ servico_nome = p["servico_nome"].split(" - ")[1]
else:
- servico_nome = p['servico_nome']
+ servico_nome = p["servico_nome"]
servico = Servico.objects.get_or_create(
- sigla=p['servico_sigla'],
- nome=servico_nome
+ sigla=p["servico_sigla"], nome=servico_nome
)[0]
servico.subsecretaria = secretaria
servico.save()
servidor.servico = servico
- if p['telefone']:
+ if p["telefone"]:
try:
- t = servidor.telefones.get(numero=p['telefone'])
+ t = servidor.telefones.get(numero=p["telefone"])
except:
- t = servidor.telefones.create(numero=p['telefone'])
- t.tipo = 'F'
+ t = servidor.telefones.create(numero=p["telefone"])
+ t.tipo = "F"
t.save()
- if p['celular']:
+ if p["celular"]:
try:
- t = servidor.telefones.get(numero=p['celular'])
+ t = servidor.telefones.get(numero=p["celular"])
except:
- t = servidor.telefones.create(numero=p['celular'])
- t.tipo = 'M'
+ t = servidor.telefones.create(numero=p["celular"])
+ t.tipo = "M"
t.save()
- if p['endereco']:
+ if p["endereco"]:
try:
- e = servidor.endereco.get(logradouro=p['endereco'])
+ e = servidor.endereco.get(logradouro=p["endereco"])
except:
- e = servidor.endereco.create(logradouro=p['endereco'])
+ e = servidor.endereco.create(logradouro=p["endereco"])
e.municipio = BRASILIA
- e.bairro = p['cidade'] # bizarro mas é isso mesmo
- e.cep = re.sub("\D", "", p['cep'])
+ e.bairro = p["cidade"] # bizarro mas é isso mesmo
+ e.cep = re.sub("\D", "", p["cep"])
e.save()
- servidor.apontamentos = p['apontamentos']
- servidor.obs = p['obs']
+ servidor.apontamentos = p["apontamentos"]
+ servidor.obs = p["obs"]
- if p['cargo'] or p['funcao']:
+ if p["cargo"] or p["funcao"]:
funcao = servidor.funcao_set.get_or_create(
- funcao=p['funcao'],
- cargo=p['cargo'],
+ funcao=p["funcao"],
+ cargo=p["cargo"],
)[0]
- if p['data_bap_entrada']:
- funcao.data_bap_entrada = self.to_date(p['data_bap_entrada'])
+ if p["data_bap_entrada"]:
+ funcao.data_bap_entrada = self.to_date(
+ p["data_bap_entrada"]
+ )
- if p['data_bap_saida']:
- funcao.data_bap_saida = self.to_date(p['data_bap_saida'])
+ if p["data_bap_saida"]:
+ funcao.data_bap_saida = self.to_date(p["data_bap_saida"])
- if p['data_entrada']:
- funcao.inicio_funcao = self.to_date(p['data_entrada'])
+ if p["data_entrada"]:
+ funcao.inicio_funcao = self.to_date(p["data_entrada"])
- if p['data_saida']:
- funcao.fim_funcao = self.to_date(p['data_saida'])
+ if p["data_saida"]:
+ funcao.fim_funcao = self.to_date(p["data_saida"])
- funcao.bap_entrada = p['bap_entrada']
- funcao.bap_saida = p['bap_saida']
+ funcao.bap_entrada = p["bap_entrada"]
+ funcao.bap_saida = p["bap_saida"]
funcao.save()
- if re.search(r'estagi.ri[o|a]', p['cargo'], re.I): # XXX i18n
+ if re.search(r"estagi.ri[o|a]", p["cargo"], re.I): # XXX i18n
# TODO inserir dados de estagio
pass
- if p['inicio_ferias'] and p['final_ferias']:
+ if p["inicio_ferias"] and p["final_ferias"]:
servidor.ferias_set.get_or_create(
- inicio_ferias=self.to_date(p['inicio_ferias']),
- fim_ferias=self.to_date(p['final_ferias']),
- obs=p['obs_ferias']
+ inicio_ferias=self.to_date(p["inicio_ferias"]),
+ fim_ferias=self.to_date(p["final_ferias"]),
+ obs=p["obs_ferias"],
)
- if p['inicio_licenca'] and p['fim_licenca']:
+ if p["inicio_licenca"] and p["fim_licenca"]:
servidor.licenca_set.get_or_create(
- inicio_licenca=self.to_date(p['inicio_licenca']),
- fim_licenca=self.to_date(p['fim_licenca']),
- obs=p['obs_licenca']
+ inicio_licenca=self.to_date(p["inicio_licenca"]),
+ fim_licenca=self.to_date(p["fim_licenca"]),
+ obs=p["obs_licenca"],
)
servidor.save()
diff --git a/sigi/apps/servidores/management/commands/sync_ldap.py b/sigi/apps/servidores/management/commands/sync_ldap.py
index 2742696..5d7dfc8 100644
--- a/sigi/apps/servidores/management/commands/sync_ldap.py
+++ b/sigi/apps/servidores/management/commands/sync_ldap.py
@@ -8,7 +8,7 @@ from sigi.settings import *
class Command(BaseCommand):
- help = 'Sincroniza Usuários e Servidores com o LDAP'
+ help = "Sincroniza Usuários e Servidores com o LDAP"
def handle(self, *args, **options):
self.sync_groups()
@@ -16,18 +16,19 @@ class Command(BaseCommand):
def get_ldap_groups(self):
filter = "(&(objectclass=Group))"
- values = ['cn', ]
+ values = [
+ "cn",
+ ]
l = ldap.initialize(AUTH_LDAP_SERVER_URI)
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
- l.simple_bind_s(AUTH_LDAP_BIND_DN.encode('utf-8'),
- AUTH_LDAP_BIND_PASSWORD)
+ l.simple_bind_s(
+ AUTH_LDAP_BIND_DN.encode("utf-8"), AUTH_LDAP_BIND_PASSWORD
+ )
page_control = ldap.controls.SimplePagedResultsControl(
- True,
- size=1000,
- cookie=''
+ True, size=1000, cookie=""
)
result = []
pages = 0
@@ -39,15 +40,18 @@ class Command(BaseCommand):
ldap.SCOPE_SUBTREE,
filter,
values,
- serverctrls=[page_control]
+ serverctrls=[page_control],
)
rtype, rdata, rmsgid, serverctrls = l.result3(response)
result.extend(rdata)
- controls = [control for control in serverctrls
- if control.controlType ==
- ldap.controls.SimplePagedResultsControl.controlType]
+ controls = [
+ control
+ for control in serverctrls
+ if control.controlType
+ == ldap.controls.SimplePagedResultsControl.controlType
+ ]
if not controls:
- raise Exception('The server ignores RFC 2696 control')
+ raise Exception("The server ignores RFC 2696 control")
if not controls[0].cookie:
break
page_control.cookie = controls[0].cookie
@@ -59,20 +63,23 @@ class Command(BaseCommand):
def get_ldap_users(self):
filter = "(&(objectclass=user)(|(memberof=CN=lgs_ilb,OU=GruposAutomaticosOU,DC=senado,DC=gov,DC=br)(memberof=CN=lgt_ilb,OU=GruposAutomaticosOU,DC=senado,DC=gov,DC=br)(memberof=CN=lge_ilb,OU=GruposAutomaticosOU,DC=senado,DC=gov,DC=br)))"
- values = ['sAMAccountName', 'userPrincipalName', 'givenName', 'sn', 'cn']
+ values = [
+ "sAMAccountName",
+ "userPrincipalName",
+ "givenName",
+ "sn",
+ "cn",
+ ]
l = ldap.initialize(AUTH_LDAP_SERVER_URI)
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s(
- AUTH_LDAP_BIND_DN.encode('utf-8'),
- AUTH_LDAP_BIND_PASSWORD
+ AUTH_LDAP_BIND_DN.encode("utf-8"), AUTH_LDAP_BIND_PASSWORD
)
page_control = ldap.controls.SimplePagedResultsControl(
- True,
- size=1000,
- cookie=''
+ True, size=1000, cookie=""
)
result = []
@@ -81,19 +88,22 @@ class Command(BaseCommand):
while True:
pages += 1
response = l.search_ext(
- AUTH_LDAP_USER.encode('utf-8'),
+ AUTH_LDAP_USER.encode("utf-8"),
ldap.SCOPE_SUBTREE,
filter,
values,
- serverctrls=[page_control]
+ serverctrls=[page_control],
)
rtype, rdata, rmsgid, serverctrls = l.result3(response)
result.extend(rdata)
- controls = [control for control in serverctrls
- if control.controlType ==
- ldap.controls.SimplePagedResultsControl.controlType]
+ controls = [
+ control
+ for control in serverctrls
+ if control.controlType
+ == ldap.controls.SimplePagedResultsControl.controlType
+ ]
if not controls:
- raise Exception('The server ignores RFC 2696 control')
+ raise Exception("The server ignores RFC 2696 control")
if not controls[0].cookie:
break
page_control.cookie = controls[0].cookie
@@ -104,12 +114,12 @@ class Command(BaseCommand):
return result
def sync_groups(self):
- print ("Syncing groups...")
+ print("Syncing groups...")
ldap_groups = self.get_ldap_groups()
- print (f"\tFetched groups: {ldap_groups}")
+ print(f"\tFetched groups: {ldap_groups}")
for ldap_group in ldap_groups:
try:
- group_name = ldap_group[1]['cn'][0]
+ group_name = ldap_group[1]["cn"][0]
except:
pass
else:
@@ -118,23 +128,24 @@ class Command(BaseCommand):
except Group.DoesNotExist:
group = Group(name=group_name)
group.save()
- print (f"\tGroup '{group_name}' created.")
- print ("Groups are synchronized.")
+ print(f"\tGroup '{group_name}' created.")
+ print("Groups are synchronized.")
def sync_users(self):
- print ("Syncing users...")
+ print("Syncing users...")
ldap_users = self.get_ldap_users()
- print (f"\tFetched users: {ldap_users}")
+ print(f"\tFetched users: {ldap_users}")
+
def get_ldap_property(ldap_user, property_name, default_value=None):
value = ldap_user[1].get(property_name, None)
- return value[0].decode('utf8') if value else default_value
+ return value[0].decode("utf8") if value else default_value
for ldap_user in ldap_users:
- username = get_ldap_property(ldap_user, 'sAMAccountName')
+ username = get_ldap_property(ldap_user, "sAMAccountName")
if username:
- email = get_ldap_property(ldap_user, 'userPrincipalName', '')
- first_name = get_ldap_property(ldap_user, 'givenName', username)
- last_name = get_ldap_property(ldap_user, 'sn', '')[:30]
+ email = get_ldap_property(ldap_user, "userPrincipalName", "")
+ first_name = get_ldap_property(ldap_user, "givenName", username)
+ last_name = get_ldap_property(ldap_user, "sn", "")[:30]
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
@@ -142,7 +153,9 @@ class Command(BaseCommand):
user = User.objects.get(email=email)
old_username = user.username
user.username = username
- print (f"\tUser with email {email} had his/her username updated from [{old_username}] to [{username}].")
+ print(
+ f"\tUser with email {email} had his/her username updated from [{old_username}] to [{username}]."
+ )
except User.DoesNotExist:
user = User.objects.create_user(
username=username,
@@ -150,33 +163,39 @@ class Command(BaseCommand):
last_name=last_name,
email=email,
)
- print (f"\tUser '{username}' created.")
+ print(f"\tUser '{username}' created.")
if not user.first_name == first_name:
user.first_name = first_name
- print (f"\tUser '{username}' first name updated.")
+ print(f"\tUser '{username}' first name updated.")
if not user.last_name == last_name:
user.last_name = last_name
- print (f"\tUser '{username}' last name updated.")
+ print(f"\tUser '{username}' last name updated.")
if not user.email == email:
user.email = email
- print (f"\tUser '{username}' email updated.")
+ print(f"\tUser '{username}' email updated.")
- nome_completo = get_ldap_property(ldap_user, 'cn', '')
+ nome_completo = get_ldap_property(ldap_user, "cn", "")
try:
servidor = user.servidor
except Servidor.DoesNotExist:
try:
- servidor = Servidor.objects.get(nome_completo=nome_completo)
+ servidor = Servidor.objects.get(
+ nome_completo=nome_completo
+ )
except Servidor.DoesNotExist:
- servidor = user.servidor_set.create(nome_completo=nome_completo)
- print (f"\tServidor '{nome_completo}' created.")
+ servidor = user.servidor_set.create(
+ nome_completo=nome_completo
+ )
+ print(f"\tServidor '{nome_completo}' created.")
else:
if not servidor.nome_completo == nome_completo:
servidor.nome_completo = nome_completo
- print (f"\tFull name of Servidor '{nome_completo}' updated.")
+ print(
+ f"\tFull name of Servidor '{nome_completo}' updated."
+ )
servidor.user = user
servidor.save()
user.save()
- print ("Users are synchronized.")
+ print("Users are synchronized.")
diff --git a/sigi/apps/servidores/management/commands/test_sync_ldap.py b/sigi/apps/servidores/management/commands/test_sync_ldap.py
index 87ee765..73596f0 100644
--- a/sigi/apps/servidores/management/commands/test_sync_ldap.py
+++ b/sigi/apps/servidores/management/commands/test_sync_ldap.py
@@ -10,7 +10,6 @@ pytestmark = pytest.mark.django_db
class StubCommand(Command):
-
def __init__(self, users):
super(StubCommand, self).__init__()
self.users = users
@@ -20,69 +19,172 @@ class StubCommand(Command):
def create_stub_user(username, nome_completo, first_name, last_name, email):
- user = G(User, username=username, first_name=first_name, last_name=last_name, email=email)
+ user = G(
+ User,
+ username=username,
+ first_name=first_name,
+ last_name=last_name,
+ email=email,
+ )
user.servidor.nome_completo = nome_completo
return user
-ALEX_LDAP, BRUNO_LDAP, RITA_LDAP = [
- ('...',
- {'cn': ['Alex Lima'],
- 'givenName': ['Alex'],
- 'sAMAccountName': ['alexlima'],
- 'sn': ['Lima'],
- 'userPrincipalName': ['alexlima@interlegis.leg.br']}),
-
- ('...',
- {'cn': ['Bruno Almeida Prado'],
- 'givenName': ['Bruno'],
- 'sAMAccountName': ['bruno'],
- 'sn': ['Almeida Prado'],
- 'userPrincipalName': ['bruno@interlegis.leg.br']}),
- ('...',
- {'cn': ['Cl\xc3\xa1udia de C\xc3\xa1ssia'],
- 'givenName': ['Cl\xc3\xa1udia'],
- 'sAMAccountName': ['claudia'],
- 'sn': ['de C\xc3\xa1ssia'],
- 'userPrincipalName': ['claudia@interlegis.leg.br']}),
+ALEX_LDAP, BRUNO_LDAP, RITA_LDAP = [
+ (
+ "...",
+ {
+ "cn": ["Alex Lima"],
+ "givenName": ["Alex"],
+ "sAMAccountName": ["alexlima"],
+ "sn": ["Lima"],
+ "userPrincipalName": ["alexlima@interlegis.leg.br"],
+ },
+ ),
+ (
+ "...",
+ {
+ "cn": ["Bruno Almeida Prado"],
+ "givenName": ["Bruno"],
+ "sAMAccountName": ["bruno"],
+ "sn": ["Almeida Prado"],
+ "userPrincipalName": ["bruno@interlegis.leg.br"],
+ },
+ ),
+ (
+ "...",
+ {
+ "cn": ["Cl\xc3\xa1udia de C\xc3\xa1ssia"],
+ "givenName": ["Cl\xc3\xa1udia"],
+ "sAMAccountName": ["claudia"],
+ "sn": ["de C\xc3\xa1ssia"],
+ "userPrincipalName": ["claudia@interlegis.leg.br"],
+ },
+ ),
]
-@pytest.mark.parametrize("before, ldap_users, after, messages", [
- # new user from ldap is created
- ([],
- [ALEX_LDAP],
- [('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br')],
- '''
+@pytest.mark.parametrize(
+ "before, ldap_users, after, messages",
+ [
+ # new user from ldap is created
+ (
+ [],
+ [ALEX_LDAP],
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ )
+ ],
+ """
User 'alexlima' created.
Users are synchronized.
- '''),
-
- # nothing changes
- ([('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br')],
- [ALEX_LDAP],
- [('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br')],
- '''
+ """,
+ ),
+ # nothing changes
+ (
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ )
+ ],
+ [ALEX_LDAP],
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ )
+ ],
+ """
Users are synchronized.
- '''),
-
- # unicode encoding from LDAP data works well
- ([('claudia', 'Cláudia de Cássia', 'Cláudia', 'de Cássia', 'claudia@interlegis.leg.br', )],
- [RITA_LDAP],
- [('claudia', 'Cláudia de Cássia', 'Cláudia', 'de Cássia', 'claudia@interlegis.leg.br', )],
- '''
+ """,
+ ),
+ # unicode encoding from LDAP data works well
+ (
+ [
+ (
+ "claudia",
+ "Cláudia de Cássia",
+ "Cláudia",
+ "de Cássia",
+ "claudia@interlegis.leg.br",
+ )
+ ],
+ [RITA_LDAP],
+ [
+ (
+ "claudia",
+ "Cláudia de Cássia",
+ "Cláudia",
+ "de Cássia",
+ "claudia@interlegis.leg.br",
+ )
+ ],
+ """
Users are synchronized.
- '''),
-
- # update: full name, first name, last name, email
- ([('alexlima', '___', '___', '___', '___', ),
- ('bruno', 'Bruno Almeida Prado', '___', 'Almeida Prado', '___', ),
- ('claudia', '___', 'Cláudia', '___', 'claudia@interlegis.leg.br', )],
- [ALEX_LDAP, BRUNO_LDAP, RITA_LDAP],
- [('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br', ),
- ('bruno', 'Bruno Almeida Prado', 'Bruno', 'Almeida Prado', 'bruno@interlegis.leg.br', ),
- ('claudia', 'Cláudia de Cássia', 'Cláudia', 'de Cássia', 'claudia@interlegis.leg.br', )],
- '''
+ """,
+ ),
+ # update: full name, first name, last name, email
+ (
+ [
+ (
+ "alexlima",
+ "___",
+ "___",
+ "___",
+ "___",
+ ),
+ (
+ "bruno",
+ "Bruno Almeida Prado",
+ "___",
+ "Almeida Prado",
+ "___",
+ ),
+ (
+ "claudia",
+ "___",
+ "Cláudia",
+ "___",
+ "claudia@interlegis.leg.br",
+ ),
+ ],
+ [ALEX_LDAP, BRUNO_LDAP, RITA_LDAP],
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ ),
+ (
+ "bruno",
+ "Bruno Almeida Prado",
+ "Bruno",
+ "Almeida Prado",
+ "bruno@interlegis.leg.br",
+ ),
+ (
+ "claudia",
+ "Cláudia de Cássia",
+ "Cláudia",
+ "de Cássia",
+ "claudia@interlegis.leg.br",
+ ),
+ ],
+ """
User 'alexlima' first name updated.
User 'alexlima' last name updated.
User 'alexlima' email updated.
@@ -93,30 +195,69 @@ Full name of Servidor 'Bruno Almeida Prado' updated.
User 'claudia' last name updated.
Full name of Servidor 'Cláudia de Cássia' updated.
Users are synchronized.
- '''),
-
- # update username (username from LDAP not in base, so match user by email and update username)
- # TODO: is this functionality really necessary? If not remove this and corresponding code
-
- # connect servidor with nome_completo to user
- # TODO: is this functionality really necessary? If not remove this and corresponding code
-
- # create new servidor with nome_completo and connect to user
- # TODO: is this functionality really necessary? If not remove this and corresponding code
-
-
- # user not present in ldap is NOT deleted
- ([('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br', ),
- ('bruno', 'Bruno Almeida Prado', 'Bruno', 'Almeida Prado', 'bruno@interlegis.leg.br', ),
- ('claudia', 'Cláudia de Cássia', 'Cláudia', 'de Cássia', 'claudia@interlegis.leg.br', )],
- [ALEX_LDAP, RITA_LDAP],
- [('alexlima', 'Alex Lima', 'Alex', 'Lima', 'alexlima@interlegis.leg.br', ),
- ('bruno', 'Bruno Almeida Prado', 'Bruno', 'Almeida Prado', 'bruno@interlegis.leg.br', ),
- ('claudia', 'Cláudia de Cássia', 'Cláudia', 'de Cássia', 'claudia@interlegis.leg.br', )],
- '''
+ """,
+ ),
+ # update username (username from LDAP not in base, so match user by email and update username)
+ # TODO: is this functionality really necessary? If not remove this and corresponding code
+ # connect servidor with nome_completo to user
+ # TODO: is this functionality really necessary? If not remove this and corresponding code
+ # create new servidor with nome_completo and connect to user
+ # TODO: is this functionality really necessary? If not remove this and corresponding code
+ # user not present in ldap is NOT deleted
+ (
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ ),
+ (
+ "bruno",
+ "Bruno Almeida Prado",
+ "Bruno",
+ "Almeida Prado",
+ "bruno@interlegis.leg.br",
+ ),
+ (
+ "claudia",
+ "Cláudia de Cássia",
+ "Cláudia",
+ "de Cássia",
+ "claudia@interlegis.leg.br",
+ ),
+ ],
+ [ALEX_LDAP, RITA_LDAP],
+ [
+ (
+ "alexlima",
+ "Alex Lima",
+ "Alex",
+ "Lima",
+ "alexlima@interlegis.leg.br",
+ ),
+ (
+ "bruno",
+ "Bruno Almeida Prado",
+ "Bruno",
+ "Almeida Prado",
+ "bruno@interlegis.leg.br",
+ ),
+ (
+ "claudia",
+ "Cláudia de Cássia",
+ "Cláudia",
+ "de Cássia",
+ "claudia@interlegis.leg.br",
+ ),
+ ],
+ """
Users are synchronized.
- '''),
-])
+ """,
+ ),
+ ],
+)
def test_sync_users(before, ldap_users, after, messages, capsys):
# setup
@@ -127,12 +268,18 @@ def test_sync_users(before, ldap_users, after, messages, capsys):
command = StubCommand(ldap_users)
command.sync_users()
- users = User.objects.all().order_by('username')
+ users = User.objects.all().order_by("username")
for user, expected in zip(users, after):
- real = user.username, user.servidor.nome_completo, user.first_name, user.last_name, user.email
+ real = (
+ user.username,
+ user.servidor.nome_completo,
+ user.first_name,
+ user.last_name,
+ user.email,
+ )
assert real == expected
# feedbak messages
out, err = capsys.readouterr()
assert out.strip() == messages.strip()
- assert err == ''
+ assert err == ""
diff --git a/sigi/apps/servidores/migrations/0001_initial.py b/sigi/apps/servidores/migrations/0001_initial.py
index 94139df..2b68bbc 100644
--- a/sigi/apps/servidores/migrations/0001_initial.py
+++ b/sigi/apps/servidores/migrations/0001_initial.py
@@ -13,140 +13,401 @@ class Migration(migrations.Migration):
operations = [
migrations.CreateModel(
- name='Ferias',
+ name="Ferias",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('inicio_ferias', models.DateField(verbose_name='in\xedcio das f\xe9rias')),
- ('fim_ferias', models.DateField(verbose_name='fim das f\xe9rias')),
- ('obs', models.TextField(null=True, verbose_name='observa\xe7\xe3o', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "inicio_ferias",
+ models.DateField(verbose_name="in\xedcio das f\xe9rias"),
+ ),
+ (
+ "fim_ferias",
+ models.DateField(verbose_name="fim das f\xe9rias"),
+ ),
+ (
+ "obs",
+ models.TextField(
+ null=True, verbose_name="observa\xe7\xe3o", blank=True
+ ),
+ ),
],
options={
- 'verbose_name': 'f\xe9rias',
- 'verbose_name_plural': 'f\xe9rias',
+ "verbose_name": "f\xe9rias",
+ "verbose_name_plural": "f\xe9rias",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Funcao',
+ name="Funcao",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('funcao', models.CharField(max_length=250, null=True)),
- ('cargo', models.CharField(max_length=250, null=True)),
- ('inicio_funcao', models.DateField(null=True, verbose_name='in\xedcio da fun\xe7\xe3o')),
- ('fim_funcao', models.DateField(null=True, verbose_name='fim da fun\xe7\xe3o', blank=True)),
- ('descricao', models.TextField(null=True, verbose_name='descri\xe7\xe3o', blank=True)),
- ('bap_entrada', models.CharField(max_length=50, null=True, verbose_name='BAP de entrada', blank=True)),
- ('data_bap_entrada', models.DateField(null=True, verbose_name='data BAP de entrada', blank=True)),
- ('bap_saida', models.CharField(max_length=50, null=True, verbose_name='BAP de sa\xedda', blank=True)),
- ('data_bap_saida', models.DateField(null=True, verbose_name='data BAP de sa\xedda', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("funcao", models.CharField(max_length=250, null=True)),
+ ("cargo", models.CharField(max_length=250, null=True)),
+ (
+ "inicio_funcao",
+ models.DateField(
+ null=True, verbose_name="in\xedcio da fun\xe7\xe3o"
+ ),
+ ),
+ (
+ "fim_funcao",
+ models.DateField(
+ null=True,
+ verbose_name="fim da fun\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "descricao",
+ models.TextField(
+ null=True, verbose_name="descri\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "bap_entrada",
+ models.CharField(
+ max_length=50,
+ null=True,
+ verbose_name="BAP de entrada",
+ blank=True,
+ ),
+ ),
+ (
+ "data_bap_entrada",
+ models.DateField(
+ null=True,
+ verbose_name="data BAP de entrada",
+ blank=True,
+ ),
+ ),
+ (
+ "bap_saida",
+ models.CharField(
+ max_length=50,
+ null=True,
+ verbose_name="BAP de sa\xedda",
+ blank=True,
+ ),
+ ),
+ (
+ "data_bap_saida",
+ models.DateField(
+ null=True,
+ verbose_name="data BAP de sa\xedda",
+ blank=True,
+ ),
+ ),
],
options={
- 'verbose_name': 'fun\xe7\xe3o',
- 'verbose_name_plural': 'fun\xe7\xf5es',
+ "verbose_name": "fun\xe7\xe3o",
+ "verbose_name_plural": "fun\xe7\xf5es",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Licenca',
+ name="Licenca",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('inicio_licenca', models.DateField(verbose_name='in\xedcio da licen\xe7a')),
- ('fim_licenca', models.DateField(verbose_name='fim da licen\xe7a')),
- ('obs', models.TextField(null=True, verbose_name='observa\xe7\xe3o', blank=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "inicio_licenca",
+ models.DateField(verbose_name="in\xedcio da licen\xe7a"),
+ ),
+ (
+ "fim_licenca",
+ models.DateField(verbose_name="fim da licen\xe7a"),
+ ),
+ (
+ "obs",
+ models.TextField(
+ null=True, verbose_name="observa\xe7\xe3o", blank=True
+ ),
+ ),
],
options={
- 'verbose_name': 'licen\xe7a',
- 'verbose_name_plural': 'licen\xe7as',
+ "verbose_name": "licen\xe7a",
+ "verbose_name_plural": "licen\xe7as",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Servico',
+ name="Servico",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=250, null=True, verbose_name='Setor')),
- ('sigla', models.CharField(max_length=10, null=True)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ (
+ "nome",
+ models.CharField(
+ max_length=250, null=True, verbose_name="Setor"
+ ),
+ ),
+ ("sigla", models.CharField(max_length=10, null=True)),
],
options={
- 'ordering': ('nome',),
- 'verbose_name': 'servi\xe7o',
- 'verbose_name_plural': 'servi\xe7os',
+ "ordering": ("nome",),
+ "verbose_name": "servi\xe7o",
+ "verbose_name_plural": "servi\xe7os",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Servidor',
+ name="Servidor",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome_completo', models.CharField(max_length=128)),
- ('apelido', models.CharField(max_length=50, blank=True)),
- ('foto', models.ImageField(height_field='foto_altura', width_field='foto_largura', upload_to='fotos/servidores', blank=True)),
- ('foto_largura', models.SmallIntegerField(null=True, editable=False)),
- ('foto_altura', models.SmallIntegerField(null=True, editable=False)),
- ('sexo', models.CharField(blank=True, max_length=1, null=True, choices=[('M', 'Masculino'), ('F', 'Feminino')])),
- ('data_nascimento', models.DateField(null=True, verbose_name='data de nascimento', blank=True)),
- ('matricula', models.CharField(max_length=25, null=True, verbose_name='matr\xedcula', blank=True)),
- ('turno', models.CharField(blank=True, max_length=1, null=True, choices=[('M', 'Manh\xe3'), ('T', 'Tarde'), ('N', 'Noite')])),
- ('de_fora', models.BooleanField(default=False)),
- ('data_nomeacao', models.DateField(null=True, verbose_name='data de nomea\xe7\xe3o', blank=True)),
- ('ato_exoneracao', models.CharField(max_length=150, null=True, verbose_name='ato de exonera\xe7\xe3o', blank=True)),
- ('ato_numero', models.CharField(max_length=150, null=True, verbose_name='ato de exonera\xe7\xe3o', blank=True)),
- ('cpf', models.CharField(max_length=11, null=True, verbose_name='CPF', blank=True)),
- ('rg', models.CharField(max_length=25, null=True, verbose_name='RG', blank=True)),
- ('obs', models.TextField(null=True, verbose_name='observa\xe7\xe3o', blank=True)),
- ('apontamentos', models.TextField(null=True, verbose_name='apontamentos', blank=True)),
- ('email_pessoal', models.EmailField(max_length=75, null=True, verbose_name='email pessoal', blank=True)),
- ('ramal', models.CharField(max_length=25, null=True, blank=True)),
- ('servico', models.ForeignKey(blank=True, to='servidores.Servico', null=True, on_delete=models.CASCADE)),
- ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True, on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome_completo", models.CharField(max_length=128)),
+ ("apelido", models.CharField(max_length=50, blank=True)),
+ (
+ "foto",
+ models.ImageField(
+ height_field="foto_altura",
+ width_field="foto_largura",
+ upload_to="fotos/servidores",
+ blank=True,
+ ),
+ ),
+ (
+ "foto_largura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "foto_altura",
+ models.SmallIntegerField(null=True, editable=False),
+ ),
+ (
+ "sexo",
+ models.CharField(
+ blank=True,
+ max_length=1,
+ null=True,
+ choices=[("M", "Masculino"), ("F", "Feminino")],
+ ),
+ ),
+ (
+ "data_nascimento",
+ models.DateField(
+ null=True, verbose_name="data de nascimento", blank=True
+ ),
+ ),
+ (
+ "matricula",
+ models.CharField(
+ max_length=25,
+ null=True,
+ verbose_name="matr\xedcula",
+ blank=True,
+ ),
+ ),
+ (
+ "turno",
+ models.CharField(
+ blank=True,
+ max_length=1,
+ null=True,
+ choices=[
+ ("M", "Manh\xe3"),
+ ("T", "Tarde"),
+ ("N", "Noite"),
+ ],
+ ),
+ ),
+ ("de_fora", models.BooleanField(default=False)),
+ (
+ "data_nomeacao",
+ models.DateField(
+ null=True,
+ verbose_name="data de nomea\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "ato_exoneracao",
+ models.CharField(
+ max_length=150,
+ null=True,
+ verbose_name="ato de exonera\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "ato_numero",
+ models.CharField(
+ max_length=150,
+ null=True,
+ verbose_name="ato de exonera\xe7\xe3o",
+ blank=True,
+ ),
+ ),
+ (
+ "cpf",
+ models.CharField(
+ max_length=11, null=True, verbose_name="CPF", blank=True
+ ),
+ ),
+ (
+ "rg",
+ models.CharField(
+ max_length=25, null=True, verbose_name="RG", blank=True
+ ),
+ ),
+ (
+ "obs",
+ models.TextField(
+ null=True, verbose_name="observa\xe7\xe3o", blank=True
+ ),
+ ),
+ (
+ "apontamentos",
+ models.TextField(
+ null=True, verbose_name="apontamentos", blank=True
+ ),
+ ),
+ (
+ "email_pessoal",
+ models.EmailField(
+ max_length=75,
+ null=True,
+ verbose_name="email pessoal",
+ blank=True,
+ ),
+ ),
+ (
+ "ramal",
+ models.CharField(max_length=25, null=True, blank=True),
+ ),
+ (
+ "servico",
+ models.ForeignKey(
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ to=settings.AUTH_USER_MODEL,
+ unique=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('nome_completo',),
- 'verbose_name_plural': 'servidores',
+ "ordering": ("nome_completo",),
+ "verbose_name_plural": "servidores",
},
bases=(models.Model,),
),
migrations.CreateModel(
- name='Subsecretaria',
+ name="Subsecretaria",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('nome', models.CharField(max_length=250, null=True)),
- ('sigla', models.CharField(max_length=10, null=True)),
- ('responsavel', models.ForeignKey(related_name='diretor', to='servidores.Servidor', null=True, on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("nome", models.CharField(max_length=250, null=True)),
+ ("sigla", models.CharField(max_length=10, null=True)),
+ (
+ "responsavel",
+ models.ForeignKey(
+ related_name="diretor",
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
+ ),
],
options={
- 'ordering': ('nome',),
+ "ordering": ("nome",),
},
bases=(models.Model,),
),
migrations.AddField(
- model_name='servico',
- name='responsavel',
- field=models.ForeignKey(related_name='chefe', to='servidores.Servidor', null=True, on_delete=models.CASCADE),
+ model_name="servico",
+ name="responsavel",
+ field=models.ForeignKey(
+ related_name="chefe",
+ to="servidores.Servidor",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='servico',
- name='subsecretaria',
- field=models.ForeignKey(to='servidores.Subsecretaria', null=True, on_delete=models.CASCADE),
+ model_name="servico",
+ name="subsecretaria",
+ field=models.ForeignKey(
+ to="servidores.Subsecretaria",
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='licenca',
- name='servidor',
- field=models.ForeignKey(to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="licenca",
+ name="servidor",
+ field=models.ForeignKey(
+ to="servidores.Servidor", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='funcao',
- name='servidor',
- field=models.ForeignKey(to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="funcao",
+ name="servidor",
+ field=models.ForeignKey(
+ to="servidores.Servidor", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='ferias',
- name='servidor',
- field=models.ForeignKey(to='servidores.Servidor', on_delete=models.CASCADE),
+ model_name="ferias",
+ name="servidor",
+ field=models.ForeignKey(
+ to="servidores.Servidor", on_delete=models.CASCADE
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0002_auto_20210416_0841.py b/sigi/apps/servidores/migrations/0002_auto_20210416_0841.py
index a75cb70..4453596 100644
--- a/sigi/apps/servidores/migrations/0002_auto_20210416_0841.py
+++ b/sigi/apps/servidores/migrations/0002_auto_20210416_0841.py
@@ -8,26 +8,41 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0001_initial'),
+ ("servidores", "0001_initial"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='responsavel',
- field=models.ForeignKey(related_name='chefe', on_delete=django.db.models.deletion.SET_NULL, to='servidores.Servidor', null=True),
+ model_name="servico",
+ name="responsavel",
+ field=models.ForeignKey(
+ related_name="chefe",
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servidor',
- name='servico',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, blank=True, to='servidores.Servico', null=True),
+ model_name="servidor",
+ name="servico",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='subsecretaria',
- name='responsavel',
- field=models.ForeignKey(related_name='diretor', on_delete=django.db.models.deletion.SET_NULL, to='servidores.Servidor', null=True),
+ model_name="subsecretaria",
+ name="responsavel",
+ field=models.ForeignKey(
+ related_name="diretor",
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0003_auto_20210422_1729.py b/sigi/apps/servidores/migrations/0003_auto_20210422_1729.py
index 229ed1d..5845e98 100644
--- a/sigi/apps/servidores/migrations/0003_auto_20210422_1729.py
+++ b/sigi/apps/servidores/migrations/0003_auto_20210422_1729.py
@@ -8,102 +8,107 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0002_auto_20210416_0841'),
+ ("servidores", "0002_auto_20210416_0841"),
]
operations = [
migrations.RemoveField(
- model_name='ferias',
- name='servidor',
+ model_name="ferias",
+ name="servidor",
),
migrations.DeleteModel(
- name='Ferias',
+ name="Ferias",
),
migrations.RemoveField(
- model_name='funcao',
- name='servidor',
+ model_name="funcao",
+ name="servidor",
),
migrations.DeleteModel(
- name='Funcao',
+ name="Funcao",
),
migrations.RemoveField(
- model_name='licenca',
- name='servidor',
+ model_name="licenca",
+ name="servidor",
),
migrations.DeleteModel(
- name='Licenca',
+ name="Licenca",
),
migrations.RemoveField(
- model_name='subsecretaria',
- name='responsavel',
+ model_name="subsecretaria",
+ name="responsavel",
),
migrations.RemoveField(
- model_name='servico',
- name='subsecretaria',
+ model_name="servico",
+ name="subsecretaria",
),
migrations.DeleteModel(
- name='Subsecretaria',
+ name="Subsecretaria",
),
migrations.RemoveField(
- model_name='servidor',
- name='apontamentos',
+ model_name="servidor",
+ name="apontamentos",
),
migrations.RemoveField(
- model_name='servidor',
- name='ato_exoneracao',
+ model_name="servidor",
+ name="ato_exoneracao",
),
migrations.RemoveField(
- model_name='servidor',
- name='ato_numero',
+ model_name="servidor",
+ name="ato_numero",
),
migrations.RemoveField(
- model_name='servidor',
- name='cpf',
+ model_name="servidor",
+ name="cpf",
),
migrations.RemoveField(
- model_name='servidor',
- name='data_nascimento',
+ model_name="servidor",
+ name="data_nascimento",
),
migrations.RemoveField(
- model_name='servidor',
- name='data_nomeacao',
+ model_name="servidor",
+ name="data_nomeacao",
),
migrations.RemoveField(
- model_name='servidor',
- name='de_fora',
+ model_name="servidor",
+ name="de_fora",
),
migrations.RemoveField(
- model_name='servidor',
- name='email_pessoal',
+ model_name="servidor",
+ name="email_pessoal",
),
migrations.RemoveField(
- model_name='servidor',
- name='matricula',
+ model_name="servidor",
+ name="matricula",
),
migrations.RemoveField(
- model_name='servidor',
- name='obs',
+ model_name="servidor",
+ name="obs",
),
migrations.RemoveField(
- model_name='servidor',
- name='ramal',
+ model_name="servidor",
+ name="ramal",
),
migrations.RemoveField(
- model_name='servidor',
- name='rg',
+ model_name="servidor",
+ name="rg",
),
migrations.RemoveField(
- model_name='servidor',
- name='sexo',
+ model_name="servidor",
+ name="sexo",
),
migrations.RemoveField(
- model_name='servidor',
- name='turno',
+ model_name="servidor",
+ name="turno",
),
migrations.AddField(
- model_name='servico',
- name='subordinado',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='subordinado a', to='servidores.Servico', null=True),
+ model_name="servico",
+ name="subordinado",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="subordinado a",
+ to="servidores.Servico",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0004_auto_20210422_1907.py b/sigi/apps/servidores/migrations/0004_auto_20210422_1907.py
index 364a337..4760914 100644
--- a/sigi/apps/servidores/migrations/0004_auto_20210422_1907.py
+++ b/sigi/apps/servidores/migrations/0004_auto_20210422_1907.py
@@ -8,20 +8,32 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0003_auto_20210422_1729'),
+ ("servidores", "0003_auto_20210422_1729"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='responsavel',
- field=models.ForeignKey(related_name='chefe', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='servidores.Servidor', null=True),
+ model_name="servico",
+ name="responsavel",
+ field=models.ForeignKey(
+ related_name="chefe",
+ on_delete=django.db.models.deletion.SET_NULL,
+ blank=True,
+ to="servidores.Servidor",
+ null=True,
+ ),
preserve_default=True,
),
migrations.AlterField(
- model_name='servico',
- name='subordinado',
- field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='subordinado a', blank=True, to='servidores.Servico', null=True),
+ model_name="servico",
+ name="subordinado",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.SET_NULL,
+ verbose_name="subordinado a",
+ blank=True,
+ to="servidores.Servico",
+ null=True,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0005_auto_20210423_0904.py b/sigi/apps/servidores/migrations/0005_auto_20210423_0904.py
index 5d0fc81..f3e8f5c 100644
--- a/sigi/apps/servidores/migrations/0005_auto_20210423_0904.py
+++ b/sigi/apps/servidores/migrations/0005_auto_20210423_0904.py
@@ -7,12 +7,16 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0004_auto_20210422_1907'),
+ ("servidores", "0004_auto_20210422_1907"),
]
operations = [
migrations.AlterModelOptions(
- name='servico',
- options={'ordering': ('-subordinado__sigla', 'nome'), 'verbose_name': 'servi\xe7o', 'verbose_name_plural': 'servi\xe7os'},
+ name="servico",
+ options={
+ "ordering": ("-subordinado__sigla", "nome"),
+ "verbose_name": "servi\xe7o",
+ "verbose_name_plural": "servi\xe7os",
+ },
),
]
diff --git a/sigi/apps/servidores/migrations/0006_auto_20210429_0822.py b/sigi/apps/servidores/migrations/0006_auto_20210429_0822.py
index d50e2cb..90f23ae 100644
--- a/sigi/apps/servidores/migrations/0006_auto_20210429_0822.py
+++ b/sigi/apps/servidores/migrations/0006_auto_20210429_0822.py
@@ -8,14 +8,19 @@ from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0005_auto_20210423_0904'),
+ ("servidores", "0005_auto_20210423_0904"),
]
operations = [
migrations.AlterField(
- model_name='servidor',
- name='user',
- field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE),
+ model_name="servidor",
+ name="user",
+ field=models.ForeignKey(
+ blank=True,
+ to=settings.AUTH_USER_MODEL,
+ null=True,
+ on_delete=models.CASCADE,
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0007_auto_20210430_0735.py b/sigi/apps/servidores/migrations/0007_auto_20210430_0735.py
index d6c5300..162ab9f 100644
--- a/sigi/apps/servidores/migrations/0007_auto_20210430_0735.py
+++ b/sigi/apps/servidores/migrations/0007_auto_20210430_0735.py
@@ -7,26 +7,34 @@ from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0006_auto_20210429_0822'),
+ ("servidores", "0006_auto_20210429_0822"),
]
operations = [
migrations.AddField(
- model_name='servidor',
- name='externo',
- field=models.BooleanField(default=False, verbose_name='colaborador externo'),
+ model_name="servidor",
+ name="externo",
+ field=models.BooleanField(
+ default=False, verbose_name="colaborador externo"
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='servidor',
- name='orgao_origem',
- field=models.CharField(max_length=100, verbose_name='\xf3rg\xe3o de origem, ', blank=True),
+ model_name="servidor",
+ name="orgao_origem",
+ field=models.CharField(
+ max_length=100,
+ verbose_name="\xf3rg\xe3o de origem, ",
+ blank=True,
+ ),
preserve_default=True,
),
migrations.AddField(
- model_name='servidor',
- name='qualificacoes',
- field=models.TextField(verbose_name='qualifica\xe7\xf5es', blank=True),
+ model_name="servidor",
+ name="qualificacoes",
+ field=models.TextField(
+ verbose_name="qualifica\xe7\xf5es", blank=True
+ ),
preserve_default=True,
),
]
diff --git a/sigi/apps/servidores/migrations/0008_alter_servico_id_alter_servidor_foto_and_more.py b/sigi/apps/servidores/migrations/0008_alter_servico_id_alter_servidor_foto_and_more.py
index cf35107..a9e1087 100644
--- a/sigi/apps/servidores/migrations/0008_alter_servico_id_alter_servidor_foto_and_more.py
+++ b/sigi/apps/servidores/migrations/0008_alter_servico_id_alter_servidor_foto_and_more.py
@@ -6,23 +6,38 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
- ('servidores', '0007_auto_20210430_0735'),
+ ("servidores", "0007_auto_20210430_0735"),
]
operations = [
migrations.AlterField(
- model_name='servico',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="servico",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
migrations.AlterField(
- model_name='servidor',
- name='foto',
- field=models.ImageField(blank=True, height_field='foto_altura', upload_to='fotos/servidores', width_field='foto_largura'),
+ model_name="servidor",
+ name="foto",
+ field=models.ImageField(
+ blank=True,
+ height_field="foto_altura",
+ upload_to="fotos/servidores",
+ width_field="foto_largura",
+ ),
),
migrations.AlterField(
- model_name='servidor',
- name='id',
- field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
+ model_name="servidor",
+ name="id",
+ field=models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
),
]
diff --git a/sigi/apps/servidores/models.py b/sigi/apps/servidores/models.py
index 21d4970..8c40c46 100644
--- a/sigi/apps/servidores/models.py
+++ b/sigi/apps/servidores/models.py
@@ -3,65 +3,63 @@ from django.db import models
from django.db.models.signals import post_save, pre_save
from django.utils.translation import gettext as _
+
class Servico(models.Model):
- nome = models.CharField(_('Setor'), max_length=250, null=True)
+ nome = models.CharField(_("Setor"), max_length=250, null=True)
sigla = models.CharField(max_length=10, null=True)
subordinado = models.ForeignKey(
- 'self',
+ "self",
on_delete=models.SET_NULL,
null=True,
blank=True,
- verbose_name=_("subordinado a")
+ verbose_name=_("subordinado a"),
)
responsavel = models.ForeignKey(
- 'servidores.Servidor',
+ "servidores.Servidor",
on_delete=models.SET_NULL,
- related_name='chefe',
+ related_name="chefe",
null=True,
- blank=True
+ blank=True,
)
class Meta:
- ordering = ('-subordinado__sigla', 'nome',)
- verbose_name = _('serviço')
- verbose_name_plural = _('serviços')
+ ordering = (
+ "-subordinado__sigla",
+ "nome",
+ )
+ verbose_name = _("serviço")
+ verbose_name_plural = _("serviços")
def __str__(self):
return f"{self.sigla} - {self.nome}"
+
class Servidor(models.Model):
user = models.ForeignKey(
- User,
- on_delete=models.CASCADE,
- null=True,
- blank=True
+ User, on_delete=models.CASCADE, null=True, blank=True
)
nome_completo = models.CharField(max_length=128)
apelido = models.CharField(max_length=50, blank=True)
foto = models.ImageField(
- upload_to='fotos/servidores',
- width_field='foto_largura',
- height_field='foto_altura',
- blank=True
+ upload_to="fotos/servidores",
+ width_field="foto_largura",
+ height_field="foto_altura",
+ blank=True,
)
foto_largura = models.SmallIntegerField(editable=False, null=True)
foto_altura = models.SmallIntegerField(editable=False, null=True)
servico = models.ForeignKey(
- Servico,
- on_delete=models.SET_NULL,
- blank=True,
- null=True
+ Servico, on_delete=models.SET_NULL, blank=True, null=True
)
externo = models.BooleanField(_("colaborador externo"), default=False)
orgao_origem = models.CharField(
- _("órgão de origem, "),
- max_length=100, blank=True
+ _("órgão de origem, "), max_length=100, blank=True
)
qualificacoes = models.TextField(_("qualificações"), blank=True)
class Meta:
- ordering = ('nome_completo',)
- verbose_name_plural = 'servidores'
+ ordering = ("nome_completo",)
+ verbose_name_plural = "servidores"
def __str__(self):
return self.nome_completo
@@ -75,15 +73,18 @@ class Servidor(models.Model):
if self.apelido:
return self.apelido
else:
- nomes = self.nome_completo.split(' ')
+ nomes = self.nome_completo.split(" ")
return nomes[0]
+
# Soluçao alternativa para extender o usuário do django
# Acessa do servidor de um objeto user criando um profile
# baseado nos dados do LDAP
-User.servidor = property(lambda user: Servidor.objects.get(user=user)
- if Servidor.objects.filter(user=user).exists()
- else None)
+User.servidor = property(
+ lambda user: Servidor.objects.get(user=user)
+ if Servidor.objects.filter(user=user).exists()
+ else None
+)
# Sinal para ao criar um usuário criar um servidor
# baseado no nome contido no LDAP
@@ -91,9 +92,10 @@ def create_user_profile(sender, instance, created, **kwargs):
if created:
Servidor.objects.create(
user=instance,
- nome_completo="%s %s" % (instance.first_name, instance.last_name)
+ nome_completo="%s %s" % (instance.first_name, instance.last_name),
)
+
post_save.connect(create_user_profile, sender=User)
# Hack horrível para ajustar o first_name e o last_name do User criado pelo
@@ -104,4 +106,5 @@ def ajusta_nome_usuario(sender, instance, *args, **kwargs):
instance.first_name = instance.first_name[:30]
instance.last_name = instance.last_name[:30]
-pre_save.connect(ajusta_nome_usuario, sender=User)
\ No newline at end of file
+
+pre_save.connect(ajusta_nome_usuario, sender=User)
diff --git a/sigi/apps/utils/__init__.py b/sigi/apps/utils/__init__.py
index 6a1b8f7..b226836 100644
--- a/sigi/apps/utils/__init__.py
+++ b/sigi/apps/utils/__init__.py
@@ -6,44 +6,47 @@ from django.utils.encoding import force_str
class SearchField(models.TextField):
-
def pre_save(self, model_instance, add):
search_text = []
for field_name in self.field_names:
val = force_str(to_ascii(getattr(model_instance, field_name)))
search_text.append(val)
- value = ' '.join(search_text)
+ value = " ".join(search_text)
setattr(model_instance, self.name, value)
return value
def __init__(self, field_names, *args, **kwargs):
self.field_names = field_names
- kwargs['editable'] = False
+ kwargs["editable"] = False
super(self.__class__, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(SearchField, self).deconstruct()
- kwargs['field_names'] = self.field_names
+ kwargs["field_names"] = self.field_names
return name, path, args, kwargs
-def to_ascii(txt, codif='utf-8'):
+def to_ascii(txt, codif="utf-8"):
if not isinstance(txt, str):
txt = force_str(txt)
if isinstance(txt, str):
- txt = txt.encode('utf-8')
- return normalize('NFKD', txt.decode(codif)).encode(
- 'ASCII', 'ignore').decode(codif)
+ txt = txt.encode("utf-8")
+ return (
+ normalize("NFKD", txt.decode(codif))
+ .encode("ASCII", "ignore")
+ .decode(codif)
+ )
def queryset_ascii(self, request):
- if 'q' in request.GET:
+ if "q" in request.GET:
request.GET._mutable = True
- request.GET['q'] = to_ascii(request.GET['q'])
+ request.GET["q"] = to_ascii(request.GET["q"])
return admin.ModelAdmin.get_queryset(self, request)
+
def field_label(name, model):
- name = name.split('__')
+ name = name.split("__")
try:
field = model._meta.get_field(name[0])
except FieldDoesNotExist:
@@ -58,4 +61,4 @@ def field_label(name, model):
to_model = field.get_path_info()[0].to_opts.model
label = label + "/" + field_label("__".join(name[1:]), to_model)
- return label
\ No newline at end of file
+ return label
diff --git a/sigi/apps/utils/apps.py b/sigi/apps/utils/apps.py
index fdf4443..58013e8 100644
--- a/sigi/apps/utils/apps.py
+++ b/sigi/apps/utils/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
+
class UtilsConfig(AppConfig):
- name = 'sigi.apps.utils'
- verbose_name = _('utiliátios SIGI')
+ name = "sigi.apps.utils"
+ verbose_name = _("utiliátios SIGI")
diff --git a/sigi/apps/utils/base_admin.py b/sigi/apps/utils/base_admin.py
index 394a9f8..16a7fb5 100644
--- a/sigi/apps/utils/base_admin.py
+++ b/sigi/apps/utils/base_admin.py
@@ -4,7 +4,7 @@ from django.contrib.admin.views.main import ChangeList
class ClearAllFilter(object):
title = None
- template = 'clear_all_filter.html'
+ template = "clear_all_filter.html"
def __init__(self, disabled):
self.disabled = disabled
@@ -17,10 +17,10 @@ class ClearAllFilter(object):
class BaseChangeList(ChangeList):
-
def get_filters(self, request):
- (filter_specs, has_filters, lookup_params,
- use_distinct) = super(BaseChangeList, self).get_filters(request)
+ (filter_specs, has_filters, lookup_params, use_distinct) = super(
+ BaseChangeList, self
+ ).get_filters(request)
if filter_specs:
clear_all_disabled = not self.get_filters_params()
filter_specs = [ClearAllFilter(clear_all_disabled)] + filter_specs
diff --git a/sigi/apps/utils/decorators.py b/sigi/apps/utils/decorators.py
index 85d6786..db05857 100644
--- a/sigi/apps/utils/decorators.py
+++ b/sigi/apps/utils/decorators.py
@@ -11,6 +11,7 @@ obsoleto.
"""
import urlparse
+
try:
from functools import wraps
except ImportError:
@@ -21,7 +22,9 @@ from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.decorators import available_attrs
-def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
+def user_passes_test(
+ test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME
+):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
@@ -36,19 +39,26 @@ def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIE
path = request.build_absolute_uri()
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
- login_scheme, login_netloc = urlparse.urlparse(login_url or
- settings.LOGIN_URL)[:2]
+ login_scheme, login_netloc = urlparse.urlparse(
+ login_url or settings.LOGIN_URL
+ )[:2]
current_scheme, current_netloc = urlparse.urlparse(path)[:2]
- if ((not login_scheme or login_scheme == current_scheme) and
- (not login_netloc or login_netloc == current_netloc)):
+ if (not login_scheme or login_scheme == current_scheme) and (
+ not login_netloc or login_netloc == current_netloc
+ ):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
+
return redirect_to_login(path, login_url, redirect_field_name)
+
return _wrapped_view
+
return decorator
-def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
+def login_required(
+ function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None
+):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
@@ -56,7 +66,7 @@ def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login
actual_decorator = user_passes_test(
lambda u: u.is_authenticated(),
login_url=login_url,
- redirect_field_name=redirect_field_name
+ redirect_field_name=redirect_field_name,
)
if function:
return actual_decorator(function)
diff --git a/sigi/apps/utils/email.py b/sigi/apps/utils/email.py
index 00cabce..d60ad32 100644
--- a/sigi/apps/utils/email.py
+++ b/sigi/apps/utils/email.py
@@ -28,6 +28,10 @@ def enviar_email(from_email, subject, template, tags):
mensagem = render_to_string(template, tags)
# Enviando a mensagem
- email = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + " " + subject, mensagem,
- from_email, [from_email])
+ email = EmailMessage(
+ settings.EMAIL_SUBJECT_PREFIX + " " + subject,
+ mensagem,
+ from_email,
+ [from_email],
+ )
email.send()
diff --git a/sigi/apps/utils/filters.py b/sigi/apps/utils/filters.py
index 777ce3d..7bc0a18 100644
--- a/sigi/apps/utils/filters.py
+++ b/sigi/apps/utils/filters.py
@@ -7,23 +7,31 @@ from django.contrib.admin.options import IncorrectLookupParameters
from django.utils.translation import ngettext, gettext as _
from django.core.exceptions import ValidationError
+
class NotEmptyableField(Exception):
pass
class AlphabeticFilter(admin.SimpleListFilter):
- title = ''
- parameter_name = ''
+ title = ""
+ parameter_name = ""
def lookups(self, request, model_admin):
- return ((letter, letter,) for letter in string.ascii_uppercase)
+ return (
+ (
+ letter,
+ letter,
+ )
+ for letter in string.ascii_uppercase
+ )
def queryset(self, request, queryset):
if self.value():
return queryset.filter(
- (self.parameter_name + '__istartswith', self.value())
+ (self.parameter_name + "__istartswith", self.value())
)
+
class EmptyFilter(admin.FieldListFilter):
EMPTY_STRING = _("Em branco")
NOT_EMPTY_STRING = _("Preenchido")
@@ -31,7 +39,7 @@ class EmptyFilter(admin.FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.model = model
self.model_admin = model_admin
- self.parameter_name = f'{field_path}__empty'
+ self.parameter_name = f"{field_path}__empty"
if (not field.null) and (not field.blank):
raise NotEmptyableField(
@@ -51,22 +59,26 @@ class EmptyFilter(admin.FieldListFilter):
def choices(self, changelist):
yield {
- 'selected': self.value() is None,
- 'query_string': changelist.get_query_string(remove=[
- self.parameter_name]),
- 'display': _('All'),
+ "selected": self.value() is None,
+ "query_string": changelist.get_query_string(
+ remove=[self.parameter_name]
+ ),
+ "display": _("All"),
}
for value, display in self.lookups():
yield {
- 'selected': self.value() == value,
- 'query_string': changelist.get_query_string(
- {self.parameter_name: value}),
- 'display': display,
+ "selected": self.value() == value,
+ "query_string": changelist.get_query_string(
+ {self.parameter_name: value}
+ ),
+ "display": display,
}
def expected_parameters(self):
- return [self.parameter_name,]
+ return [
+ self.parameter_name,
+ ]
def queryset(self, request, queryset):
val = self.value()
@@ -88,6 +100,7 @@ class EmptyFilter(admin.FieldListFilter):
return queryset.filter(filter)
+
class RangeFilter(admin.FieldListFilter):
num_faixas = 4
parameter_name = None
@@ -95,7 +108,7 @@ class RangeFilter(admin.FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.model = model
self.model_admin = model_admin
- self.parameter_name = f'{field_path}__range'
+ self.parameter_name = f"{field_path}__range"
super().__init__(field, request, params, model, model_admin, field_path)
@@ -110,22 +123,23 @@ class RangeFilter(admin.FieldListFilter):
def ranges(self, model):
tudo = model.objects.values_list(self.field_path, flat=True).order_by(
- self.field_path)
+ self.field_path
+ )
passo = len(tudo) // self.num_faixas
ultimo = 0
for i in range(1, self.num_faixas):
- value = tudo[i*passo]
+ value = tudo[i * passo]
if value > 100:
if value > 1000:
l = int(log10(value))
else:
- l = int(log10(value))-1
+ l = int(log10(value)) - 1
value = value // (10**l) * (10**l)
yield (i, ultimo, value)
ultimo = value
- yield (self.num_faixas, ultimo, tudo.last()+1)
+ yield (self.num_faixas, ultimo, tudo.last() + 1)
def lookups(self, request, model_admin):
def humanize(num):
@@ -134,27 +148,25 @@ class RangeFilter(admin.FieldListFilter):
l = int(log10(num))
if l < 6:
return ngettext(
- f"{num//10**3} mil",
- f"{num//10**3} mil",
- num//10**3
+ f"{num//10**3} mil", f"{num//10**3} mil", num // 10**3
)
elif l < 9:
return ngettext(
f"{num//10**6} milhão",
f"{num//10**6} milhões",
- num//10**6
+ num // 10**6,
)
elif l < 12:
return ngettext(
f"{num//10**9} bilhão",
f"{num//10**9} bilhões",
- num//10**9
+ num // 10**9,
)
else:
return ngettext(
f"{num//10**12} trilhão",
f"{num//10**12} trilhões",
- num//10**12
+ num // 10**12,
)
primeiro, *meio, ultimo = self.ranges(self.model)
@@ -172,22 +184,25 @@ class RangeFilter(admin.FieldListFilter):
return self.used_parameters.get(self.parameter_name)
def expected_parameters(self):
- return [self.parameter_name,]
+ return [
+ self.parameter_name,
+ ]
def choices(self, changelist):
yield {
- 'selected': self.value() is None,
- 'query_string': changelist.get_query_string(
- remove=[self.parameter_name]),
- 'display': _('All'),
+ "selected": self.value() is None,
+ "query_string": changelist.get_query_string(
+ remove=[self.parameter_name]
+ ),
+ "display": _("All"),
}
for lookup, title in self.lookup_choices:
yield {
- 'selected': self.value() == str(lookup),
- 'query_string': changelist.get_query_string(
+ "selected": self.value() == str(lookup),
+ "query_string": changelist.get_query_string(
{self.parameter_name: lookup}
),
- 'display': title,
+ "display": title,
}
def queryset(self, request, queryset):
@@ -195,27 +210,30 @@ class RangeFilter(admin.FieldListFilter):
for value, min, max in self.ranges(self.model):
if self.value() == str(value):
return queryset.filter(
- (f'{self.field_path}__gte', min),
- (f'{self.field_path}__lt', max)
+ (f"{self.field_path}__gte", min),
+ (f"{self.field_path}__lt", max),
)
except (ValueError, ValidationError) as e:
raise IncorrectLookupParameters(e)
return queryset
+
class DateRangeFilter(admin.FieldListFilter):
- template = 'admin/date_range_filter.html'
+ template = "admin/date_range_filter.html"
+
def __init__(self, field, request, params, model, model_admin, field_path):
self.model = model
self.model_admin = model_admin
- self.lookup_kwargs = [f'{field_path}__gte', f'{field_path}__lte']
+ self.lookup_kwargs = [f"{field_path}__gte", f"{field_path}__lte"]
super().__init__(field, request, params, model, model_admin, field_path)
form = self.get_date_form(self.used_parameters)
if form.is_valid():
self.used_parameters = {
- key: value for key,value in form.cleaned_data.items()
+ key: value
+ for key, value in form.cleaned_data.items()
if value is not None
}
else:
@@ -228,16 +246,19 @@ class DateRangeFilter(admin.FieldListFilter):
return self.lookup_kwargs
def choices(self, changelist):
- return [{
- 'query_string': changelist.get_query_string(
- remove=self.lookup_kwargs),
- 'form': self.get_date_form(self.used_parameters)
- }]
+ return [
+ {
+ "query_string": changelist.get_query_string(
+ remove=self.lookup_kwargs
+ ),
+ "form": self.get_date_form(self.used_parameters),
+ }
+ ]
def get_date_form(self, context={}):
- date_fields = {name: forms.DateField(required=False)
- for name in self.lookup_kwargs}
- DateForm = type('DateForm', (forms.Form,), date_fields)
+ date_fields = {
+ name: forms.DateField(required=False) for name in self.lookup_kwargs
+ }
+ DateForm = type("DateForm", (forms.Form,), date_fields)
return DateForm(context)
-
diff --git a/sigi/apps/utils/mixins.py b/sigi/apps/utils/mixins.py
index 7f9f19b..e973c23 100644
--- a/sigi/apps/utils/mixins.py
+++ b/sigi/apps/utils/mixins.py
@@ -18,25 +18,29 @@ from import_export.forms import ExportForm
from import_export.signals import post_export
from sigi.apps.utils import field_label
+
class ValueField(Field):
def get_value(self, obj):
if self.attribute is None:
return None
return obj[self.attribute]
+
class ExportFormFields(ExportForm):
- def __init__(self, formats, field_list, *args, **kwargs):
+ def __init__(self, formats, field_list, *args, **kwargs):
super().__init__(formats, *args, **kwargs)
- self.fields['selected_fields'] = forms.MultipleChoiceField(
- label=_('Campos a exportar'),
+ self.fields["selected_fields"] = forms.MultipleChoiceField(
+ label=_("Campos a exportar"),
required=True,
choices=field_list,
initial=[f[0] for f in field_list],
widget=forms.CheckboxSelectMultiple,
)
+
class LabeledResourse(resources.ModelResource):
selected_fields = None
+
def get_export_headers(self):
headers = []
for field in self.get_export_fields():
@@ -50,14 +54,18 @@ class LabeledResourse(resources.ModelResource):
def get_export_fields(self):
fields = self.get_fields()
if self.selected_fields:
- fields = [f for f in fields
- if self.get_field_name(f) in self.selected_fields]
+ fields = [
+ f
+ for f in fields
+ if self.get_field_name(f) in self.selected_fields
+ ]
return fields
def export(self, queryset=None, selected_fields=None, *args, **kwargs):
self.selected_fields = selected_fields
return super().export(queryset, *args, **kwargs)
+
class ValueLabeledResource(LabeledResourse):
DEFAULT_RESOURCE_FIELD = ValueField
@@ -65,16 +73,17 @@ class ValueLabeledResource(LabeledResourse):
queryset = queryset.values(*selected_fields)
return super().export(queryset, selected_fields, *args, **kwargs)
+
class CartExportMixin(ExportMixin):
- to_encoding = 'utf-8'
- change_list_template = 'admin/cart/change_list_cart_export.html'
+ to_encoding = "utf-8"
+ change_list_template = "admin/cart/change_list_cart_export.html"
_cart_session_name = None
_cart_viewing_name = None
def __init__(self, *args, **kwargs):
super(CartExportMixin, self).__init__(*args, **kwargs)
- self._cart_session_name = 'cart_%s' % self.opts.model_name
- self._cart_viewing_name = 'view_cart_%s' % self.opts.model_name
+ self._cart_session_name = "cart_%s" % self.opts.model_name
+ self._cart_viewing_name = "view_cart_%s" % self.opts.model_name
def get_queryset(self, request):
qs = super(CartExportMixin, self).get_queryset(request)
@@ -85,22 +94,22 @@ class CartExportMixin(ExportMixin):
def get_actions(self, request):
if self._cart_viewing_name in request.session:
- action = self.get_action('remove_from_cart')
+ action = self.get_action("remove_from_cart")
return OrderedDict([(action[1], action)])
else:
if self.actions is None:
self.actions = []
- self.actions.append('add_to_cart')
+ self.actions.append("add_to_cart")
return super(CartExportMixin, self).get_actions(request)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
- if 'cart' in request.GET:
+ if "cart" in request.GET:
request.GET._mutable = True
- cart = request.GET.get('cart', '0')
- request.GET.pop('cart', None)
+ cart = request.GET.get("cart", "0")
+ request.GET.pop("cart", None)
request.GET._mutable = False
- if cart == '1':
+ if cart == "1":
request.session[self._cart_viewing_name] = True
else:
request.session.pop(self._cart_viewing_name, None)
@@ -108,31 +117,33 @@ class CartExportMixin(ExportMixin):
cart_item_count = len(request.session.get(self._cart_session_name, []))
extra_context = extra_context or {}
- extra_context['cart_item_count'] = cart_item_count
+ extra_context["cart_item_count"] = cart_item_count
if self._cart_viewing_name in request.session:
- extra_context['viewing_cart'] = True
- return super(CartExportMixin, self).changelist_view(request, extra_context)
+ extra_context["viewing_cart"] = True
+ return super(CartExportMixin, self).changelist_view(
+ request, extra_context
+ )
def get_urls(self):
urls = super().get_urls()
my_urls = [
- path('clearcart/',
+ path(
+ "clearcart/",
self.admin_site.admin_view(self.clear_cart),
- name='%s_%s_clearcart' % self.get_model_info()),
+ name="%s_%s_clearcart" % self.get_model_info(),
+ ),
]
return my_urls + urls
@csrf_protect_m
def add_to_cart(self, request, queryset):
- if request.POST.get('select_across', '0') == '0':
+ if request.POST.get("select_across", "0") == "0":
selected_ids = set(
request.POST.getlist(helpers.ACTION_CHECKBOX_NAME, [])
)
else:
- selected_ids = set(
- map(str, queryset.values_list('id', flat=True))
- )
+ selected_ids = set(map(str, queryset.values_list("id", flat=True)))
if self._cart_session_name in request.session:
cart_ids = set(request.session[self._cart_session_name])
@@ -145,13 +156,14 @@ class CartExportMixin(ExportMixin):
cart_ids.update(selected_ids)
request.session[self._cart_session_name] = list(cart_ids)
self.message_user(
- request,
- _(u"%s itens adicionados no carrinho") % quant)
+ request, _("%s itens adicionados no carrinho") % quant
+ )
else:
self.message_user(
- request,
- _(u"Os itens selecionados já estavam no carrinho"))
- return HttpResponseRedirect('.')
+ request, _("Os itens selecionados já estavam no carrinho")
+ )
+ return HttpResponseRedirect(".")
+
add_to_cart.short_description = _(
"Armazenar itens no carrinho para exportar"
)
@@ -159,31 +171,35 @@ class CartExportMixin(ExportMixin):
@csrf_protect_m
def remove_from_cart(self, request, queryset):
if self._cart_session_name not in request.session:
- self.message_user(request, _(u"O carrinho está vazio"))
- return HttpResponseRedirect('.')
+ self.message_user(request, _("O carrinho está vazio"))
+ return HttpResponseRedirect(".")
- if request.POST.get('select_across', '0') == '0':
+ if request.POST.get("select_across", "0") == "0":
remove_ids = set(request.POST.getlist(helpers.ACTION_CHECKBOX_NAME))
else:
- remove_ids = set(map(str, queryset.values_list('id', flat=True)))
+ remove_ids = set(map(str, queryset.values_list("id", flat=True)))
cart_ids = set(request.session[self._cart_session_name])
request.session[self._cart_session_name] = list(
cart_ids.difference(remove_ids)
)
- self.message_user(request, _(u"%s itens removidos do carrinho.") %
- len(cart_ids.intersection(remove_ids)))
+ self.message_user(
+ request,
+ _("%s itens removidos do carrinho.")
+ % len(cart_ids.intersection(remove_ids)),
+ )
+
+ return HttpResponseRedirect(".")
- return HttpResponseRedirect('.')
remove_from_cart.short_description = _("Remove itens do carrinho")
@csrf_protect_m
def clear_cart(self, request):
request.session.pop(self._cart_session_name, None)
request.session.pop(self._cart_viewing_name, None)
- self.message_user(request, _(u"Carrinho vazio"))
- return HttpResponseRedirect('..')
+ self.message_user(request, _("Carrinho vazio"))
+ return HttpResponseRedirect("..")
@csrf_protect_m
def export_action(self, request, *args, **kwargs):
@@ -192,13 +208,12 @@ class CartExportMixin(ExportMixin):
formats = self.get_export_formats()
resource = (self.get_export_resource_class())()
- field_list = list(zip(resource.get_export_order(),
- resource.get_export_headers()))
+ field_list = list(
+ zip(resource.get_export_order(), resource.get_export_headers())
+ )
form = ExportFormFields(formats, field_list, request.POST or None)
if form.is_valid():
- file_format = formats[
- int(form.cleaned_data['file_format'])
- ]()
+ file_format = formats[int(form.cleaned_data["file_format"])]()
queryset = self.get_export_queryset(request)
export_data = self.get_export_data(
@@ -206,10 +221,11 @@ class CartExportMixin(ExportMixin):
queryset,
request=request,
encoding=self.to_encoding,
- selected_fields=form.cleaned_data['selected_fields'])
+ selected_fields=form.cleaned_data["selected_fields"],
+ )
content_type = file_format.get_content_type()
response = HttpResponse(export_data, content_type=content_type)
- response['Content-Disposition'] = 'attachment; filename="%s"' % (
+ response["Content-Disposition"] = 'attachment; filename="%s"' % (
self.get_export_filename(request, queryset, file_format),
)
@@ -220,23 +236,25 @@ class CartExportMixin(ExportMixin):
context.update(self.admin_site.each_context(request))
- context['title'] = _("Export")
- context['form'] = form
- context['opts'] = self.model._meta
+ context["title"] = _("Export")
+ context["form"] = form
+ context["opts"] = self.model._meta
request.current_app = self.admin_site.name
- return TemplateResponse(request, [self.export_template_name],
- context)
+ return TemplateResponse(request, [self.export_template_name], context)
+
class CartExportReportMixin(CartExportMixin):
- export_template_name = 'admin/import_export/export_report.html'
+ export_template_name = "admin/import_export/export_report.html"
reports = []
def get_urls(self):
urls = super().get_urls()
my_urls = [
- path('report//',
+ path(
+ "report//",
self.admin_site.admin_view(self.report),
- name='%s_%s_report' % self.get_model_info()),
+ name="%s_%s_report" % self.get_model_info(),
+ ),
]
return my_urls + urls
@@ -248,21 +266,25 @@ class CartExportReportMixin(CartExportMixin):
if report is None:
continue
report_list.append(
- {'name': name,
- 'title': getattr(report, 'title', pretty_name(name)),
- 'icon': getattr(report, 'icon', 'picture_as_pdf')
+ {
+ "name": name,
+ "title": getattr(report, "title", pretty_name(name)),
+ "icon": getattr(report, "icon", "picture_as_pdf"),
}
)
- context['reports'] = report_list
+ context["reports"] = report_list
return context
def report(self, request, name):
- if (name not in self.reports or not hasattr(self, name) or
- not callable(getattr(self, name))):
+ if (
+ name not in self.reports
+ or not hasattr(self, name)
+ or not callable(getattr(self, name))
+ ):
raise Http404(_(f"Report {name} not exists"))
report_view = getattr(self, name)
- return report_view(request)
\ No newline at end of file
+ return report_view(request)
diff --git a/sigi/apps/utils/templatetags/action_icons.py b/sigi/apps/utils/templatetags/action_icons.py
index 5d46a3e..29d5632 100644
--- a/sigi/apps/utils/templatetags/action_icons.py
+++ b/sigi/apps/utils/templatetags/action_icons.py
@@ -3,12 +3,13 @@ from django import template
register = template.Library()
ACTION_LIST = {
- 'delete_selected': 'delete_forever',
- 'add_to_cart': 'add_shopping_cart',
- 'remove_from_cart': 'remove_shopping_cart',
- 'calcular_data_uso': 'functions',
+ "delete_selected": "delete_forever",
+ "add_to_cart": "add_shopping_cart",
+ "remove_from_cart": "remove_shopping_cart",
+ "calcular_data_uso": "functions",
}
+
@register.simple_tag
def action_icon(action_name):
if action_name in ACTION_LIST:
diff --git a/sigi/apps/utils/test_base_admin.py b/sigi/apps/utils/test_base_admin.py
index 2f2f96e..56fd480 100644
--- a/sigi/apps/utils/test_base_admin.py
+++ b/sigi/apps/utils/test_base_admin.py
@@ -2,22 +2,22 @@
def get_li_clear_all_filters(res):
- text = res.html.find(text='Clear All Filters')
- li = text.find_parent('li')
+ text = res.html.find(text="Clear All Filters")
+ li = text.find_parent("li")
assert li
return li
def test_clear_all_filters_is_disabled_if_no_filter_was_used(app):
- res = app.get('/parlamentares/parlamentar/')
+ res = app.get("/parlamentares/parlamentar/")
assert res.status_code == 200
li = get_li_clear_all_filters(res)
- assert 'disabled' in li.attrs['class']
+ assert "disabled" in li.attrs["class"]
def test_clear_all_filters_is_enabled_if_some_filter_was_used(app):
# now we filter by capital letter
- res = app.get('/parlamentares/parlamentar/?nome_completo=B')
+ res = app.get("/parlamentares/parlamentar/?nome_completo=B")
assert res.status_code == 200
li = get_li_clear_all_filters(res)
- assert 'disabled' not in li.attrs['class']
+ assert "disabled" not in li.attrs["class"]
diff --git a/sigi/apps/whois/urls.py b/sigi/apps/whois/urls.py
index 8e6223a..c2e37f1 100644
--- a/sigi/apps/whois/urls.py
+++ b/sigi/apps/whois/urls.py
@@ -4,7 +4,6 @@ from django.views.generic.base import TemplateView
from . import views
urlpatterns = patterns(
- '',
- url(r'^(?P.+)$', views.whois_query),
+ "",
+ url(r"^(?P.+)$", views.whois_query),
)
-
diff --git a/sigi/apps/whois/views.py b/sigi/apps/whois/views.py
index aad3675..8548d1d 100644
--- a/sigi/apps/whois/views.py
+++ b/sigi/apps/whois/views.py
@@ -1,5 +1,5 @@
# coding: utf-8
-from django.http import HttpResponse,HttpResponseBadRequest
+from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
@@ -15,6 +15,7 @@ from collections import OrderedDict
from sigi.apps.servicos.models import *
from sigi.settings import WHOIS_WHITELIST
+
class WhitelistPermission(permissions.BasePermission):
"""
Allow only whitelisted IP addresses
@@ -27,30 +28,33 @@ class WhitelistPermission(permissions.BasePermission):
else:
return False
+
def consulta_valida(consulta):
"""
Determina se uma consulta é válida. Além de ser um domínio válido, deve terminar em uf.leg.br
"""
- regex_dominio=r'^[a-zA-Z\d]{,63}(\.[a-zA-Z\d-]{,63})*.(ac|al|ap|am|ba|ce|df|es|go|ma|mt|ms|mg|pr|pb|pa|pe|pi|rj|rn|rs|ro|rr|sc|se|sp|to).leg.br$'
+ regex_dominio = r"^[a-zA-Z\d]{,63}(\.[a-zA-Z\d-]{,63})*.(ac|al|ap|am|ba|ce|df|es|go|ma|mt|ms|mg|pr|pb|pa|pe|pi|rj|rn|rs|ro|rr|sc|se|sp|to).leg.br$"
m = re.match(regex_dominio, consulta)
if m == None:
return False
return True
+
def match_url_dominio(url, dominio):
"""
Compara o url cadastrado no serviço com o domínio pesquisado.
"""
- url=urlparse(url)
+ url = urlparse(url)
if url.netloc == dominio:
return True
else:
return False
-@api_view(['GET'])
+
+@api_view(["GET"])
@permission_classes([WhitelistPermission])
def whois_query(request, dominio):
"""
@@ -58,9 +62,14 @@ def whois_query(request, dominio):
"""
if not consulta_valida(dominio):
- return Response({'detail':'406 Not Acceptable'}, status=status.HTTP_406_NOT_ACCEPTABLE)
-
- servicos = Servico.objects.filter(tipo_servico__sigla='LEGBR', url__contains=dominio)
+ return Response(
+ {"detail": "406 Not Acceptable"},
+ status=status.HTTP_406_NOT_ACCEPTABLE,
+ )
+
+ servicos = Servico.objects.filter(
+ tipo_servico__sigla="LEGBR", url__contains=dominio
+ )
resposta_dic = OrderedDict()
for s in servicos:
@@ -69,18 +78,22 @@ def whois_query(request, dominio):
if not match_url_dominio(s.url, dominio):
continue
- resposta_dic['_encoding'] = 'utf-8'
- resposta_dic['domain'] = urlparse(s.url).netloc
- resposta_dic['owner'] = "%s - %s " % (s.casa_legislativa.nome, s.casa_legislativa.municipio.uf.sigla)
- resposta_dic['cnpj'] = s.casa_legislativa.cnpj
- resposta_dic['created'] = unicode(s.data_ativacao)
- resposta_dic['modified'] = unicode(s.data_alteracao)
- resposta_dic['tech-name'] = s.contato_tecnico.nome
- resposta_dic['tech-email'] = s.contato_tecnico.email
- resposta_dic['tech-modified'] = unicode(s.contato_tecnico.ult_alteracao)
- resposta_dic['admin-name'] = s.contato_administrativo.nome
- resposta_dic['admin-email'] = s.contato_administrativo.email
- resposta_dic['admin-modified'] = unicode(s.contato_administrativo.ult_alteracao)
+ resposta_dic["_encoding"] = "utf-8"
+ resposta_dic["domain"] = urlparse(s.url).netloc
+ resposta_dic["owner"] = "%s - %s " % (
+ s.casa_legislativa.nome,
+ s.casa_legislativa.municipio.uf.sigla,
+ )
+ resposta_dic["cnpj"] = s.casa_legislativa.cnpj
+ resposta_dic["created"] = unicode(s.data_ativacao)
+ resposta_dic["modified"] = unicode(s.data_alteracao)
+ resposta_dic["tech-name"] = s.contato_tecnico.nome
+ resposta_dic["tech-email"] = s.contato_tecnico.email
+ resposta_dic["tech-modified"] = unicode(s.contato_tecnico.ult_alteracao)
+ resposta_dic["admin-name"] = s.contato_administrativo.nome
+ resposta_dic["admin-email"] = s.contato_administrativo.email
+ resposta_dic["admin-modified"] = unicode(
+ s.contato_administrativo.ult_alteracao
+ )
return Response(resposta_dic, status=status.HTTP_200_OK)
-
diff --git a/sigi/asgi.py b/sigi/asgi.py
index f13aff2..ab3a4fd 100644
--- a/sigi/asgi.py
+++ b/sigi/asgi.py
@@ -11,6 +11,6 @@ import os
from django.core.asgi import get_asgi_application
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sigi.settings')
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sigi.settings")
application = get_asgi_application()
diff --git a/sigi/settings.py b/sigi/settings.py
index 868a034..ac58462 100644
--- a/sigi/settings.py
+++ b/sigi/settings.py
@@ -21,104 +21,109 @@ env = environ.Env()
env.read_env(BASE_DIR / ".env")
# SECURITY WARNING: keep the secret key used in production secret!
-SECRET_KEY = env('SECRET_KEY', default="Unsafe")
+SECRET_KEY = env("SECRET_KEY", default="Unsafe")
# SECURITY WARNING: don't run with debug turned on in production!
-DEBUG = env('DEBUG', default=False, cast=bool)
+DEBUG = env("DEBUG", default=False, cast=bool)
-ALLOWED_HOSTS = ['*']
+ALLOWED_HOSTS = ["*"]
-INTERNAL_IPS = ["127.0.0.1",]
+INTERNAL_IPS = [
+ "127.0.0.1",
+]
-ADMINS = env('ADMINS', eval)
+ADMINS = env("ADMINS", eval)
# Application definition
INSTALLED_APPS = [
- 'sigi.apps.casas',
- 'sigi.apps.contatos',
- 'sigi.apps.convenios',
- 'sigi.apps.eventos',
- 'sigi.apps.home',
- 'sigi.apps.inventario',
- 'sigi.apps.ocorrencias',
- 'sigi.apps.servicos',
- 'sigi.apps.servidores',
- 'sigi.apps.utils',
- 'localflavor',
- 'import_export',
- 'tinymce',
- 'django.forms',
- 'material',
- 'material.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'django_extensions',
+ "sigi.apps.casas",
+ "sigi.apps.contatos",
+ "sigi.apps.convenios",
+ "sigi.apps.eventos",
+ "sigi.apps.home",
+ "sigi.apps.inventario",
+ "sigi.apps.ocorrencias",
+ "sigi.apps.servicos",
+ "sigi.apps.servidores",
+ "sigi.apps.utils",
+ "localflavor",
+ "import_export",
+ "tinymce",
+ "django.forms",
+ "material",
+ "material.admin",
+ "django.contrib.auth",
+ "django.contrib.contenttypes",
+ "django.contrib.sessions",
+ "django.contrib.messages",
+ "django.contrib.staticfiles",
+ "django_extensions",
]
MIDDLEWARE = [
- 'django.middleware.security.SecurityMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.common.CommonMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- 'django.middleware.clickjacking.XFrameOptionsMiddleware',
+ "django.middleware.security.SecurityMiddleware",
+ "django.contrib.sessions.middleware.SessionMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
+ "django.contrib.messages.middleware.MessageMiddleware",
+ "django.middleware.clickjacking.XFrameOptionsMiddleware",
]
if DEBUG:
- INSTALLED_APPS = ['debug_toolbar',] + INSTALLED_APPS
- MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware',] + \
- MIDDLEWARE
-
-EMAIL_PORT=env("EMAIL_PORT", int, default=25)
-EMAIL_HOST=env("EMAIL_HOST", default="")
-EMAIL_HOST_USER=env("EMAIL_HOST_USER", default="")
-EMAIL_HOST_PASSWORD=env("EMAIL_HOST_PASSWORD", default="")
-EMAIL_SUBJECT_PREFIX=env("EMAIL_SUBJECT_PREFIX", default="[SIGI]")
-EMAIL_USE_LOCALTIME=env("EMAIL_USE_LOCALTIME", bool, default=False)
-EMAIL_USE_TLS=env("EMAIL_USE_TLS", bool, default=False)
-EMAIL_USE_SSL=env("EMAIL_USE_SSL", bool, default=False)
-EMAIL_TIMEOUT=env("EMAIL_TIMEOUT", int, default=None)
+ INSTALLED_APPS = [
+ "debug_toolbar",
+ ] + INSTALLED_APPS
+ MIDDLEWARE = [
+ "debug_toolbar.middleware.DebugToolbarMiddleware",
+ ] + MIDDLEWARE
+
+EMAIL_PORT = env("EMAIL_PORT", int, default=25)
+EMAIL_HOST = env("EMAIL_HOST", default="")
+EMAIL_HOST_USER = env("EMAIL_HOST_USER", default="")
+EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD", default="")
+EMAIL_SUBJECT_PREFIX = env("EMAIL_SUBJECT_PREFIX", default="[SIGI]")
+EMAIL_USE_LOCALTIME = env("EMAIL_USE_LOCALTIME", bool, default=False)
+EMAIL_USE_TLS = env("EMAIL_USE_TLS", bool, default=False)
+EMAIL_USE_SSL = env("EMAIL_USE_SSL", bool, default=False)
+EMAIL_TIMEOUT = env("EMAIL_TIMEOUT", int, default=None)
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
- 'default': env.db(),
+ "default": env.db(),
}
-ROOT_URLCONF = 'sigi.urls'
+ROOT_URLCONF = "sigi.urls"
TEMPLATES = [
{
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [BASE_DIR / 'templates'],
- 'APP_DIRS': True,
- 'OPTIONS': {
- 'context_processors': [
- 'django.template.context_processors.debug',
- 'django.template.context_processors.request',
- 'django.contrib.auth.context_processors.auth',
- 'django.contrib.messages.context_processors.messages',
- 'django.template.context_processors.media',
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
+ "DIRS": [BASE_DIR / "templates"],
+ "APP_DIRS": True,
+ "OPTIONS": {
+ "context_processors": [
+ "django.template.context_processors.debug",
+ "django.template.context_processors.request",
+ "django.contrib.auth.context_processors.auth",
+ "django.contrib.messages.context_processors.messages",
+ "django.template.context_processors.media",
],
},
},
]
-FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
+FORM_RENDERER = "django.forms.renderers.TemplatesSetting"
-WSGI_APPLICATION = 'sigi.wsgi.application'
+WSGI_APPLICATION = "sigi.wsgi.application"
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
-LANGUAGE_CODE = 'pt-br'
+LANGUAGE_CODE = "pt-br"
TIME_ZONE = "America/Sao_Paulo"
@@ -135,69 +140,70 @@ USE_THOUSAND_SEPARATOR = True
AUTH_PASSWORD_VALIDATORS = [
{
- 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
+ "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
- 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+ "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
- 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
+ "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
- 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
+ "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
-if env('AUTH_LDAP_SERVER_URI', default=None):
+if env("AUTH_LDAP_SERVER_URI", default=None):
AUTHENTICATION_BACKENDS = [
"django_auth_ldap.backend.LDAPBackend",
"django.contrib.auth.backends.ModelBackend",
]
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
import ldap
- AUTH_LDAP_SERVER_URI = env('AUTH_LDAP_SERVER_URI')
- AUTH_LDAP_BIND_DN = env('AUTH_LDAP_BIND_DN')
- AUTH_LDAP_BIND_PASSWORD = env('AUTH_LDAP_BIND_PASSWORD')
- AUTH_LDAP_USER = env('AUTH_LDAP_USER')
+
+ AUTH_LDAP_SERVER_URI = env("AUTH_LDAP_SERVER_URI")
+ AUTH_LDAP_BIND_DN = env("AUTH_LDAP_BIND_DN")
+ AUTH_LDAP_BIND_PASSWORD = env("AUTH_LDAP_BIND_PASSWORD")
+ AUTH_LDAP_USER = env("AUTH_LDAP_USER")
AUTH_LDAP_USER_SEARCH = LDAPSearch(
- AUTH_LDAP_USER,
- ldap.SCOPE_SUBTREE,
- env('AUTH_LDAP_USER_SEARCH_STRING')
+ AUTH_LDAP_USER, ldap.SCOPE_SUBTREE, env("AUTH_LDAP_USER_SEARCH_STRING")
)
- AUTH_LDAP_GROUP = env('AUTH_LDAP_GROUP')
+ AUTH_LDAP_GROUP = env("AUTH_LDAP_GROUP")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
AUTH_LDAP_GROUP,
ldap.SCOPE_SUBTREE,
- env('AUTH_LDAP_GROUP_SEARCH_STRING')
+ env("AUTH_LDAP_GROUP_SEARCH_STRING"),
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(
- name_attr=env('AUTH_LDAP_GROUP_TYPE_STRING')
+ name_attr=env("AUTH_LDAP_GROUP_TYPE_STRING")
)
- AUTH_LDAP_USER_ATTR_MAP = env('AUTH_LDAP_USER_ATTR_MAP', cast=eval)
- AUTH_LDAP_PROFILE_ATTR_MAP = env('AUTH_LDAP_PROFILE_ATTR_MAP', eval)
- AUTH_LDAP_FIND_GROUP_PERMS = env('AUTH_LDAP_FIND_GROUP_PERMS', bool)
- AUTH_LDAP_MIRROR_GROUPS = env('AUTH_LDAP_MIRROR_GROUPS', bool)
- AUTH_LDAP_CACHE_GROUPS = env('AUTH_LDAP_CACHE_GROUPS', bool)
- AUTH_LDAP_GROUP_CACHE_TIMEOUT = env('AUTH_LDAP_GROUP_CACHE_TIMEOUT', int)
- AUTH_PROFILE_MODULE = env('AUTH_PROFILE_MODULE')
+ AUTH_LDAP_USER_ATTR_MAP = env("AUTH_LDAP_USER_ATTR_MAP", cast=eval)
+ AUTH_LDAP_PROFILE_ATTR_MAP = env("AUTH_LDAP_PROFILE_ATTR_MAP", eval)
+ AUTH_LDAP_FIND_GROUP_PERMS = env("AUTH_LDAP_FIND_GROUP_PERMS", bool)
+ AUTH_LDAP_MIRROR_GROUPS = env("AUTH_LDAP_MIRROR_GROUPS", bool)
+ AUTH_LDAP_CACHE_GROUPS = env("AUTH_LDAP_CACHE_GROUPS", bool)
+ AUTH_LDAP_GROUP_CACHE_TIMEOUT = env("AUTH_LDAP_GROUP_CACHE_TIMEOUT", int)
+ AUTH_PROFILE_MODULE = env("AUTH_PROFILE_MODULE")
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
-STATIC_URL = 'static/'
-STATICFILES_DIRS = [BASE_DIR / "static",]
-STATIC_ROOT = BASE_DIR / '../static/'
+STATIC_URL = "static/"
+STATICFILES_DIRS = [
+ BASE_DIR / "static",
+]
+STATIC_ROOT = BASE_DIR / "../static/"
# Media files
# https://docs.djangoproject.com/en/4.0/topics/files/#managing-files
-MEDIA_ROOT = BASE_DIR / '../media'
+MEDIA_ROOT = BASE_DIR / "../media"
MEDIA_URL = "media/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
-DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
+DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Django import-export settings
# https://django-import-export.readthedocs.io/en/latest/installation.html#settings
@@ -209,18 +215,18 @@ IMPORT_EXPORT_SKIP_ADMIN_LOG = True
# https://github.com/MaistrenkoAnton/django-material-admin#django-material-administration
MATERIAL_ADMIN_SITE = {
- 'HEADER': _('SIGI - Sistema de Informações do Interlegis'),
- 'TITLE': _('SIGI'),
- 'FAVICON': 'img/favicon.ico',
- 'PROFILE_PICTURE': 'img/interlegis.jpeg', # Admin site profile picture (path to static should be specified)
- 'PROFILE_BG': 'img/engitec.jpeg', # Admin site profile background (path to static should be specified)
- 'LOGIN_LOGO': 'img/interlegis.jpeg', # Admin site logo on login page (path to static should be specified)
- 'LOGOUT_BG': 'img/engitec.jpeg', # Admin site background on login/logout pages (path to static should be specified)
- 'SHOW_THEMES': False, # Show default admin themes button
- 'TRAY_REVERSE': False, # Hide object-tools and additional-submit-line by default
- 'NAVBAR_REVERSE': False, # Hide side navbar by default
+ "HEADER": _("SIGI - Sistema de Informações do Interlegis"),
+ "TITLE": _("SIGI"),
+ "FAVICON": "img/favicon.ico",
+ "PROFILE_PICTURE": "img/interlegis.jpeg", # Admin site profile picture (path to static should be specified)
+ "PROFILE_BG": "img/engitec.jpeg", # Admin site profile background (path to static should be specified)
+ "LOGIN_LOGO": "img/interlegis.jpeg", # Admin site logo on login page (path to static should be specified)
+ "LOGOUT_BG": "img/engitec.jpeg", # Admin site background on login/logout pages (path to static should be specified)
+ "SHOW_THEMES": False, # Show default admin themes button
+ "TRAY_REVERSE": False, # Hide object-tools and additional-submit-line by default
+ "NAVBAR_REVERSE": False, # Hide side navbar by default
}
# SIGI specific settings
-MENU_FILE = BASE_DIR / 'menu_conf.yaml'
+MENU_FILE = BASE_DIR / "menu_conf.yaml"
diff --git a/sigi/shortcuts.py b/sigi/shortcuts.py
index 4f31978..9a5ab7d 100644
--- a/sigi/shortcuts.py
+++ b/sigi/shortcuts.py
@@ -16,30 +16,33 @@ import ho.pisa as pisa
def fetch_resources(uri, rel):
if uri.find(settings.STATIC_URL) != -1:
# Imagem está em STATIC_ROOT
- path = os.path.join(settings.STATIC_ROOT,
- uri.replace(settings.STATIC_URL, ""))
+ path = os.path.join(
+ settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, "")
+ )
else:
# Imagem está em MEDIA_ROOT
- path = os.path.join(settings.MEDIA_ROOT,
- uri.replace(settings.MEDIA_URL, ""))
+ path = os.path.join(
+ settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")
+ )
return path
-def pdf_renderer(template, context, filename='report.pdf'):
+
+def pdf_renderer(template, context, filename="report.pdf"):
html = template.render(context)
- response = HttpResponse(content_type='application/pdf')
- response['Content-Disposition'] = 'attachment; filename=' + filename
+ response = HttpResponse(content_type="application/pdf")
+ response["Content-Disposition"] = "attachment; filename=" + filename
- pdf = pisa.CreatePDF(html, dest=response,
- link_callback=fetch_resources)
+ pdf = pisa.CreatePDF(html, dest=response, link_callback=fetch_resources)
if pdf.err:
- return HttpResponse(_(u'We had some errors%s ') % escape(html))
+ return HttpResponse(_("We had some errors%s ") % escape(html))
return response
+
def render_to_pdf(template_src, context_dict):
- filename = template_src.replace('.html', '').replace('_pdf', '.pdf')
+ filename = template_src.replace(".html", "").replace("_pdf", ".pdf")
template = get_template(template_src)
context = Context(context_dict)
- return pdf_renderer(template, context,filename)
\ No newline at end of file
+ return pdf_renderer(template, context, filename)
diff --git a/sigi/test_cart.py b/sigi/test_cart.py
index eb4df2f..f7e1c76 100644
--- a/sigi/test_cart.py
+++ b/sigi/test_cart.py
@@ -2,27 +2,47 @@
import pytest
from sigi.apps.casas.test_casas import some_parliaments, parliaments_from_names
-from sigi.apps.parlamentares.test_parlamentares import some_parliamentarians, parliamentarians_from_names
+from sigi.apps.parlamentares.test_parlamentares import (
+ some_parliamentarians,
+ parliamentarians_from_names,
+)
from sigi.testutils import pdf_text
-@pytest.mark.parametrize("url, some_entries, form_action, name_attr, verbose_name_plural", [
- ('/parlamentares/parlamentar/', some_parliamentarians, 'adiciona_parlamentar', 'nome_completo', 'Parlamentares'),
- ('/casas/orgao/', some_parliaments, 'adicionar_casas', 'nome', 'Casas Legislativas'),
-])
-def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plural, app):
+@pytest.mark.parametrize(
+ "url, some_entries, form_action, name_attr, verbose_name_plural",
+ [
+ (
+ "/parlamentares/parlamentar/",
+ some_parliamentarians,
+ "adiciona_parlamentar",
+ "nome_completo",
+ "Parlamentares",
+ ),
+ (
+ "/casas/orgao/",
+ some_parliaments,
+ "adicionar_casas",
+ "nome",
+ "Casas Legislativas",
+ ),
+ ],
+)
+def test_add_to_cart(
+ url, some_entries, form_action, name_attr, verbose_name_plural, app
+):
a, b, c = some_entries()
res = app.get(url)
assert res.status_code == 200
- form = res.forms['changelist-form']
- form['_selected_action'] = [a.pk, b.pk] # Andre and Bartolomeu
- form['action'] = form_action
+ form = res.forms["changelist-form"]
+ form["_selected_action"] = [a.pk, b.pk] # Andre and Bartolomeu
+ form["action"] = form_action
res = form.submit()
"2 %s adicionados" % verbose_name_plural in res.content
- res = app.get(url + 'carrinho/')
+ res = app.get(url + "carrinho/")
def right_people_present(content):
assert getattr(a, name_attr) in content
@@ -30,66 +50,90 @@ def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plu
assert getattr(c, name_attr) not in content
right_people_present(res.content)
- 'Formato da Etiqueta' in res.content
- 'Gerar Etiqueta' in res.content
- labels_form = res.forms['generate_labels']
+ "Formato da Etiqueta" in res.content
+ "Gerar Etiqueta" in res.content
+ labels_form = res.forms["generate_labels"]
res = labels_form.submit()
- assert res.content_type == 'application/pdf'
+ assert res.content_type == "application/pdf"
text = pdf_text(res)
right_people_present(text)
-@pytest.mark.parametrize("url, some_entries, all_expression", [
- ('/parlamentares/parlamentar/', some_parliamentarians, 'todos os parlamentares', ),
- ('/casas/orgao/', some_parliaments, 'todas as casas', ),
-])
-def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_expression, app):
+@pytest.mark.parametrize(
+ "url, some_entries, all_expression",
+ [
+ (
+ "/parlamentares/parlamentar/",
+ some_parliamentarians,
+ "todos os parlamentares",
+ ),
+ (
+ "/casas/orgao/",
+ some_parliaments,
+ "todas as casas",
+ ),
+ ],
+)
+def test_no_selection_brings_everyone_to_the_cart(
+ url, some_entries, all_expression, app
+):
some_entries()
- res = app.get(url + 'carrinho/')
+ res = app.get(url + "carrinho/")
assert res.status_code == 200
- msg = 'O carrinho está vazio, sendo assim %s entram na lista para exportação' % all_expression
+ msg = (
+ "O carrinho está vazio, sendo assim %s entram na lista para exportação"
+ % all_expression
+ )
assert msg in res.content
-@pytest.mark.parametrize("url, generate_entries", [
- ('/parlamentares/parlamentar/', parliamentarians_from_names, ),
- ('/casas/orgao/', parliaments_from_names, ),
-])
+@pytest.mark.parametrize(
+ "url, generate_entries",
+ [
+ (
+ "/parlamentares/parlamentar/",
+ parliamentarians_from_names,
+ ),
+ (
+ "/casas/orgao/",
+ parliaments_from_names,
+ ),
+ ],
+)
def test_pagination(url, generate_entries, app, live_server):
-
def assert_on_page_1(res):
- assert len(res.pyquery('.result_list tbody tr')) == 100
- assert 'Página 1 de 2' in res.content
- assert '112 itens' in res.content
- assert 'Anterior' not in res.content
- link = res.html.find('a', text='Próxima')
- assert link.attrs['href'] == '?page=2'
+ assert len(res.pyquery(".result_list tbody tr")) == 100
+ assert "Página 1 de 2" in res.content
+ assert "112 itens" in res.content
+ assert "Anterior" not in res.content
+ link = res.html.find("a", text="Próxima")
+ assert link.attrs["href"] == "?page=2"
def assert_on_page_2(res):
- assert len(res.pyquery('.result_list tbody tr')) == 12
- assert 'Página 2 de 2' in res.content
- assert '112 itens' in res.content
- assert 'Próxima' not in res.content
- link = res.html.find('a', text='Anterior')
- assert link.attrs['href'] == '?page=1'
+ assert len(res.pyquery(".result_list tbody tr")) == 12
+ assert "Página 2 de 2" in res.content
+ assert "112 itens" in res.content
+ assert "Próxima" not in res.content
+ link = res.html.find("a", text="Anterior")
+ assert link.attrs["href"] == "?page=1"
generate_entries(range(112))
- url_cart = url + 'carrinho/'
+ url_cart = url + "carrinho/"
res = app.get(url_cart)
assert res.status_code == 200
assert_on_page_1(res)
- res = app.get(url_cart + '?page=2')
+ res = app.get(url_cart + "?page=2")
assert_on_page_2(res)
# if the argument is too big we land on the last page
- res = app.get(url_cart + '?page=1000')
+ res = app.get(url_cart + "?page=1000")
assert_on_page_2(res)
# if the argument is not a number we land on the first page
- res = app.get(url + 'carrinho/?page=aaaa')
+ res = app.get(url + "carrinho/?page=aaaa")
assert_on_page_1(res)
diff --git a/sigi/test_testutils.py b/sigi/test_testutils.py
index 7b75ec4..d020f6c 100644
--- a/sigi/test_testutils.py
+++ b/sigi/test_testutils.py
@@ -3,15 +3,74 @@ from collections import namedtuple
from sigi.testutils import SigiDataFixture
-FieldStub = namedtuple('FieldStub', ['max_length'])
+FieldStub = namedtuple("FieldStub", ["max_length"])
def test_sigidatafixture():
data_fixture = SigiDataFixture()
field1 = FieldStub(max_length=1)
- assert ['A', 'B', 'C'] == [data_fixture.charfield_config(field1, "") for i in range(3)]
+ assert ["A", "B", "C"] == [
+ data_fixture.charfield_config(field1, "") for i in range(3)
+ ]
field2 = FieldStub(max_length=2)
- pairs = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB']
- assert pairs == [data_fixture.charfield_config(field2, "") for i in range(len(pairs))]
+ pairs = [
+ "AA",
+ "AB",
+ "AC",
+ "AD",
+ "AE",
+ "AF",
+ "AG",
+ "AH",
+ "AI",
+ "AJ",
+ "AK",
+ "AL",
+ "AM",
+ "AN",
+ "AO",
+ "AP",
+ "AQ",
+ "AR",
+ "AS",
+ "AT",
+ "AU",
+ "AV",
+ "AW",
+ "AX",
+ "AY",
+ "AZ",
+ "BA",
+ "BB",
+ "BC",
+ "BD",
+ "BE",
+ "BF",
+ "BG",
+ "BH",
+ "BI",
+ "BJ",
+ "BK",
+ "BL",
+ "BM",
+ "BN",
+ "BO",
+ "BP",
+ "BQ",
+ "BR",
+ "BS",
+ "BT",
+ "BU",
+ "BV",
+ "BW",
+ "BX",
+ "BY",
+ "BZ",
+ "CA",
+ "CB",
+ ]
+ assert pairs == [
+ data_fixture.charfield_config(field2, "") for i in range(len(pairs))
+ ]
diff --git a/sigi/testutils.py b/sigi/testutils.py
index bae2f14..ca546d6 100644
--- a/sigi/testutils.py
+++ b/sigi/testutils.py
@@ -3,13 +3,15 @@ from cStringIO import StringIO
from itertools import product
import pyPdf
-from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture
+from django_dynamic_fixture.fixture_algorithms.sequential_fixture import (
+ SequentialDataFixture,
+)
def pdf_text(res):
content_as_file = StringIO(res.content)
pdf = pyPdf.PdfFileReader(content_as_file)
- pdf_text = '\n'.join([page.extractText() for page in pdf.pages])
+ pdf_text = "\n".join([page.extractText() for page in pdf.pages])
return pdf_text
@@ -24,11 +26,11 @@ class SigiDataFixture(SequentialDataFixture):
def get_word_generator(self, length):
gen = self.word_generators.get(length)
if not gen:
- gen = (''.join(i) for i in product(self.alphabet, repeat=length))
+ gen = ("".join(i) for i in product(self.alphabet, repeat=length))
self.word_generators[length] = gen
return gen
def charfield_config(self, field, key):
- length = field.max_length or 100 # XXX leave this 100 hardcoded?
+ length = field.max_length or 100 # XXX leave this 100 hardcoded?
gen = self.get_word_generator(length)
return gen.next()
diff --git a/sigi/urls.py b/sigi/urls.py
index 5d8b61e..c2f419f 100644
--- a/sigi/urls.py
+++ b/sigi/urls.py
@@ -19,16 +19,18 @@ from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
- path('admin/casas/', include('sigi.apps.casas.urls')),
- path('admin/convenios/', include('sigi.apps.convenios.urls')),
- path('admin/ocorrencias/', include('sigi.apps.ocorrencias.urls')),
- path('admin/eventos/', include('sigi.apps.eventos.urls')),
- path('admin/', admin.site.urls),
- path('tinymce/', include('tinymce.urls')),
- path('', include('sigi.apps.home.urls')),
+ path("admin/casas/", include("sigi.apps.casas.urls")),
+ path("admin/convenios/", include("sigi.apps.convenios.urls")),
+ path("admin/ocorrencias/", include("sigi.apps.ocorrencias.urls")),
+ path("admin/eventos/", include("sigi.apps.eventos.urls")),
+ path("admin/", admin.site.urls),
+ path("tinymce/", include("tinymce.urls")),
+ path("", include("sigi.apps.home.urls")),
]
if settings.DEBUG:
- urlpatterns = urlpatterns + [
- path('__debug__/', include('debug_toolbar.urls'))
- ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+ urlpatterns = (
+ urlpatterns
+ + [path("__debug__/", include("debug_toolbar.urls"))]
+ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+ )
diff --git a/sigi/wsgi.py b/sigi/wsgi.py
index 49bdee2..42f6aaf 100644
--- a/sigi/wsgi.py
+++ b/sigi/wsgi.py
@@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sigi.settings')
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sigi.settings")
application = get_wsgi_application()